<?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(); 

 define('SERVICES_CONDITION_STATUS'," and (se.service_status>=1) and date_format(se.service_date_available,'%Y-%m-%d')<='".getServerDate()."'");
 // send event test sms email
	function tep_draw_date_field($name,$default,$parameters){
	 global $date_format,$formname;
	 
	 $result=tep_draw_input_field($name,$default,$parameters,false,'text',false);
	 $result.='&nbsp;<a href="javascript:show_calendar(\'' . sprintf("%s.%s",$formname,$name) . '\',null,null,\'' . $date_format . '\');"' .
			' onmouseover="window.status=\'Date Picker\';return true;" onmouseout="window.status=\'\';return true;"><img border="none" src="images/icon_calendar.gif" valign="middle"/></a>';
	 return $result;
  }
 
  function tep_draw_time_field($name,$select_time=""){
  	global $hour_array,$minute_array,$daynight_array;
	if (!is_array($hour_array)){
		$hour_array=array();
		for($icnt=1;$icnt<=12;$icnt++){
		  $temp=sprintf("%02s",$icnt);
		  $hour_array[]=array('id'=>$temp,'text'=>$temp);
		}
		
		$minute_array=array();
		for($icnt=0;$icnt<=59;$icnt=$icnt+5){
		  $temp=sprintf("%02s",$icnt);
		  $minute_array[]=array('id'=>$temp,'text'=>$temp);
		}
		
		$daynight_array=array(array('id'=>'AM','text'=>'AM'),array('id'=>'PM','text'=>'PM'));
	}
  	if ($select_time=="") $select_time="00:00";
  	$select_arr=$select_time;
	if (!is_array($select_arr)) $select_arr=split(":",$select_time);
	
	if ((int)$select_arr[0]>12) {
		$select_arr[0]=$select_arr[0]-12;
		$select_arr[2]="PM";
	} else if ($select_arr[0]==12 && $select_arr[1]>0) {
	   	$select_arr[2]="PM";
	}
	$result=tep_draw_pull_down_menu($name . "_h",$hour_array,$select_arr[0]) . '&nbsp;';
	$result.=tep_draw_pull_down_menu($name . "_m",$minute_array,$select_arr[1]) . '&nbsp;';

	$result.=tep_draw_pull_down_menu($name . "_d",$daynight_array,$select_arr[2]);
	
	return $result;
  } 
  
  function tep_prepare_time($name){
  	global $HTTP_POST_VARS;
  	$hour=tep_db_prepare_input($HTTP_POST_VARS[$name . '_h']);
	$minute=tep_db_prepare_input($HTTP_POST_VARS[$name. '_m']);
	$daynight=tep_db_prepare_input($HTTP_POST_VARS[$name. '_d']);
	if ($hour>=24 || $hour<0) $hour=23;
	if ($min<0 || $min>60) $minute=60;
	if ($daynight=="PM"){
		if ($hour<=12) $hour=$hour+12;
	}
	if($daynight=="AM" && $hour==12) $hour='00';
	if($daynight=="PM" && $hour==24) $hour='12';
	return tep_output_string($hour) .":" . tep_output_string($minute) . ":00";
  }
  function tep_prepare_date($date_val){
  	$date_val=tep_db_prepare_input($date_val);
	$date_val=tep_convert_date_raw($date_val);
	if ($date_val<getServerDate()) $date_val=getServerDate();
	return $date_val;
  }
  
 function tep_draw_date_combo_select($types,$selectname,$valueselect)
  {
    $result='';
    if ($types=='weeks') 
	{
      $element=array('0'=>'first','1'=>'second','2'=>'third','3'=>'fourth');
	}
	elseif ($types=='months')
	{
	  $element=array('0'=>'January','1'=>'February','2'=>'March','3'=>'April',
				  '4'=>'May','5'=>'June','6'=>'July','7'=>'August','8'=>'September',
				  '9'=>'October','10'=>'November','11'=>'December');
	}
	else{
	  $element=array('0'=>'Sunday','1'=>'Monday','2'=>'Tuesday','3'=>'Wednesday','4'=>'Thursday',
	                 '5'=>'Friday','6'=>'Saturday');}
	$result='<select id="'.$selectname.'" name="'. $selectname . '">';
	for($icnt=0,$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;
  } 
    
 function get_total_service_booking_dates($service_id,$languages_id,$type='total_time'){
  	global $date_begin,$date_end,$booking_type,$sInfo,$nb_dates,$recurring_type,$quantity,$select;
	
	$service_total=tep_time_diff($date_begin.' '.'00:00:00',$date_end.' '.'23:59:59');
	if($booking_type=='M')
		$service_total_time=$service_total["minutes"];
	else if($booking_type=='H')
		$service_total_time=round(24*$service_total["days"]);
 	else if($booking_type=='D') 
 		$service_total_time=round($service_total["days"]); 
			
			
 	if($service_id=='' && $languages_id=='') return;
 	$no_booking_sql="select recurring_type,recurring_details,sd.service_name,no_booking_start_date,
	no_booking_end_date,no_booking_start_time,no_booking_end_time,recurring_type,recurring_details 
	from ".TABLE_SERVICES_NO_BOOKING_DAYS ." snd," .TABLE_SERVICES_DESCRIPTION.   " sd where 
	snd.service_id ='".$service_id."' and sd.language_id='" . $languages_id . "' and (('$date_begin'>=snd.no_booking_start_date and '$date_begin'<=snd.no_booking_start_date) OR  ('$date_end'>=snd.no_booking_start_date and '$date_end'<=snd.no_booking_end_date) OR ('$date_begin'<=snd.no_booking_start_date and '$date_end'>=snd.no_booking_end_date)) and sd.service_id=snd.service_id order by 
	recurring_type,no_booking_end_date";
		
	$bk_query=tep_db_query($no_booking_sql);
	$dates=array();
	$n_dates=array();
	$block_dates=array();
	$nbd_array=array();
	$return="";
	if(tep_db_num_rows($bk_query)>0){
		while($nbk=tep_db_fetch_array($bk_query)){
			$sInfo=new objectInfo($nbk);
			$recurring_type=$sInfo->recurring_type;
			$nb_dates=service_get_dates_array($sInfo,$recurring_type);
			$recurring_type=$nbk['recurring_type'];
			$ser_id=$service_id;
			$type_start_date=$date_begin; 
			$type_end_date=$date_end;
			$nbd_array[]=formated_type_dates('dates');
		}
	}
	if(sizeof($nbd_array)>0){
	 for($i=0;$i<=sizeof($nbd_array);$i++){
		for($j=0;$j<=sizeof($nbd_array[$i]);$j++){
			if($service_result['booking_type']=='D'){
				$nbd_array[$i][$j]['n_s_time']="00:00:00";
				$nbd_array[$i][$j]['n_e_time']="23:59:00";
			}	
			$block_dates[]=array('s_date'=>$nbd_array[$i][$j]['n_s_date'],'e_date'=>$nbd_array[$i][$j]['n_e_date'],'s_time'=>$nbd_array[$i][$j]['n_s_time'],'e_time'=>$nbd_array[$i][$j]['n_e_time']);
		}
	 }
	}
	
	$total_block=0;
	for($ic=0;$ic<sizeof($block_dates);$ic++){
	   $no_booking_start_date=$block_dates[$ic]['s_date'];
	   $no_booking_start_time=$block_dates[$ic]['s_time'];
	   $no_booking_end_date=$block_dates[$ic]['e_date'];
	   $no_booking_end_time=$block_dates[$ic]['e_time'];
	   if($no_booking_end_time=='24:00:00') $no_booking_end_time="23:59:00";
	     if($date_begin<=$no_booking_start_date && $date_end>=$no_booking_end_date){
	        	$nbdiff=tep_time_diff($no_booking_start_date . ' ' . $no_booking_start_time,$no_booking_end_date. ' ' . $no_booking_end_time);		
			if($booking_type=='M')
				$total_block+=round($nbdiff['minutes']);
			else if($booking_type=='H')
				$total_block+=round($nbdiff['hours']);
			else if($booking_type=='D')
				$total_block+=$nbdiff['days'];
			
		 }
	}	
	
	if($type=='sale_time'){
	$check="";
	   if($select=='-1'){
	   	$check=" and (o.orders_status>1 or date_add(o.date_purchased,interval se.pending_period day)>'" . getServerDate(true) . "' and op.orders_products_status!=5 )"; 	
  		}
  		$sale_query=tep_db_query("select os.start_date,os.start_time,os.end_date,os.end_time,sum(op.products_quantity) as quantity from ".TABLE_ORDERS." o, " . TABLE_ORDERS_SERVICES." os, ".TABLE_ORDERS_PRODUCTS." op," .	TABLE_SERVICES ." se  where se.service_id=op.products_id and se.service_id=os.products_id and o.orders_id=op.orders_id and op.orders_id=os.orders_id and o.orders_id=os.orders_id and op.orders_products_id=os.orders_products_id and op.products_type='V' and (('$date_begin'>=os.start_date and '$date_begin'<=os.end_date) OR ('$date_end'>=os.start_date and '$date_end'<=os.end_date) OR ('$date_begin'<=os.start_date AND '$date_end'>=os.end_date)) and op.products_id='".(int)$service_id."'". $check ." group by os.start_date,os.start_time,os.end_date,os.end_time order by os.start_date,os.start_time"); 
		if(tep_db_num_rows($sale_query)){
		$sale_dates=array();
		 while($sale=tep_db_fetch_array($sale_query)){
				$start_date=$sale["start_date"];
				$start_time=$sale["start_time"];
				$end_date=$sale["end_date"];
				$end_time=$sale["end_time"];
				$quantity=$sale['quantity']; 
				if($start_date<$end_date){
					if($end_date==date("Y-m-d",dateadd(@strtotime($start_date),"day",1))){
						$sale_dates[]=array('dates'=>$start_date,'start_time'=>$start_time,'end_time'=>'23:59:59','quantity'=>$quantity);
						$sale_dates[sizeof($sale_dates)]=array('dates'=>$end_date,'start_time'=>'00:00:00','end_time'=>$end_time,'quantity'=>$quantity);
					}else  {
					   $temp_date=$start_date;
					   $temp_date=$start_date;
					    while(@strtotime($temp_date)<=@strtotime($end_date)){
						   if($temp_date==$start_date){
								$sale_dates[]=array('start_date'=>$start_date,'start_time'=>$start_time,'end_time'=>'23:59:59','quantity'=>$quantity);
								$sale_dates[sizeof($sale_dates)]=array('start_date'=>$end_date,'start_time'=>'00:00:00','end_time'=>$end_time,'quantity'=>$quantity);
							}else if($temp_date==$end_date){
								$sale_dates[]=array('start_date'=>$start_date,'start_time'=>$start_time,'end_time'=>$end_time,'quantity'=>$quantity);			
							}else {
								$sale_dates[]=array('start_date'=>$start_date,'start_time'=>$start_time,'end_time'=>$end_time,'quantity'=>$quantity);	
							}
							$temp_date=date("Y-m-d",dateadd(@strtotime($temp_date),"day",1));
						} 
				  }
				}else if($sale["start_date"]==$sale["end_date"]) {
					/*	$ret1=tep_time_diff($start_date.' '.$start_time,$end_date.' '. $end_time);
						$tot_time=round($sale["quantity"] * $ret1["hours"]); 
						if($booking_type=='D')	$tot_time=round($sale["quantity"] * $ret1["days"]);
					*/				 				
					$sale_dates[]=array('start_date'=>$start_date,'start_time'=>$start_time,'end_time'=>$end_time,'quantity'=>$quantity);
				}		
			}
		}
	}
	$tot_time="";
		
	for($i=0;$i<sizeof($sale_dates);$i++){
		if($sale_dates[$i]['start_date']<=$date_end && $sale_dates[$i]['start_date']>=$date_begin){
			$ret1=tep_time_diff($sale_dates[$i]['start_date'].' '.$sale_dates[$i]['start_time'],$sale_dates[$i]['start_date'].' '. $sale_dates[$i]['end_time']);
			if($booking_type=='M')
				$tot_time+=round($sale_dates[$i]["quantity"] * $ret1["minutes"]);
			else if($booking_type=='H')
				$tot_time+=round($sale_dates[$i]["quantity"] * $ret1["hours"]);
			else if($booking_type=='D')
				$tot_time+=round($sale_dates[$i]["quantity"] * $ret1["days"]);
		}
	}
	$return="0";
	if($type=='total_time'){
	//if($service_id=='18')
		//echos($service_total_time . '-' . $total_block);
		if($service_total_time>=$total_block)  {
			$return_ti=round($service_total_time-$total_block) ;
		}
		$return=(($quantity)?$quantity * $return_ti:$return_ti);  
		
	}else if($type=='sale_time') {
		$return=$tot_time;
	}
	
	return $return;
}
function tep_send_service_test_sms_email($mail_type,$service_id)
{
  if ($mail_type=='' || (int)$service_id<=0)
     return;

   $mail_data_query=tep_db_query("SELECT message_text from " . TABLE_SERVICES_SMS_MESSAGES . " where message_type='" . $mail_type . "' and service_id='" . (int)$service_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);
}

// get service description by passing service_id
 function tep_get_resource_description($resource_id, $language_id=0) {
	global $languages_id;
	if ($language_id == 0) $language_id = $languages_id;
    $resource_query = tep_db_query("select resource_description from " . TABLE_RESOURCES_DESCRIPTION . " where resource_id = '" . (int)$resource_id . "' and language_id = '" . (int)$language_id . "'");
    $resource = tep_db_fetch_array($resource_query);

    return $resource['resource_description'];
  }
  
   function tep_get_resource_name($resource_id, $language_id=0) {
	global $languages_id;
	if ($language_id == 0) $language_id = $languages_id;
    $resource_query = tep_db_query("select resource_name from " . TABLE_RESOURCES_DESCRIPTION . " where resource_id = '" . (int)$resource_id . "' and language_id = '" . (int)$language_id . "'");
    $resource = tep_db_fetch_array($resource_query);

    return $resource['resource_name'];
  }
  	
		
  function tep_get_service_name($service_id, $language_id = 0) {
    global $languages_id;

    if ($language_id == 0) $language_id = $languages_id;
    $service_query = tep_db_query("select service_name from " . TABLE_SERVICES_DESCRIPTION . " where service_id = '" . (int)$service_id . "' and language_id = '" . (int)$language_id . "'");    
 	$service = tep_db_fetch_array($service_query);

    return $service['service_name'];
  }
  
  
// get service description by passing service_id
 function tep_get_service_description($service_id, $language_id=0) {
	global $languages_id;

	if ($language_id == 0) $language_id = $languages_id;
    $service_query = tep_db_query("select service_description from " . TABLE_SERVICES_DESCRIPTION . " where service_id = '" . (int)$service_id . "' and language_id = '" . (int)$language_id . "'");
    $service = tep_db_fetch_array($service_query);

    return $service['service_description'];
  }
  
   // get service url by passing service_id
 function tep_get_service_url($service_id, $language_id=0) {
	global $languages_id;	
	if ($language_id == 0) $language_id = $languages_id;
    $service_query = tep_db_query("select service_url from " . TABLE_SERVICES_DESCRIPTION . " where service_id = '" . (int)$service_id . "' and language_id = '" . (int)$language_id . "'");
    $service = tep_db_fetch_array($service_query);

    return $service['service_url'];
 }
 function tep_get_service_image($service_id, $language_id=0) {
	global $languages_id;
	if ($language_id == 0) $language_id = $languages_id;
    $service_query = tep_db_query("select s.service_image from " . TABLE_SERVICES_DESCRIPTION . " sd,".TABLE_SERVICES." s where sd.service_id=s.service_id and s.service_id = '" . (int)$service_id . "' and sd.language_id = '" . (int)$language_id . "'");
    $service = tep_db_fetch_array($service_query);

    return $service['service_image'];
 }
//
// get service group name by passing group_id and language_id
  function tep_get_service_group_name($service_group_id, $language_id) {
    $service_group_query = tep_db_query("select service_group_name from " . TABLE_SERVICES_GROUP . " where service_group_id = '" . (int)$service_group_id . "' and language_id = '" . (int)$language_id . "'");
    $service_group = tep_db_fetch_array($service_group_query);

    return $service_group['service_group_name'];
  }
  
   // set service status by passing service_group_id
  function tep_set_service_group_status($service_group_id, $status) {
    if ($status == '1') {
      return tep_db_query("update " . TABLE_SERVICES_GROUP . " set service_group_status = 1, last_modified = now() where service_group_id = '" . (int)$service_group_id . "'");
    } elseif ($status == '0') {
      return tep_db_query("update " . TABLE_SERVICES_GROUP . " set service_group_status = 0, last_modified = now() where service_group_id = '" . (int)$service_group_id . "'");
    } else {
      return -1;
    }
  }
  
	// get service category name by passing category_id and language_id
  function tep_get_service_category_name($service_category_id, $language_id) {
    $service_category_query = tep_db_query("select services_categories_name from " . TABLE_SERVICES_CATEGORIES_DESCRIPTION . " where services_categories_id = '" . (int)$service_category_id . "' and language_id = '" . (int)$language_id . "'");
    $service_category = tep_db_fetch_array($service_category_query);
    return $service_category['services_categories_name'];
  }
  
	// get service category name by passing category_id and language_id
  function tep_get_service_category_title($service_category_id, $language_id) {
    $service_category_query = tep_db_query("select services_categories_heading_title from " . TABLE_SERVICES_CATEGORIES_DESCRIPTION . " where services_categories_id = '" . (int)$service_category_id . "' and language_id = '" . (int)$language_id . "'");
    $service_category = tep_db_fetch_array($service_category_query);
    return $service_category['services_categories_heading_title'];
  }
  
	// get service category name by passing category_id and language_id
  function tep_get_service_category_description($service_category_id, $language_id) {
    $service_category_query = tep_db_query("select services_categories_description from " . TABLE_SERVICES_CATEGORIES_DESCRIPTION . " where services_categories_id = '" . (int)$service_category_id . "' and language_id = '" . (int)$language_id . "'");
	
    $service_category = tep_db_fetch_array($service_category_query);

    return $service_category['services_categories_description'];
  }
  
  function tep_remove_service_group($service_group_id) {
		$service_group_id=(int)$service_group_id;

		tep_db_query("delete from " . TABLE_SERVICES_GROUP . " where service_group_id = '" . (int)$service_group_id . "'");

	}

  // get service_path url parameter by passing current service_category_id  
  function tep_get_service_path($current_service_category_id = '') {
    global $secPath_array;

    if ($current_service_category_id == '') {
      $secPath_new = implode('_', $secPath_array);
    } else {
      if (sizeof($secPath_array) == 0) {
        $secPath_new = $current_service_category_id;
      } else {
        $secPath_new = '';
		
        $last_service_category_query = tep_db_query("select parent_id from " . TABLE_SERVICES_CATEGORIES . " where services_categories_id = '" . (int)$secPath_array[(sizeof($secPath_array)-1)] . "'");
        $last_service_category = tep_db_fetch_array($last_service_category_query);
        
        $current_service_category_query = tep_db_query("select parent_id from " . TABLE_SERVICES_CATEGORIES . " where services_categories_id = '" . (int)$current_service_category_id . "'");
        $current_service_category = tep_db_fetch_array($current_service_category_query);

        if ($last_service_category['parent_id'] == $current_service_category['parent_id']) {
          for ($i = 0, $n = sizeof($secPath_array) - 1; $i < $n; $i++) {
            $secPath_new .= '_' . $secPath_array[$i];
          }
        } else {
          for ($i = 0, $n = sizeof($secPath_array); $i < $n; $i++) {
            $secPath_new .= '_' . $secPath_array[$i];
          }
        }

        $secPath_new .= '_' . $current_service_category_id;

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

    return 'secPath=' . $secPath_new;
  } 
  
  // form the generated service category tree
	function tep_get_services_category_tree($parent_id = '0', $spacing = '', $exclude = '', $service_category_tree_array = '', $include_itself = false) {
		global $languages_id;
		
		if (!is_array($service_category_tree_array)) $service_category_tree_array = array();
		if ( (sizeof($service_category_tree_array) < 1) && ($exclude != '0') ) $service_category_tree_array[] = array('id' => '0', 'text' => TEXT_TOP);
		if ($include_itself) {
			$service_category_query = tep_db_query("select sucd.services_categories_name from " . TABLE_SERVICES_CATEGORIES_DESCRIPTION . " sucd where sucd.language_id = '" . (int)$languages_id . "' and sucd.services_categories_id = '" . (int)$parent_id . "'");
			
			$service_category = tep_db_fetch_array($service_category_query);
			$service_category_tree_array[] = array('id' => $parent_id, 'text' => $service_category['services_categories_name']);
		}
		$service_categories_query = tep_db_query("select suc.services_categories_id, sucd.services_categories_name, suc.parent_id from " . TABLE_SERVICES_CATEGORIES . " suc, " . TABLE_SERVICES_CATEGORIES_DESCRIPTION . " sucd where suc.services_categories_id = sucd.services_categories_id and sucd.language_id = '" . (int)$languages_id . "' and suc.parent_id = '" . (int)$parent_id . "' order by suc.sort_order, sucd.services_categories_name");
		while ($service_categories = tep_db_fetch_array($service_categories_query)) {
			if ($exclude != $service_categories['services_categories_id']) {
				$service_category_tree_array[] = array('id' => $service_categories['services_categories_id'], 'text' => $spacing . $service_categories['services_categories_name']);
			}
			$service_category_tree_array = tep_get_services_category_tree($service_categories['services_categories_id'], $spacing . '&nbsp;&nbsp;&nbsp;', $exclude, $service_category_tree_array);
		}
		return $service_category_tree_array;
	}
	//for resource-service
	function tep_get_resource_tree()
	{
	global $languages_id;
	$resource_array=array();
	$resource_query=tep_db_query("Select resource_id, resource_name from " . TABLE_RESOURCES_DESCRIPTION . " where language_id='" . (int)$languages_id . "' order by resource_name");
	while($resource_result=tep_db_fetch_array($resource_query))
		{
			$resource_array[]=array('id'=>$resource_result['resource_id'],'text'=>$resource_result['resource_name']);
		}
	
	return($resource_array);
}
	
	  // get the service category path by passing current directory
	  function tep_get_generated_service_category_path_ids($id, $from = 'service_category') {
		$calculated_service_category_path_string = '';
		$calculated_service_category_path = tep_generate_service_category_path($id, $from);
		for ($i=0, $n=sizeof($calculated_service_category_path); $i<$n; $i++) {
		  for ($j=0, $k=sizeof($calculated_service_category_path[$i]); $j<$k; $j++) {
			$calculated_service_category_path_string .= $calculated_service_category_path[$i][$j]['id'] . '_';
		  }
		  $calculated_service_category_path_string = substr($calculated_service_category_path_string, 0, -1) . '<br>';
		}
		$calculated_service_category_path_string = substr($calculated_service_category_path_string, 0, -4);
	
		if (strlen($calculated_service_category_path_string) < 1) $calculated_service_category_path_string = TEXT_TOP;
	
		return $calculated_service_category_path_string;
	  }
	  
	  // find total no of child service in a selected category
	  function tep_childs_in_service_category_count($service_categories_id) {
		$service_categories_count = 0;
	
		$service_categories_query = tep_db_query("select services_categories_id from " . TABLE_SERVICES_CATEGORIES . " where parent_id = '" . (int)$service_categories_id . "'");
		while ($service_categories = tep_db_fetch_array($service_categories_query)) {
		  $service_categories_count++;
		  $service_categories_count += tep_childs_in_service_category_count($service_categories['services_categories_id']);
		}
	
		return $service_categories_count;
	  }

	 // get total service count by navigating nested category
	  function tep_service_in_service_category_count($service_categories_id, $include_deactivated = false) {
		$service_count = 0;
	
		if ($include_deactivated) {
		  $service_query = tep_db_query("select count(*) as total from " . TABLE_SERVICES . " su " . TABLE_SERVICES_TO_SERVICES_CATEGORIES . " su2c where su.service_id = su2c.service_id and su2c.services_categories_id = '" . (int)$service_categories_id . "'");
		} else {
		  $service_query = tep_db_query("select count(*) as total from " . TABLE_SERVICES . " su, " . TABLE_SERVICES_TO_SERVICES_CATEGORIES . " su2c where su.service_id = su2c.service_id and su.service_status>=1 and su2c.services_categories_id = '" . (int)$service_categories_id . "'");
		}
	
		$service = tep_db_fetch_array($service_query);
	
		$service_count += $service['total'];
	
		$childs_query = tep_db_query("select services_categories_id from " . TABLE_SERVICES_CATEGORIES . " where parent_id = '" . (int)$service_categories_id . "'");
		if (tep_db_num_rows($childs_query)) {
		  while ($childs = tep_db_fetch_array($childs_query)) {
			$service_count += tep_service_in_service_category_count($childs['services_categories_id'], $include_deactivated);
		  }
		}
	
		return $service_count;
	  }
	  
	 // generate service category path from the current category
	  function tep_output_generated_service_category_path($id, $from = 'service_category') {
		$calculated_service_category_path_string = '';
		$calculated_service_category_path = tep_generate_service_category_path($id, $from);
		for ($i=0, $n=sizeof($calculated_service_category_path); $i<$n; $i++) {
		  for ($j=0, $k=sizeof($calculated_service_category_path[$i]); $j<$k; $j++) {
			$calculated_service_category_path_string .= $calculated_service_category_path[$i][$j]['text'] . '&nbsp;&gt;&nbsp;';
		  }
		  $calculated_service_category_path_string = substr($calculated_service_category_path_string, 0, -16) . '<br>';
		}
		$calculated_service_category_path_string = substr($calculated_service_category_path_string, 0, -4);
	
		if (strlen($calculated_service_category_path_string) < 1) $calculated_service_category_path_string = TEXT_TOP;
	
		return $calculated_service_category_path_string;
	  }

	  // get service category path
	  function tep_generate_service_category_path($id, $from = 'service_category', $service_categories_array = '', $index = 0) {
		global $languages_id;
	
		if (!is_array($service_categories_array)) $service_categories_array = array();
	
		if ($from == 'service') {
		  $service_categories_query = tep_db_query("select services_categories_id from " . TABLE_SERVICES_TO_SERVICES_CATEGORIES . " where service_id = '" . (int)$id . "'");
		  while ($service_categories = tep_db_fetch_array($service_categories_query)) {
			if ($service_categories['services_categories_id'] == '0') {
			  $service_categories_array[$index][] = array('id' => '0', 'text' => TEXT_TOP);
			} else {
			  $service_category_query = tep_db_query("select sucd.services_categories_name, suc.parent_id from " . TABLE_SERVICES_CATEGORIES . " suc, " . TABLE_SERVICES_CATEGORIES_DESCRIPTION . " sucd where suc.services_categories_id = '" . (int)$service_categories['services_categories_id'] . "' and suc.services_categories_id = sucd.services_categories_id and sucd.language_id = '" . (int)$languages_id . "'");
			  $service_category = tep_db_fetch_array($service_category_query);
			  $service_categories_array[$index][] = array('id' => $service_categories['services_categories_id'], 'text' => $service_category['services_categories_name']);
			  if ( (tep_not_null($service_category['parent_id'])) && ($service_category['parent_id'] != '0') ) $service_categories_array = tep_generate_service_category_path($service_category['parent_id'], 'service_category', $service_categories_array, $index);
			  $service_categories_array[$index] = array_reverse($service_categories_array[$index]);
			}
			$index++;
		  }
		} elseif ($from == 'service_category') {
		  $service_category_query = tep_db_query("select sucd.services_categories_name, suc.parent_id from " . TABLE_SERVICES_CATEGORIES . " suc, " . TABLE_SERVICES_CATEGORIES_DESCRIPTION . " sucd where suc.services_categories_id = '" . (int)$id . "' and suc.services_categories_id = sucd.services_categories_id and sucd.language_id = '" . (int)$languages_id . "'");
		  $service_category = tep_db_fetch_array($service_category_query);
		  $service_categories_array[$index][] = array('id' => $id, 'text' => $service_category['services_categories_name']);
		  if ( (tep_not_null($service_category['parent_id'])) && ($service_category['parent_id'] != '0') ) $service_categories_array = tep_generate_service_category_path($service_category['parent_id'], 'service_category', $service_categories_array, $index++);
		}
		return $service_categories_array;
	  }
	// form the tree of catgories and events for customized list box to select event (only for the page addevents)
	function tep_get_service_time_info_tree($customer_id,$parent_id = '0', $spacing = '', $exclude = '', $service_category_tree_array = '', $include_itself = false) {
		global $languages_id,$currencies;
		
		if (!is_array($service_category_tree_array)) $service_category_tree_array = array();
		if ( (sizeof($service_category_tree_array) < 1) && ($exclude != '0') ) $service_category_tree_array[] = array('id' => '0', 'text' => TEXT_TOP);
		
		// if the category is to be included
		if ($include_itself) {
			$service_category_query = tep_db_query("select scd.services_categories_name from " . TABLE_SERVICES_CATEGORIES_DESCRIPTION . " scd where scd.language_id = '" . (int)$languages_id . "' and scd.services_categories_id = '" . (int)$parent_id . "'");
			$service_category = tep_db_fetch_array($category_query);
			$service_category_tree_array[] = array('id' => $parent_id, 'text' => $service_category['services_categories_name'],'mode'=>'C');
		}
		// recursively select the category
		$service_categories_query = tep_db_query("select sc.services_categories_id, scd.services_categories_name, sc.parent_id from " . TABLE_SERVICES_CATEGORIES . " sc, " . TABLE_SERVICES_CATEGORIES_DESCRIPTION . " scd where sc.services_categories_id = scd.services_categories_id and scd.language_id = '" . (int)$languages_id . "' and sc.parent_id = '" . (int)$parent_id . "' order by sc.sort_order, scd.services_categories_name");
		while ($service_categories = tep_db_fetch_array($service_categories_query)) {
			if ($exclude != $service_categories['services_categories_id']) $service_category_tree_array[] = array('id' => $service_categories['services_categories_id'], 'text' => $spacing . $service_categories['services_categories_name']);
			$service_category_tree_array = tep_get_service_time_info_tree($customer_id,$service_categories['services_categories_id'], $spacing . '&nbsp;&nbsp;&nbsp;', $exclude, $service_category_tree_array);
		}
		
		// select the service
		$service_query=tep_db_query("select sed.service_name,se.service_location,se.service_total_time,sed.service_id,se.service_costs,se.service_tax_class_id,se.include_resource,se.include_resource_price,se.booking_type  from " . TABLE_SERVICES . ' se, ' . TABLE_SERVICES_DESCRIPTION . " sed, " . TABLE_SERVICES_TO_SERVICES_CATEGORIES . " secd where secd.services_categories_id='" . (int)$parent_id . "' and se.service_id=secd.service_id and se.service_id=sed.service_id  " . SERVICES_CONDITION_STATUS . " and sed.language_id = " . $languages_id . " order by sed.service_name");
		while ($service=tep_db_fetch_array($service_query))
		{
			$service_name=$service["service_name"];
			$total_time=$service["service_total_time"];
			$ratevalue="";
			if($service['include_resource']=='Y' && $service['include_resource_price']=='N' || $service['include_resource']=='N'){
				$price=$service["service_costs"];
				$tax=tep_get_tax_rate($service["service_tax_class_id"]);
				$ratevalue=$currencies->format(tep_add_tax($price,$tax_rate));
			}
			$fmt=" Hr.";
			if($service['booking_type']=='M') $fmt=" Min.";
			if($service['booking_type']=='D') $fmt=" Day.";
			if($total_time>1)	$fmt=str_replace(".","",$fmt)."s.";
			$service_time = $service_name . '&nbsp;' . $total_time . $fmt;
			// form the array with events_name,color,price,start_date
			$service_category_tree_array[] = array('id' => $service['service_id'], 'text' => $spacing . $service_time . '&nbsp;<font color=' . $color . '>' . $ratevalue . '</font>&nbsp;&nbsp;&nbsp;' . $start_date . $discount_info,'mode'=>'V');
		}    
		
		return $service_category_tree_array;
	} 

 // function remove a survey by passing survey_id
function tep_delete_service_survey($delete_id){
		$delete_id=(int)$delete_id;
		$question_query=tep_db_query("SELECT question_id from " . TABLE_SERVICES_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_SERVICES_SURVEYS_CHOICE . " where question_id in(" . $question_ids . ")");
			tep_db_query("DELETE from " . TABLE_SERVICES_SURVEYS_QUESTION . " where question_id in(" . $question_ids . ")");
			tep_db_query("DELETE from " . TABLE_SERVICES_SURVEYS_ANSWER . " where question_id in(" . $question_ids . ")");
			tep_db_query("DELETE from " . TABLE_SERVICES_SURVEYS_TEXT . " where question_id in(" . $question_ids . ")");
		}
		tep_db_query("DELETE from " . TABLE_SERVICES_SURVEYS . " where survey_id='" . $delete_id . "'");
		tep_db_query("DELETE from " . TABLE_SERVICES_SURVEYS_FLAG . " where survey_id='" . $delete_id . "'");
	}
	
	 function tep_get_provider_name($id) {
    $provider_query = tep_db_query("select provider_firstname,provider_lastname from " . TABLE_SERVICES_PROVIDERS . " where provider_id='" . (int)$id  . "'");
    if ($provider=tep_db_fetch_array($provider_query))
        return $provider['provider_firstname'] . ' ' . $provider['provider_lastname'];
  }


// remove service from database
	function tep_remove_service($service_id) {
		// fetch image name 
		$service_image_query = tep_db_query("select service_image from " . TABLE_SERVICES . " where service_id = '" . (int)$service_id . "'");
		$service_image = tep_db_fetch_array($service_image_query);
	
		$duplicate_image_query = tep_db_query("select count(*) as total from " . TABLE_SERVICES . " where service_image = '" . tep_db_input($service_image['service_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 . $service_image['service_image'])) {
			@unlink(DIR_FS_CATALOG_IMAGES . $service_image['service_image']);
		  }
		}
		$service_id=(int)$service_id;
		
		$survey_id_query=tep_db_query("select * from ".TABLE_SERVICES_SURVEYS . " where service_id='" .$service_id ."'");
		$survey_id_array=tep_db_fetch_array($survey_id_query);
		
		// delete from service,service,service_to_service table
		tep_db_query("delete from " . TABLE_SERVICES . " where service_id = '" . $service_id . "'");
		tep_db_query("delete from " . TABLE_SERVICES_DESCRIPTION . " where service_id = '" . $service_id . "'");
		tep_db_query("delete from " . TABLE_SERVICES_MESSAGES . " where service_id = '" . $service_id . "'");
		tep_db_query("delete from " . TABLE_SERVICES_NO_BOOKING_DAYS . " where service_id='" .$service_id ."'");
		tep_db_query("delete from " . TABLE_SERVICES_LOADINGS . " where service_id='".$service_id."'");
		tep_db_query("delete from " . TABLE_SERVICES_SMS_MESSAGES . " where service_id='" .$service_id. "'");
		tep_db_query("delete from " . TABLE_SERVICES_ATTRIBUTES . " where service_id = '" . $service_id . "'");

		tep_delete_service_survey($survey_id_array["survey_id"]);
	}	
	
  // remove the selected service category
  function tep_remove_service_category($service_category_id) {
    $category_image_query = tep_db_query("select services_categories_image from " . TABLE_SERVICES_CATEGORIES . " where services_categories_id = '" . (int)$service_category_id . "'");
    $category_image = tep_db_fetch_array($category_image_query);

    $duplicate_image_query = tep_db_query("select count(*) as total from " . TABLE_SERVICES_CATEGORIES . " where services_categories_image = '" . tep_db_input($service_category_image['services_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['services_categories_image'])) {
        @unlink(DIR_FS_CATALOG_IMAGES . $category_image['services_categories_image']);
      }
    }
  
    tep_db_query("delete from " . TABLE_SERVICES_CATEGORIES . " where services_categories_id = '" . (int)$service_category_id . "'");
    tep_db_query("delete from " . TABLE_SERVICES_CATEGORIES_DESCRIPTION . " where services_categories_id = '" . (int)$service_category_id . "'");
    tep_db_query("delete from " . TABLE_SERVICES_TO_SERVICES_CATEGORIES . " where services_categories_id = '" . (int)$service_category_id . "'");

  }

  // generate service category path to the current category
  function tep_output_rev_generated_service_category_path($id, $from = 'service_category') {
    $calculated_service_category_path_string = '';
    $calculated_service_category_path = tep_generate_service_category_path($id, $from);
    for ($i=0, $n=sizeof($calculated_service_category_path); $i<$n; $i++) {
      for ($j=0, $k=sizeof($calculated_service_category_path[$i]); $j<$k; $j++) {
        $calculated_service_category_path_string = $calculated_service_category_path[$i][$j]['text'] . '&nbsp;&gt;&nbsp;' . $calculated_service_category_path_string;
      }
      $calculated_service_category_path_string = substr($calculated_service_category_path_string, 0, -16) . '<br>';
    }
    $calculated_service_category_path_string = substr($calculated_service_category_path_string, 0, -4);

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

    return $calculated_service_category_path_string;
  }
  
  /// get the value for subcription group name
	/*function tep_get_group_name($service_group_id) {
		$service_group_query = tep_db_query("select service_group_name from " . TABLE_SERVICES_GROUP . " where service_group_id = '" . (int)$service_group_id . "'");
		$service_group = tep_db_fetch_array($service_group_query);
		return $service_group['service_group_name'];
  }*/
  
	// get the service display tree
  function tep_get_service_display_tree($parent_id = '0', $spacing = '', $exclude = '', $service_category_tree_array = '', $include_itself = false) {
    global $languages_id;
    
    if (!is_array($service_category_tree_array)) $service_category_tree_array = array();
    if ( (sizeof($service_category_tree_array) < 1) && ($exclude != '0') ) $service_category_tree_array[] = array('id' => '0', 'text' => TEXT_TOP);

    if ($include_itself) {
      $service_category_query = tep_db_query("select sud.services_categories_name from " . TABLE_SERVICES_CATEGORIES_DESCRIPTION . " sud where sud.language_id = '" . (int)$languages_id . "' and sud.services_categories_id = '" . (int)$parent_id . "'");
	  $service_category = tep_db_fetch_array($service_category_query);
      $service_category_tree_array[] = array('id' => $parent_id, 'text' => $service_category['services_categories_name']);
    }

    $service_categories_query = tep_db_query("select su.services_categories_id, sud.services_categories_name, su.parent_id from " . TABLE_SERVICES_CATEGORIES . " su, " . TABLE_SERVICES_CATEGORIES_DESCRIPTION . " sud where su.services_categories_id = sud.services_categories_id and sud.language_id = '" . (int)$languages_id . "' and su.parent_id = '" . (int)$parent_id . "' order by su.sort_order, sud.services_categories_name");
	while ($service_categories = tep_db_fetch_array($service_categories_query)) {
      if ($exclude != $service_categories['services_categories_id']) $service_category_tree_array[] = array('id' => $service_categories['services_categories_id'], 'text' => $spacing . "--" .  $service_categories['services_categories_name'] . "--");
      $service_category_tree_array = tep_get_service_display_tree($service_categories['services_categories_id'], $spacing . '&nbsp;&nbsp;&nbsp;', $exclude, $service_category_tree_array);
    }
    $service_query=tep_db_query("select sud.service_name,sud.service_id from " . TABLE_SERVICES." su," . TABLE_SERVICES_DESCRIPTION . " sud, " . TABLE_SERVICES_TO_SERVICES_CATEGORIES . " suTsuc where su.service_status>=1 and su.service_id=sud.service_id and suTsuc.services_categories_id='" . (int)$parent_id . "' and sud.service_id=suTsuc.service_id and sud.language_id='" . (int)$languages_id . "'");
	while ($service=tep_db_fetch_array($service_query))
    {
        $service_category_tree_array[] = array('id' => $service['service_id'], 'text' => $spacing . $service['service_name'] . '(service)');
    }
    return $service_category_tree_array;
  }


// send email to customer regarding the order
function tep_send_service_order_email($order_id){
	global $currencies;
	if ((int)EMAIL_ACTIVATE!=1) return;
	if ((int)$order_id<=0)	return;
	$url_home=(ENABLE_SSL == 'true'?HTTPS_SERVER . DIR_WS_CATALOG:HTTP_SERVER . DIR_WS_CATALOG);
	// 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 service added to order
	$service_query=tep_db_query("SELECT op.final_price,op.orders_products_id, op.products_id,op.products_tax,op.products_quantity,op.products_name,op.products_price as service_costs,se.service_location," .
									" se.service_tax_class_id,time_format(os.start_time,'%h:%m %p') as start_time,time_format(os.end_time,'%h:%m %p') as end_time,os.start_date,os.end_date,os.resource_name,date_add(os.end_date,interval se.service_renewal_end day) as renewal_end_date  from " . 
									TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_SERVICES . " se, " . TABLE_ORDERS_SERVICES . " os " .
							
							 		" where o.orders_id='" . $order_id ."' and o.orders_id=op.orders_id and op.products_type='V' and op.products_id=se.service_id and o.orders_id=os.orders_id and op.products_id=os.products_id");
	if (tep_db_num_rows($service_query)<=0) return;
	
	// get mail template details
	$details=array();
	$details['type']='RCF';
	$details['table']=TABLE_SERVICES_MESSAGES;
	
	while($service_result=tep_db_fetch_array($service_query))
	{
		$service_ordered_attributes="";
		$attributes_query = tep_db_query("select products_options, products_options_values, options_values_price, price_prefix from " . TABLE_ORDERS_PRODUCTS_ATTRIBUTES . " where orders_id = '" . (int)$order_id . "' and orders_products_id = '" . (int)$service_result['orders_products_id'] . "'");
		
		if(tep_db_num_rows($attributes_query)>0)
		{
		while($attributes_result=tep_db_fetch_array($attributes_query))
			{
				$service_ordered_attributes .=  $attributes_result['products_options'] . ' :  ' . $attributes_result['products_options_values'] . '  (' .  $attributes_result['price_prefix'] . $currencies->format($attributes_result['options_values_price']) . ")<br>";
			}
		}
		
		$resource_query = tep_db_query("Select date_format(start_date,'%Y-%m-%d') as start_date, date_format(end_date,'%Y-%m-%d') as end_date, time_format(start_time,'%I:%i %p') as start_time,end_time, resource_name from " . TABLE_ORDERS_SERVICES . " where orders_id='" . (int)$order_id . "' and orders_products_id='" . (int)$service_result['orders_products_id'] . "' ");	
		
		if(tep_db_num_rows($resource_query)>0)
			$resource_result=tep_db_fetch_array($resource_query);
		
		$details['service_id']=$service_result['products_id'];
		tep_get_template1($details);
		
		//for direct deposit module
		if($GLOBALS['payment']=='ausbank')
			$direct_deposit=sprintf(TEXT_DIRECT_DEPOSIT,substr(strtolower($order_result['customers_firstname']),0,3) , substr(strtolower($order_result['customers_lastname']),0,3) , $order_timestamp );
		else 
			$direct_deposit='';

		if($resource_result['end_date'] && $resource_result['end_time']) $end_time_string=strtotime($resource_result['end_date'].' '.$resource_result['end_time'])+60;
		$resource_result['end_date']=date('Y-m-d',$end_time_string);
		$resource_result['end_time']=date('h:i A',$end_time_string);
		// 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_SER_SN=>$service_result['products_name'],
								TEXT_SER_SC=>$currencies->format(tep_add_tax($service_result['service_costs'],tep_get_tax_rate($service_result['service_tax_class_id']))),
								TEXT_SER_SD=>format_date($resource_result['start_date']),
								TEXT_SER_ED=>format_date($resource_result['end_date']),
								TEXT_SER_ST=>$resource_result['start_time'],
								TEXT_SER_ET=>$resource_result['end_time'],
								TEXT_SER_RN=>$resource_result['resource_name'],
								TEXT_SER_AD=>$service_ordered_attributes,
								TEXT_SER_SL=>tep_get_service_location_name($service_result["service_location"]),
								TEXT_RE=>format_date($service_result['renewal_end_date']),  
								TEXT_IV=>'<a href="' . tep_catalog_href_link(FILENAME_SERVICES_INVITE_FRIEND,'R=1&path=ACC&seID=' . $service_result['products_id'],'NONSSL',false) . '">' . TEST_MAIL_SUB_IV . '</a>',
								TEXT_UN=>'<a href="' . tep_catalog_href_link(FILENAME_SERVICES_UNSUBSCRIBE,'R=1&cID=' . $order_result['customers_id'],'NONSSL',false) . '">' . TEST_MAIL_SUB_UN . '</a>',
								TEXT_SUB_RL=>'<a href="' . tep_catalog_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_SUB_RL . '</a>',
								TEXT_RV=>'<a href="' . tep_catalog_href_link(FILENAME_SERVICES_SURVEYS_ANSWER,'R=1&type=RV&service_id=' . $service_result['products_id'],'NONSSL',false) . '">' . TEST_MAIL_RV . '</a>',
								TEXT_WV=>'<a href="' . tep_catalog_href_link(FILENAME_SERVICES_SURVEYS_ANSWER,'R=1&type=WV&service_id=' . $service_result['products_id'],'NONSSL',false) . '">' . TEST_MAIL_WV . '</a>',
								TEXT_FV=>'<a href="' . tep_catalog_href_link(FILENAME_SERVICES_SURVEYS_ANSWER,'R=1&type=FV&service_id=' . $service_result['products_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_SUB_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_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($service_result['final_price']*$service_result['products_quantity'],$service_result['products_tax'])),
								TEXT_SB=>$currencies->format($service_result['final_price']),
								TEXT_TL=>$currencies->format(tep_add_tax($service_result['final_price'],$service_result['products_tax']))
								);

	$sql_array=array(	'orders_id'=>$order_id,
						'service_id'=>$service_result['products_id'],
						'customers_id'=>$order_result["customers_id"],
						'message_type'=>'RCF',
						'message_mode'=>'E',
						'email_address'=>$order_result["customers_email_address"],
						'send_date'=>'now()'
					);
		// replace template
		if ($details['html_text']!='') {
			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;
			tep_send_email($details);
			if (SEND_EXTRA_ORDER_EMAILS_TO!=''){
			$details['to_email'] = SEND_EXTRA_ORDER_EMAILS_TO;
			tep_send_email($details);
			}
			
			tep_db_perform(TABLE_SERVICES_MESSAGES_HISTORY,$sql_array);
		}
	}	
}

// get location name by passing location_id
  function tep_get_service_location_name($location_id) {
    $location_query = tep_db_query("select service_location_name from " . TABLE_SERVICES_LOCATIONS . " where service_location_id = '" . (int)$location_id . "'");
    $location = tep_db_fetch_array($location_query);

    return $location['service_location_name'];
  }  

 // set status by passing service_id
  function tep_set_service_status($service_id, $status) {
    if ($status == '1') {
      return tep_db_query("update " . TABLE_SERVICES . " set service_status = 1, service_last_modified = now() where service_id = '" . (int)$service_id . "'");
    } elseif ($status == '0') {
      return tep_db_query("update " . TABLE_SERVICES . " set service_status = 0, service_last_modified = now() where service_id = '" . (int)$service_id . "'");
    } else {
      return -1;
    }
  }   
  
// send service test email 
function tep_send_service_test_email($mail_type,$service_id){
	global $currencies;
	
	if ($mail_type=='' || (int)$service_id<=0) return;

	$mail_data_query=tep_db_query("SELECT * from " . TABLE_SERVICES_MESSAGES . " where message_type='" . $mail_type . "' and service_id='" . (int)$service_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']);
	// echo $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);
  
	$message = new email(array('X-Mailer: FreeWay'));


     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 , TEST_MAIL_EM, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, $mail_data_result['message_subject']);
}


  function tep_services_options_name($options_id) {
    global $languages_id;

    $options = tep_db_query("select services_options_name from " . TABLE_SERVICES_OPTIONS . " where services_options_id = '" . (int)$options_id . "' and language_id = '" . (int)$languages_id . "'");
    $options_values = tep_db_fetch_array($options);

    return $options_values['services_options_name'];
  }

  function tep_services_values_name($values_id) {
    global $languages_id;

    $values = tep_db_query("select services_options_values_name from " . TABLE_SERVICES_OPTIONS_VALUES . " where services_options_values_id = '" . (int)$values_id . "' and language_id = '" . (int)$languages_id . "'");
    $values_values = tep_db_fetch_array($values);

    return $values_values['services_options_values_name'];
  }

  function tep_service_in_attribute_count($service_id, $include_deactivated = false) {
		$service_count = 0;
	
		if ($include_deactivated) {
		  $service_query = tep_db_query("select count(*) as total from " . TABLE_ORDERS_PRODUCTS .  "  where products_id ='" . (int)$service_id . "' and products_type='R'");
		} else {
		  $service_query = tep_db_query("select count(*) as total from " . TABLE_ORDERS_PRODUCTS . " where products_id = '" . (int)$service_id . "' and products_type='R'");
		}
	
		$service = tep_db_fetch_array($service_query);
	
		$service_count += $service['total'];
		return $service_count;
  }
  
    //time interval
function tep_time_interval($starttime,$endtime)
{
	$starthour=split(':',$starttime);
	$shour=$starthour[0];
	$smin= $starthour[1];
	$ssession=$starthour[2];

	$endhour=split(':',$endtime);
	$ehour=$endhour[0];
	$emin= $endhour[1];
	$esession=$endhour[2];

		
	if($ssession=='PM' && $esesssion=='AM')
  		$diff=(24-$shour) + $ehour;
	else if($ssession=='AM' && $esession=='PM')
  		$diff=(12-$shour) + $ehour;
	else if($ssession=='PM' && $esession=='PM')
		$diff=$ehour-$shour;
	else if($ssession=='AM' && $esession=='AM')
		$diff=$ehour-$shour; 
	
/*	$diffhour=$ehour-$shour;
	$diffmin=$emin-$smin;
	
	if($diffmin<0) {
	$diffhour=$diffhour-1;
	$diffmin=$diffmin+60;
	} */
	//$time=sprintf("%02d",$hour) . ":" .sprintf("%02d",$start_min). ":" .$meridian;
//return($diffhour) . ":" .($diffmin). ":" ."00";
return($diff);
}

function tep_get_time_array($start_time,$end_time,$interval_min){
	// first get the elements of hour
	$time_splt1=split(":",$start_time);
	$time_splt2=split(":",$end_time);
	
	$start_hour=$time_splt1[0];
	$start_min=$time_splt1[1];
	
	$end_hour=$time_splt2[0];
	$end_min=$time_splt2[1];
	$result=array();
	while($start_hour<=$end_hour){
		if ($start_hour==$end_hour && $start_min>=$end_min) break;
		$time=sprintf("%02s:%02s",$start_hour,$start_min);
		
		if ($start_hour>=13){
			$time_text=sprintf("%02d:%02d PM",$start_hour-12,$start_min);
		} else  {
			$time_text=sprintf("%02d:%02d AM",$start_hour,$start_min);
		}
		
		$result[]=array('id'=>$time,'text'=>$time_text);
		$start_min+=$interval_min;
		// create time text AM or PM 
		if ($start_min>=60){
			$start_min=$start_min-60;
			$start_hour++;
		}
	}
	return $result;
}
function tep_get_dates_array($start_date,$interval){
  
	$date_splt=split("-",$start_date);
	$day=$date_splt[2];
	$month=$date_splt[1];
	$year=$date_splt[0];
	$dates=array();
	$total_days=0;
	for ($icnt=1;$icnt<=$interval;$icnt++){
		// calculate the total days
		if ($day==1 || $total_days==0){
			$total_days=31;
			if ($month==4 || $month==6 || $month==9 || $month==11) $total_days=30;
			if ($month==2){
				$total_days=28;
				if ($year % 4 == 0 && ($year % 100 != 0 || $year % 400 == 0)) $total_days=29;
			}
		}
		//form the day
		$date=sprintf("%4s-%02d-%02d",$year,$month,$day); 
		$dates[]=array('id'=>$date,'text'=>format_date($date)); 
		$day=$day+1;
		
		if ($day>$total_days){
			$day=1;
			$month=$month+1;
			if ($month>12){
				$month=1;
				$year=$year+1;
			}
		}
	}
	return $dates;
}

 function tep_get_service_dates_array($start_date,$end_date,$type){	
   global $no_booking_sdate,$no_booking_edate,$no_booking_dates,$no_booking_stime,$no_booking_etime,$service_start_time,$service_week,$time_length,$block_dates,$no_booking_sdate_array,$granular;
   $granular_cnt=$granular;   
   if($type!='D') $granular_cnt=1; 
   $cur_date_string=strtotime(getServerDate(true));    
   $dis_time_format="";   
   if(defined('TIME_FORMAT')) $dis_time_format=TIME_FORMAT;	
	$nb_dates_array=$block_dates;
	if ($start_date=="" || $end_date=="") return;
	$hr=date("H",$cur_date_string)+1;
	$mt=date("i",$cur_date_string)+(($type=='M')?$time_length:0);
	if($type=='M') $time_length=0;
	$start_date_splt=split("-",$start_date);	
	if($type=='D')
		$start_date=date('Y-m-d',mktime(0,0,0,$start_date_splt[1],$start_date_splt[2]+1,$start_date_splt[0]));
	else if(($type=='H' || $type=='M') && $time_length!='' && date("d",mktime(($hr+$time_length),$mt,0,1,1,1987))=="02")		
		 $start_date=date("Y-m-d",mktime(0,0,0,date("m",$cur_date_string),(date("d",$cur_date_string)+1),date("Y",$cur_date_string)));
	$start_time=@strtotime($start_date);
	$end_time=@strtotime($end_date);
	$service_start_time_text=date("h:i A",@strtotime($service_start_time));
	if($dis_time_format!="" && $dis_time_format=='24')  $service_start_time_text=date("H:i",@strtotime($service_start_time));		
	for($i=0;$i<sizeof($nb_dates_array);$i++){
		if($i>0) $block_datesarray=array_merge($block_datesarray,$nb_dates_array[$i]);
		else  $block_datesarray=$nb_dates_array[$i];		
	}
	if($block_datesarray)
		while(list($key,$value)=each($block_datesarray))
			$find_max_dates[]=$key;	
	while($start_time<=$end_time){
		//form the day		
		if(count($no_booking_sdate_array)>0){
			for($icnt=0;$icnt<count($no_booking_sdate_array);$icnt++){ 
				$date_s_string=@strtotime($no_booking_sdate_array[$icnt]['start_date']); 
				$date_e_string=@strtotime($no_booking_sdate_array[$icnt]['end_date']); 
				if($date_s_string<=$start_time && $date_e_string>=$start_time){
					$start_time=$date_e_string;
					$end_time=tep_dateadd($start_time,"day",30);				
				}								
			}
		} 					 
		$date=date('Y-m-d',$start_time);
		$week=date("w",$start_time);
		if($time_length!='' && date("d",mktime(($hr+$time_length),$mt,0,1,1,1987))=="02")
		 	$start_date=date("Y-m-d",mktime(0,0,0,date("m"),(date("d")+1),date("Y")));
		if($block_datesarray[format_date($date)]!='full'){	
			if ($type=="H" || $type=='M') $dates[]=array('id'=>$date,'text'=>format_date($date)); 
			else $dates[]=array('id'=>$date." ".$service_start_time,'text'=>format_date($date) . " " . $service_start_time_text); 				
		}
		$start_time=tep_dateadd($start_time,"day",$granular_cnt);
	}
	if(!$dates){
		$start_date=tep_convert_date_raw($find_max_dates[sizeof($find_max_dates)-1]);
		$end_date=date('Y-m-d',dateadd(@strtotime($start_date),"day",30));
		$dates=tep_get_service_dates_array($start_date,$end_date,$type);
	}
	return $dates;
}

//to add specified interval to a given time
function timeadd($timestamp, $unit, $amount) {
// 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 = @mktime($delta_vars["hr"],
   $delta_vars["min"],
   $delta_vars["sec"],
   $delta_vars["mon"],
   $delta_vars["day"],
   $delta_vars["yr"]);
   return $timestamp + $delta;
}



function tep_get_service_time_array($start_time,$end_time,$interval_min,$type="list"){
	global $no_booking_stime,$no_booking_etime,$times_array,$select_id,$day_start_time;
	if ($start_time=="" || $end_time=="") return;
	$current_time=date("H:i");
	// first get the elements of hour
	$time_splt1=split(":",$start_time);
	$time_splt2=split(":",$end_time);
	
	$start_hour=$time_splt1[0];
	$start_min=$time_splt1[1];
	
	$end_hour=$time_splt2[0];
	$end_min=$time_splt2[1];
	$result=array();
	
	while($start_hour<=$end_hour){
		if ($start_hour==$end_hour && $start_min>$end_min || ($start_time=="" && $end_time=="")) break;
		$time=sprintf("%02s:%02s",$start_hour,$start_min);
			
	    	if ($start_hour>=13){
		     if($start_hour==24) { 
			   $time_text=sprintf("%02d:%02d AM",$start_hour-12,$start_min);
			 }else{
			   $time_text=sprintf("%02d:%02d PM",$start_hour-12,$start_min);
		     }
		} else if ($start_hour==12){
			$time_text=sprintf("%02d:%02d PM",$start_hour,$start_min);
		} else {
			$time_text=sprintf("%02d:%02d AM",(($start_hour=='00')?12:$start_hour),$start_min);
		}
		if (!($time>=$no_booking_stime && $time<=$no_booking_etime)){
			if ($type=="list"){
				$result[]=array('id'=>$time,'text'=>$time_text);
			} else {
				$times_array[$time]=1;
			}
		}
		$start_min+=$interval_min;
		
		// create time text AM or PM 
		if ($start_min>=60){
			$start_min=$start_min-60;
			$start_hour++;
		}
	}
	return $result;
}
// get the booked service users count
 function tep_service_booking_count($service_id,$start_date,$end_date,$start_time,$end_time,$booking_type,$order_id=0,$resource_id="0",$include_resource='N'){
	global $curDate;
	$add_option="";
	if($service_id) $service_info=get_services_info($service_id);
	$add_option.=" and (o.orders_status>1 or date_add(o.date_purchased,interval v.pending_period  day)>='".getServerDate(true)."' and op.orders_products_status!=5 )";
	$add_option.=" and (('".$start_date.' '.$start_time."'>=concat(os.start_date,' ',os.start_time) and '".$start_date.' '.$start_time."'<=concat(os.end_date,' ',os.end_time)) OR ('".$end_date.' '.$end_time."'>=concat(os.start_date,' ',os.start_time) and '".$end_date . ' '.$end_time."'<=concat(os.end_date,' ',os.end_time)) OR ('".$start_date.' '.$start_time."'<=concat(os.start_date,' ',os.start_time) and '".$end_date.' '.$end_time."'>=concat(os.end_date,' ',os.end_time)))";
	if($include_resource=='Y') $add_option.=" and os.resource_id='".(int)$resource_id."'";
	$booking_sql= "SELECT sum(op.products_quantity) as total from " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_ORDERS_SERVICES . " os, " .  TABLE_SERVICES . " v " .
					" where op.products_id='" . $service_id . "' and op.products_type='V' and op.products_id=v.service_id and o.orders_id=op.orders_id and op.products_id=os.products_id " .
					" and o.orders_id=os.orders_id ".$add_option;
	$booking_query=tep_db_query($booking_sql);
	$booking_result=tep_db_fetch_array($booking_query);
	return $booking_result["total"];
 }

function get_diff_time($stime,$etime,$mode="m"){
	$splt1=split(":",$stime);
	$splt2=split(":",$etime);
	$smin=(int)$splt1[0]*60+$splt1[1];
	$emin=(int)$splt2[0]*60+$splt2[1];
	if ($mode=="m"){
		return $emin-$smin;
	} else{
		return ($emin-$smin)/60;
	}
}
function tep_get_template1(&$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'] . "'";
		else if (isset($details['service_id']))
			$add_option=" and service_id='" . $details['service_id'] . "'";	
		$mail_data_query=tep_db_query("SELECT * from " . $details["table"] . " where message_type='" . $details["type"] . "'" . $add_option);
		if (tep_db_num_rows($mail_data_query)>0){
			$mail_data_result=tep_db_fetch_array($mail_data_query);
			//get message content
			$details['format']=$mail_data_result['message_format'];
			$details['html_text']=$mail_data_result['message_text'];
			$details['subject']=$mail_data_result['message_subject'];
		return $details;
		}
		
	}

// to set service view style normal,calendar
 function tep_cfg_pull_down_service_view_style($value){
  $choices=array(array("id"=>"basic","text"=>"Basic"),array("id"=>"calendar","text"=>"calendar"));
	$result.=tep_draw_pull_down_menu('configuration_value[]',$choices,strtolower($value)) . '&nbsp;';
	$result.=tep_image_submit('button_modify.gif',IMAGE_MODIFY,'align=absmiddle');
	return $result;
  }

  // to set service view calendar style
  function tep_cfg_pull_down_service_calendar_style($value,$key=''){
    $name = (($key) ? 'configuration[' . $key . ']' : 'configuration_value');
  	$choices=array(array("id"=>"week","text"=>"Week"),array("id"=>"month","text"=>"Month"));
	$lock_option="";
	//if (strtolower(SERVICES_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_resource_option($value) {
	$result=tep_draw_radio_field('configuration_value','1',($value==1?true:false)) . '&nbsp;' . TEXT_ENABLED . '&nbsp;';
	$result.=tep_draw_radio_field('configuration_value','0',($value==0?true:false)) . '&nbsp;' . TEXT_DISABLED . '&nbsp;';
	//$result.=tep_image_submit('button_modify.gif',IMAGE_MODIFY,'align=absmiddle');
	return $result;
  }
  
   function tep_cfg_resource_name($value) {
	$result=tep_draw_radio_field('configuration_value','1',($value==1?true:false)) . '&nbsp;' .  TEXT_ENABLED . '&nbsp;';
	$result.=tep_draw_radio_field('configuration_value','0',($value==0?true:false)) . '&nbsp;' . TEXT_DISABLED. '&nbsp;';
	//$result.=tep_image_submit('button_modify.gif',IMAGE_MODIFY,'align=absmiddle');
	return $result;
  }
  
  function tep_cfg_resource_description($value) {
	$result=tep_draw_radio_field('configuration_value','1',($value==1?true:false)) . '&nbsp;' .  TEXT_ENABLED . '&nbsp;';
	$result.=tep_draw_radio_field('configuration_value','0',($value==0?true:false)) . '&nbsp;' . TEXT_DISABLED. '&nbsp;';
	//$result.=tep_image_submit('button_modify.gif',IMAGE_MODIFY,'align=absmiddle');
	return $result;
  }

// get the list of services as an array
  function tep_get_services_array($first=''){
  	global $login_id,$login_groups_type,$languages_id;
    $service_array=array();
	 $login_option="";
	 //if ($login_groups_type==TEXT_INSTRUCTOR_ENTRY){
	//	$login_option=" and e.events_instructor=" . $login_id;
///	}
    if ($first!='')
    $service_array[]=array('id'=>-2,'text'=>$first);
    $service_query=tep_db_query("SELECT se.service_id,sd.service_name from " . TABLE_SERVICES . " se, " . TABLE_SERVICES_DESCRIPTION . " sd where 1=1 " . $login_option . " and se.service_id=sd.service_id and sd.language_id='" . $languages_id . "'" . SERVICES_CONDITION_STATUS . "order by sd.service_name");
    while($service_result=tep_db_fetch_array($service_query)){
        $service_array[]=array('id'=>$service_result['service_id'],'text'=>$service_result['service_name']);
    }
    return $service_array;
 } 
 
 function tep_get_service_report_name($idValue){
		$idValue=strtolower($idValue);
		$name="";
		switch($idValue){
			case "rspo":
			   $name=FILENAME_SERVICES_PENDING_ORDERS;
			   break;
			case "rsc":
			   $name=FILANEME_SERVICES_CUSTOMER_DETAILS;
			   break;
			case "senr":
			  $name=FILENAME_SERVICES_NON_RETURNS;
			  break;
			case "rst":
			   $name=FILENAME_SERVICES_ATTENDEES;
			   break;
			case "rss":
			  $name=FILENAME_SERVICES_SALES;
			  break;
			case "rsid":
			  $name=FILENAME_SERVICES_IDCARTS;
			  break;
			case "rstic":
			  $name=FILENAME_SERVICES_TICKETS;
			  break;
			case "rsb":
			   $name=FILENAME_SERVICES_BOOKINGS;
			   break;
			case "rscl":
			   $name=FILENAME_SERVICES_CALL_CENTRE_ORDERS;
			   break;
			case "rsfs":
			  $name=FILENAME_SERVICES_FORSALE;
			  break;
			case "sb":
			  $name=FILENAME_SERVICES_SEARCH_BOOKINGS;
			  break;
		}
		return tep_href_link($name,"return=1");
	}
	/*function tep_calc_service_cost($service,$book_stime,$book_etime,$option_price=0,$loading_dates=""){
		global $product_price,$quantity;	
		$service_costs=$product_price;
		$service_costs=(float)$service_costs;
		$total_service_time=(int)$service["service_total_time"];
		if ($total_service_time==0) $total_service_time=1;
		$ret=tep_time_diff($book_stime,$book_etime);
		if ($service["booking_type"]=="H"){
			$total_book_time=(int)$ret["hours"];
		} else if($service["booking_type"]=="D"){
			$total_book_time=(int)$ret["days"];
		}
		$final_cost=(round(($total_book_time/$total_service_time)) * ($service_costs+$option_price));
		if($loading_dates){
		   $loading_price=tep_loading_price($loading_dates['loading_price_dates'],$loading_dates['start_date'],$loading_dates['end_date'],$loading_dates['start_time'],$loading_dates['end_time'],$service["booking_type"],$final_cost);
		   $final_cost=round($final_cost+$loading_price);
		}			
		return $final_cost;
	}*/
	function tep_calc_service_cost($service,$book_stime,$book_etime,$option_price=0,$loading_dates="",$qty=1,$price=0){
		$total_service_time=(int)$service["service_total_time"];
		$ret=tep_time_diff($book_stime,$book_etime);
		if ($service["booking_type"]=="M")
			$total_book_time=(int)$ret["minutes"];
		else if ($service["booking_type"]=="H")
			$total_book_time=(int)$ret["hours"];
		else if ($service["booking_type"]=="D")
			$total_book_time=(int)$ret["days"];
		$diff=$total_book_time/$total_service_time;
		if(!$diff) $diff=1; 	
		$final_cost=($diff)*($option_price + $price);
		if($final_cost==0) $final_cost=$price;
		if($loading_dates){
		   $loading_price=tep_loading_price($loading_dates['loading_price_dates'],$loading_dates['start_date'],$loading_dates['end_date'],$loading_dates['start_time'],$loading_dates['end_time'],$service["booking_type"],$final_cost);
		   $final_cost=round($final_cost+$loading_price);
		}
		return round($final_cost);
	}
	function tep_calc_service_option_cost(&$service,$book_stime,$book_etime,$option_price,$service_costs="",$loading_dates=""){
		$total_service_time=(int)$service["service_total_time"];
		if ($total_service_time==0) $total_service_time=1;
		$ret=tep_time_diff($book_stime,$book_etime);		
		if ($service["booking_type"]=="M") $total_book_time=(int)$ret["minutes"];
		else if ($service["booking_type"]=="H") $total_book_time=(int)$ret["hours"];
		else if($service["booking_type"]=="D") $total_book_time=(int)$ret["days"];
		
		$diff=$total_book_time/$total_service_time;
		if(!$diff) $diff=1;
		$final_cost=(($diff)* ($service_costs + $option_price));		
		if($loading_dates){
			$loading_price=tep_loading_price($loading_dates['loading_price_dates'],$loading_dates['start_date'],$loading_dates['end_date'],$loading_dates['start_time'],$loading_dates['end_time'],$service["booking_type"],$final_cost);
			$final_cost=$final_cost+$loading_price;
		}
		return $final_cost;
	}
		
	// calculate the time difference
	function tep_time_diff($from, $to){
	   if ($from=="" || $to=="") return array();
	   $from_split=split(" ",$from);
	   if($from_split[0]) $from_date=$from_split[0];
	   if($from_split[1]) $from_split_time=split(":",$from_split[1]);
	   if($from_split_time[0]) $from=$from_date.' '.$from_split_time[0].':'.$from_split_time[1];
	   
	   $to_split=split(" ",$to);
	   if($to_split[0]) $to_date=$to_split[0];
	   if($to_split[1]) $to_split_time=split(":",$to_split[1]);
	   if($to_split_time[0]) $to=$to_date.' '.$to_split_time[0].':'.$to_split_time[1];
	   	
	   $fromtime=@strtotime($from);
	   $totime=@strtotime($to);
	   $start_time_split=split(":",$start_time);
	   $end_time_split=split(":",$end_time);
	   $s_hour=$start_time_split[0];
	   $e_hour=$end_time_split[0];
	   $timediff = $totime-$fromtime;
	   if(($fromtime==$totime && ($s_hour==00 && $e_hour==23)) || !$timediff) $timediff=1;
	   //check for leap years in the middle	 	
	   if (@date('Y',$fromtime)>0 && @date('Y',$totime)>0){
		   for($i=@date('Y',$fromtime); $i<=@date('Y',$totime); $i++){
			   if ((($i%4 == 0) && ($i%100 != 0)) || ($i%400 == 0)) {
				   $timediff -= 24*60*60;
			   }
		   }
	   }
	   $remain = $timediff;
	   $remain            = $remain%(365*24*60*60); 
	   if($remain<1) $remain=1;
	   $ret['days']    = ceil($remain/(24*60*60));
	   $remain            = $remain%($ret['days']*24*60*60);
	   $ret['minutes']    = intval(($remain/60+1));
	   $ret["hours"]=$ret['minutes']/60;
	   $ret['seconds']    = $remain%60;
	   return $ret;
	}
function tep_get_service_category_notes($service_category_id, $language_id) {
    $service_category_query = tep_db_query("select services_categories_notes from " . TABLE_SERVICES_CATEGORIES_DESCRIPTION . " where services_categories_id = '" . (int)$service_category_id . "' and language_id = '" . (int)$language_id . "'");
	
    $service_category = tep_db_fetch_array($service_category_query);

    return $service_category['services_categories_notes'];
  }
  
 function formated_type_dates($type='dates',$price_value=false,$loadingtype=false){
	global $service,$nb_dates,$sInfo,$combo_start_date,$recurring_type,$service_id,$type_start_date,$type_end_date;
	$start_date=$type_start_date;
	$end_date=$type_end_date;
	if(!is_object($service)){
		 $service_info=get_services_info($service['service_id']);
		 $span_days=$service_info["span_days"];
		 $booking_type=$service_info["booking_type"];
		 $time_length=$service_info["service_total_time"];
	}else {
		$span_days=$service->span_days;
		$booking_type=$service->booking_type;
		$time_length=$service->service_total_time;
	}
	$total_dates_nb=array();
	$total_dates_nbdates=array();
	$no_b_stime=$sInfo->no_booking_start_time;
	$no_b_etime=$sInfo->no_booking_end_time;
	$price=0;
    $loading_type="";
	if($booking_type=='D'){
		$no_b_stime="00:00:00";
		$no_b_etime="24:00:00";
	}
	for($i=0;$i<sizeof($nb_dates);$i++){
		$no_b_sdate=$nb_dates[$i];
		$no_b_edate=$nb_dates[$i];
	  if($end_date>=$no_b_sdate && $end_date>=$no_b_edate){ 
		if($price_value) $price=$nb_dates['price'];
		if($loadingtype) $loading_type=$nb_dates['price_type'];
			if($no_b_etime<=$no_b_stime && $span_days=='Y')
				$no_b_edate=date("Y-m-d",dateadd(@strtotime($no_b_sdate),"day",1));
			else if($no_b_etime<=$no_b_stime && $span_days=='N')
				$no_b_etime="24:00:00";
			$total_dates_nb[]=array('price'=>$price,'loading_type'=>$loading_type,'type'=>$recurring_type,'n_s_date'=>$no_b_sdate,'n_e_date'=>$no_b_edate,'n_s_time'=>$no_b_stime,'n_e_time'=>$no_b_etime);
			if($no_b_stime=='00:00:00' && ($no_b_etime>=(24-$time_length).':05:00' && $no_b_etime<='24:00:00'))
				$total_dates_nbdates[format_date($no_b_sdate)]='full';
			if($no_b_stime<=$cur_time && ($no_b_etime>=(24-$time_length).':05:00' && $no_b_etime<='24:00:00') && $no_b_sdate<=$combo_start_date && $no_b_edate>=$combo_start_date)
				$total_dates_nbdates[format_date($no_b_sdate)]='full';
      }
    }
     if($type=='dates')
		return $total_dates_nb;
     else 
		return $total_dates_nbdates;	
  }	

function dateadd($timestamp, $unit, $amount) {
// 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);
   $delta_vars[$unit] += $amount;
   $delta = @mktime($delta_vars["hr"],
   $delta_vars["min"],
   $delta_vars["sec"],
   $delta_vars["mon"],
   $delta_vars["day"],
   $delta_vars["yr"]);
   return $timestamp + $delta;
}

// block date
function service_get_dates_array($sInfo,$type){
	$result_dates=array();
    $caldate=$sInfo->no_booking_start_date;
    $edate=$sInfo->no_booking_end_date;
    $sdate=$sInfo->no_booking_start_date;
	//daily type
	if ($type=='DD')
	  {
		  while ($caldate<=$edate)
		  {
		  	$result_dates[]=$caldate;
			$query = tep_db_query("select date_add('" . $caldate . "',interval '" . $sInfo->recurring_details . "' day) as datenew");
			$result=tep_db_fetch_array($query);
			$caldate=$result['datenew'];
		  }
	  }
	  // weekly type
	  else if ($type=='WW')
	  {
		 $week_splt=split(";",$sInfo->recurring_details);
		 $weekno=$week_splt[0];
		 $splt_week=$week_splt[1];
		 $weekday_splt=split(",",$week_splt[1]);
		 $sta_date=$caldate;
		while(list($key,$value)=each($weekday_splt)){
		   	$weekday.=$value;	
		}
		if ((int)$weekno<=0) return $result_dates;
		if ($weekday=='') return $result_dates;
		 $query = tep_db_query("select date_format('" . $caldate . "', '%w') as weekdate"); 
		 $result=tep_db_fetch_array($query);
		 $query = tep_db_query("select date_sub('" . $caldate . "',interval '" . ($result['weekdate']) . "' day) as caldate");
		 $result=tep_db_fetch_array($query);
		 $caldate=$result['caldate'];
	     while ($caldate<=$edate)
		  {
		   $query = tep_db_query("select date_format('" . $caldate . "', '%d') as day,date_format('" . $caldate .  "', '%m') as month,date_format('" . $caldate . "', '%Y') as year");
		   $result=tep_db_fetch_array($query);
		   $startday=$result['day'];
		   $month=$result['month'];
		   $year=$result['year'];
		   $caldate=date('Y-m-d',mktime(0,0,0,$month,$startday,$year));
		   if ($caldate>$edate) break;
		   for ($icnt=0;$icnt<7;$icnt++){
		     $caldate=date('Y-m-d',mktime(0,0,0,$month,$startday,$year));
		     $week_array=split(",",$splt_week);
		      if ($caldate>$edate) break;
			while(list(,$value)=each($week_array)){
			      if($value==$icnt && $sta_date<=$caldate){
			 	$result_dates[]=$caldate;
		     	    }	
			}	
			 $startday=$startday+1;
   		     }
			  $query = tep_db_query("select date_add('" . $caldate . "',interval '" . ((($weekno-1) * 7)+1) . "' day) as datenew");
		     $result=tep_db_fetch_array($query);
		     $caldate=$result['datenew'];
		  }
	  }
	  //monthly day
	  else if ($type=='MD')
	  {
		$query = tep_db_query("select date_format('" . $caldate . "', '%d') as day,date_format('" . $caldate .  "', '%m') as month,date_format('" . $caldate . "', '%Y') as year");
		$result=tep_db_fetch_array($query);
		$month_splt=split(";",$sInfo->recurring_details);		
		$day=$month_splt[0];
		$months=$month_splt[1];
		
		$month=$result['month'];
		$year=$result['year'];
		
		if ($day<$result['day']) $month=$month+$months;
		$caldate=date('Y-m-d',mktime(0,0,0,$month,$day,$year));
  	         while ($caldate<=$edate)
		  {
		    $result_dates[]=$caldate;
		    $month=$month+$months;
			$caldate=date('Y-m-d',mktime(0,0,0,$month,$day,$year));	
		  }			 
	  }
	  //Monthly month
	  else if ($type=='MM')
	  {
		 $query = tep_db_query("select date_format('" . $caldate . "', '%d') as day,date_format('" . $caldate .  "', '%m') as month,date_format('" . $caldate . "', '%Y') as year");
		 $result=tep_db_fetch_array($query);
		 $week_splt=split(";",$sInfo->recurring_details);
		 $weekno=$week_splt[0]+1;
		 $weekday=$week_splt[1];
			
		 $day=1;
		 $month=$result['month'];
		 $year=$result['year'];
		
     		$caldate=date('Y-m-d',mktime(0,0,0,$month,$day,$year));
	       while ($caldate<=$edate)
		  {
		   $day='01';
		   $query = tep_db_query("select date_format('" . $caldate . "', '%w') as weekdate");
		   $result=tep_db_fetch_array($query);			  
		   $weekdate=$result['weekdate'];
		   $months=$week_splt[2];
		   if ($weekdate>$weekday)
		     $day=$day+(7-$weekdate)+$weekday;
		   else
		     $day=$day+($weekday-$weekdate);
			 
       if ($weekno>1) $day=$day+($weekno-1)*7; 
		   $caldate=date('Y-m-d',mktime(0,0,0,$month,$day,$year));
		   if ($caldate>$edate) break;
		   if ($caldate>$sdate){
			$result_dates[]=$caldate;
		    }
		    $month=$month+$months;
			$caldate=date('Y-m-d',mktime(0,0,0,$month,'01',$year));
		  }			 
	  }
	  else if ($type=='YD')
	  {
		 $query = tep_db_query("select date_format('" . $caldate . "', '%d') as day,date_format('" . $caldate .  "', '%m') as month,date_format('" . $caldate . "', '%Y') as year");
		 $result=tep_db_fetch_array($query);
		 $splt=split(";",$sInfo->recurring_details); 
		 $day=$splt[1];
		 
		 $month=$splt[0]+1;
		 $month=(($month<10)?'0'.$month:$month);
		 $year=$result['year'];
			
		 if ($month<$result['month'] ){
		  $year=$year+1;
				 }
		 else if($month==$result['month']){
		 	 if($day<=$result['day']){
			 	$year+=1;
				}
				}
     	 $caldate=date('Y-m-d',mktime(0,0,0,$month,$day,$year));
		 while ($caldate<=$edate)
		  {
           $result_dates[]=$caldate;
		   $year=$year+1;
		   $caldate=date('Y-m-d',mktime(0,0,0,$month,$day,$year));
		   
		   
		  }			 
	  }
	  else if ($type=='YY')
	  {
		 $query = tep_db_query("select date_format('" . $caldate . "', '%d') as day,date_format('" . $caldate .  "', '%m') as month,date_format('" . $caldate . "', '%Y') as year");
		 $result=tep_db_fetch_array($query);
		 $splt=split(";",$sInfo->recurring_details);	
		 $weekno=$splt[0]+1;
		 $weekday=$splt[1];
		
		 $day=1;
		 $month=$splt[2]+1;
		 
		 $year=$result['year'];
     		 $caldate=date('Y-m-d',mktime(0,0,0,$month,$day,$year));
	     	while ($caldate<=$edate)
		  {
		   $day='01';
		   $query = tep_db_query("select date_format('" . $caldate . "', '%w') as weekdate");
		   $result=tep_db_fetch_array($query);			  
		   $weekdate=$result['weekdate'];
		
		   if ($weekdate>$weekday)
		     $day=$day+(7-$weekdate)+$weekday;
		   else
		     $day=$day+($weekday-$weekdate);
                     if ($weekno>1) $day=$day+($weekno-1)*7; 
					
		   
		   $caldate=date('Y-m-d',mktime(0,0,0,$month,$day,$year));
		   if ($caldate>$edate) break;
		   if ($caldate>$sdate){
                        $result_dates[]=$caldate;		      
		    }
		    $year=$year+1;
			$caldate=date('Y-m-d',mktime(0,0,0,$month,'01',$year));
		  }			 
	  }
   return $result_dates;
 }
 
 function tep_get_resource($field,$resource_id,$language_id){
    if($field=='' && $resource_id=='' && $language_id=='') return;
 	$resource_query=tep_db_query("select " .$field . " from " . TABLE_RESOURCES . " re," . TABLE_RESOURCES_DESCRIPTION . " red where red.language_id='" .(int)$language_id ."' and re.resource_id=red.resource_id and re.resource_id='".$resource_id."'");
    $resource=tep_db_fetch_array($resource_query);
	if(tep_db_num_rows($resource_query)>0)
		return $resource[$field];
	else
		return "0";	
  }

function get_details($field,$table,$where){
		$list_array=array();
		if($field=='' || $table=='') return;
		$select_query=tep_db_query("select ".(($field=='')?'*':$field)." from " . $table . " where " . $where);
		$splt_field=split(",",$field);
		if(tep_db_num_rows($select_query)>0){	
			$list_array[]=tep_db_fetch_array($select_query);	
		}else {
			return;
		}
	     
		return $list_array;
   }	
function get_orders_products_quantity($service_id,$start_date,$end_date,$start_time,$end_time,$booking_type='H',$resource_id=0){
	global $mode,$id,$resource_id;
	if($service_id==0) return;
	$res_quantity="";
	$where="";	
	if($mode=='edit' && $id) $where_check=" and os.orders_products_id not in('".(int)$id."')";
	$where.="and os.resource_id='".(int)$resource_id."'  and (('".$start_date.' '.$start_time."'>=concat(os.start_date,' ',os.start_time) and '".$start_date.' '.$start_time."'<=concat(os.end_date,' ',os.end_time)) OR ('".$end_date.' '.$end_time."'>=concat(os.start_date,' ',os.start_time) and '".$end_date . ' '.$end_time."'<=concat(os.end_date,' ',os.end_time)) OR ('".$start_date.' '.$start_time."'<=concat(os.start_date,' ',os.start_time) and '".$end_date.' '.$end_time."'>=concat(os.end_date,' ',os.end_time))) group by op.products_id";
	$get_edit_customer_basket=tep_db_query("select op.customers_basket_quantity as quantity,op.products_id from ".TABLE_CUSTOMERS_BASKET." op,".TABLE_CUSTOMERS_BASKET_SERVICES ." os  where  op.products_id=os.products_id ".$where."");
	$get_edit_order=tep_db_query("select sum(op.products_quantity) as quantity,op.orders_products_id,os.start_date,os.end_date,os.start_time,os.end_time from ".TABLE_ORDERS_EDIT_PRODUCTS." op,".TABLE_ORDERS_EDIT_SERVICES ." os  where os.orders_id=op.orders_id and op.orders_products_id=os.orders_products_id and op.products_id=os.products_id and  op.products_id='".(int)$service_id."'".$where_check.$where."");
	$get_order_quantity=tep_db_query("select sum(op.products_quantity) as quantity from " .TABLE_ORDERS_PRODUCTS." op,".TABLE_ORDERS_SERVICES ." os where op.orders_products_id=os.orders_products_id and os.products_id=op.products_id and os.orders_id=op.orders_id and op.products_type='V' and op.orders_products_status!=5 and op.products_id='".(int)$service_id . "'".$where_check .$where."");
	if(tep_db_num_rows($get_edit_customer_basket)>0){
	  while($order_edit_quantity=tep_db_fetch_array($get_edit_customer_basket)){
	   $pro_id=substr($order_edit_quantity['products_id'],1,strpos($order_edit_quantity['products_id'],"{")-1);
	    if($pro_id==$service_id){
	   	  $res_quantity+=$order_edit_quantity['quantity'];
	    }
	  }
	}
	if(tep_db_num_rows($get_edit_order)>0){
		$order_edit_quantity=tep_db_fetch_array($get_edit_order);
		$res_quantity+=$order_edit_quantity['quantity'];
	}			 
	if(tep_db_num_rows($get_order_quantity)>0){
		$order_quantity=tep_db_fetch_array($get_order_quantity);
		$res_quantity+=$order_quantity['quantity'];
	}
	return $res_quantity;
}
function get_resource_ids($service_id,$start_date,$end_date,$start_time,$end_time,$booking_type,$return_type='',$resource_id=''){
    global $mode,$id,$languages_id;
    
	if($service_id==0) return;
	else if($service_id) $service=get_services_info((int)$service_id,(int)$languages_id);
	$resource_ids=array();
	$where="";
	$start_time.=':00';
	$end_time.=':00';
	$check="";
	$resource_dates=array();
	if($resource_id) $where=" and os.resource_id='".(int)$resource_id."'";
	$check=" and (o.orders_status>1 or date_add(o.date_purchased,interval '".$service['pending_period']."' day)>'" . getServerDate(true) . "' and op.orders_products_status!=5)";
	if($mode=='edit' && $id) $where_check=" and op.orders_products_id not in('".(int)$id."')";
	$where.="and (('".$start_date.' '.$start_time."'>=concat(os.start_date,' ',os.start_time) and '".$start_date.' '.$start_time."'<=concat(os.end_date,' ',os.end_time)) OR ('".$end_date.' '.$end_time."'>=concat(os.start_date,' ',os.start_time) and '".$end_date . ' '.$end_time."'<=concat(os.end_date,' ',os.end_time)) OR ('".$start_date.' '.$start_time."'<=concat(os.start_date,' ',os.start_time) and '".$end_date.' '.$end_time."'>=concat(os.end_date,' ',os.end_time)))";
	$get_edit_customer_basket=tep_db_query("select op.products_id,os.resource_id,os.end_date,os.end_time from ".TABLE_CUSTOMERS_BASKET." op,".TABLE_CUSTOMERS_BASKET_SERVICES ." os  where  op.products_id=os.products_id ".$where."");
	$get_edit_order=tep_db_query("select os.resource_id,os.end_date,os.end_time from ".TABLE_ORDERS_EDIT_PRODUCTS." op,".TABLE_ORDERS_EDIT_SERVICES ." os  where os.orders_id=op.orders_id and op.orders_products_id=os.orders_products_id and op.products_id=os.products_id and  op.products_id='".(int)$service_id."'".$where.$where_check."");
	$get_order_quantity=tep_db_query("select os.resource_id,os.end_date,os.end_time from " . TABLE_ORDERS . " o, "  .TABLE_ORDERS_PRODUCTS." op,".TABLE_ORDERS_SERVICES ." os where os.products_id=op.products_id and o.orders_id=op.orders_id and o.orders_id=os.orders_id and os.orders_id=op.orders_id and op.products_type='V' and op.products_id='".(int)$service_id . "'".$where.$where_check . $check );
	
	if(tep_db_num_rows($get_edit_customer_basket)>0){
	  while($order_edit_quantity=tep_db_fetch_array($get_edit_customer_basket)){
	   $pro_id=substr($order_edit_quantity['products_id'],1,strpos($order_edit_quantity['products_id'],"{")-1);
	    if($pro_id==$service_id){
	   	  $resource_ids[].=$order_edit_quantity['resource_id'];
	   	  $resource_dates[].=$order_edit_quantity['end_date'].' '.$order_edit_quantity['end_time'];
	    }
	  }
	}
	if(tep_db_num_rows($get_edit_order)>0){
		while($order_edit_quantity=tep_db_fetch_array($get_edit_order)){
			$resource_ids[].=$order_edit_quantity['resource_id'];
			$resource_dates[].=$order_edit_quantity['end_date'].' '.$order_edit_quantity['end_time'];
		}
	}			 
	if(tep_db_num_rows($get_order_quantity)>0){
		while($order_quantity=tep_db_fetch_array($get_order_quantity)){
			$resource_ids[].=$order_quantity['resource_id'];
			if($resource_id && $resource_id==$order_quantity['resource_id']) $resource_ids[].=$order_quantity['resource_id'];
			if($return_type=='dates' && $resource_id==$order_quantity['resource_id']) $resource_dates[].=$order_quantity['end_date'].' '.$order_quantity['end_time'];	
		}
	}
	if($return_type=='dates')
	return $resource_dates;
	else if($return_type=='')
	return $resource_ids;
}
function form_recurring_array($sdate,$edate,$stime,$etime,$s_time,$e_time,$rtype,$rdetails) 
{
global $suInfo;
$week_array=array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
$month_array=array('Jan','Feb','Mar','Apr','May','June','July','Aug','Sep','Oct','Nov','Dec');
$count_array=array('first','second','third','fourth');
$recurring_id="";
$recurring_text="";
	if($rtype!="DD")
				$recurring_details_array=split(";",$rdetails);
			switch($rtype)
			{
				case "DD":
					$daily_days=$rdetails;
					$recurring_text=sprintf(TEXT_DAILY_OPTION,$daily_days); 
					break;
				case "WW":
					$temp_week_selected="";
					$week=tep_db_prepare_input($HTTP_POST_VARS['no_booking_week_days']);
					$weekly_weeks=$recurring_details_array[0];
					$week_selected=$recurring_details_array[1];
					$week_selected_array=split(",",$week_selected);
					if(sizeof($week_selected_array)>0)
					{
					for($icnt=0;$icnt<sizeof($week_selected_array);$icnt++)
						{
							$cnt=$week_selected_array[$icnt];
							$temp_week_selected.=$week_array[$cnt] . "," ;
						}
					}
					$selected_days=substr($temp_week_selected,0,-1);
					$recurring_text=sprintf(TEXT_WEEKLY_OPTION,$weekly_weeks,$selected_days);
					break;
				case "MD":
					$monthly_days=$recurring_details_array[0];
					$monthly_months=$recurring_details_array[1];
					$recurring_text=sprintf(TEXT_MONTHLY_DAYS_OPTION,$monthly_days,$monthly_months);
					break;
				case "MM":
					$monthly_weeks=$count_array[$recurring_details_array[0]];
					$monthly_week_days=$week_array[$recurring_details_array[1]];
					$monthly_week_months=$recurring_details_array[2];		
					$recurring_text=sprintf(TEXT_MONTHLY_MONTHS_OPTION,$monthly_weeks,$monthly_week_days,$monthly_week_months);
					break;
				case "YD":
					$yearly_months=$month_array[$recurring_details_array[0]];
					$yearly_month_days=$recurring_details_array[1];
					$recurring_text=sprintf(TEXT_YEARLY_MONTHS_OPTION,$yearly_months,$yearly_month_days);
					break;
				case "YY":
					$yearly_weeks=$count_array[$recurring_details_array[0]];
					$yearly_week_days=$week_array[$recurring_details_array[1]];
					$yearly_week_months=$month_array[$recurring_details_array[2]];	
					$recurring_text=sprintf(TEXT_YEARLY_YEARS_OPTION,$yearly_weeks,$yearly_week_days,$yearly_week_months);
					break;
				}	
				if($suInfo->booking_type=='D') {
					$recurring_text.= sprintf(TEXT_NO_DAYS,format_date($sdate),format_date($edate));
				}else {
					$recurring_text.= sprintf(TEXT_DAYS_AND_TIME,format_date($sdate),format_date($edate),$s_time,$e_time);
				}
				$recurring_id=format_date($sdate)."#".format_date($edate)."#".$stime."#".$etime."#".$rtype."#".$rdetails;
				$no_booking_array=array('id'=>$recurring_id,
										'text'=>$recurring_text);
				return $no_booking_array;
											
}		

function form_load_recurring_array($sdate,$edate,$stime,$etime,$s_time,$e_time,$rtype,$rdetails,$rprice,$ltype,$list=false) 
{
global $suInfo;
$loading_week_array=array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
$loading_month_array=array('Jan','Feb','Mar','Apr','May','June','July','Aug','Sep','Oct','Nov','Dec');
$loading_count_array=array('first','second','third','fourth');
$loading_recurring_id="";
$loading_recurring_text="";
	if($rtype!="DD")
				$loading_recurring_details_array=split(";",$rdetails);
			switch($rtype)
			{
				case "DD":
					$loading_daily_days=$rdetails;
					$loading_recurring_text=sprintf(TEXT_DAILY_OPTION,$loading_daily_days); 
					break;
				case "WW":
					$loading_temp_week_selected="";
					$loading_week=tep_db_prepare_input($HTTP_POST_VARS['loadings_week_days']);
					$loading_weekly_weeks=$loading_recurring_details_array[0];
					$loading_week_selected=$loading_recurring_details_array[1];
					$loading_week_selected_array=split(",",$loading_week_selected);
					if(sizeof($loading_week_selected_array)>0)
					{
					for($icnt=0;$icnt<sizeof($loading_week_selected_array);$icnt++)
						{
						$cnt=$loading_week_selected_array[$icnt];
						$loading_temp_week_selected.=$loading_week_array[$cnt] . "," ;
						}
					}
					$loading_selected_days=substr($loading_temp_week_selected,0,-1);
					$loading_recurring_text=sprintf(TEXT_WEEKLY_OPTION,$loading_weekly_weeks,$loading_selected_days);
					break;
				case "MD":
					$loading_monthly_days=$loading_recurring_details_array[0];
					$loading_monthly_months=$loading_recurring_details_array[1];
					$loading_recurring_text=sprintf(TEXT_MONTHLY_DAYS_OPTION,$loading_monthly_days,$loading_monthly_months);
					break;
				case "MM":
					$loading_monthly_weeks=$loading_count_array[$loading_recurring_details_array[0]];
					$loading_monthly_week_days=$loading_week_array[$loading_recurring_details_array[1]];
					$loading_monthly_week_months=$loading_recurring_details_array[2];		
					$loading_recurring_text=sprintf(TEXT_MONTHLY_MONTHS_OPTION,$loading_monthly_weeks,$loading_monthly_week_days,$loading_monthly_week_months);
					break;
				case "YD":
					$loading_yearly_months=$loading_month_array[$loading_recurring_details_array[0]];
					$loading_yearly_month_days=$loading_recurring_details_array[1];
					$loading_recurring_text=sprintf(TEXT_YEARLY_MONTHS_OPTION,$loading_yearly_months,$loading_yearly_month_days);
					break;
				case "YY":
					$loading_yearly_weeks=$loading_count_array[$loading_recurring_details_array[0]];
					$loading_yearly_week_days=$loading_week_array[$loading_recurring_details_array[1]];
					$loading_yearly_week_months=$loading_month_array[$loading_recurring_details_array[2]];	
					$loading_recurring_text=sprintf(TEXT_YEARLY_YEARS_OPTION,$loading_yearly_weeks,$loading_yearly_week_days,$loading_yearly_week_months);
					break;
				}	
				if($ltype=='P')
					$rload=$rprice." %";
				else
					$rload=$rprice;
				if($suInfo->booking_type=='D') {
					$loading_recurring_text.= sprintf(TEXT_NO_DAYS_LOADINGS,format_date($sdate),format_date($edate),$rload);
				}else {
					$loading_recurring_text.= sprintf(TEXT_LOAD_DAYS_AND_TIME,format_date($sdate),format_date($edate),$s_time,$e_time,$rload);		
				}
				$loading_recurring_id=format_date($sdate)."#".format_date($edate)."#".$stime."#".$etime."#".$rtype."#".$rdetails."#".$rprice."#".$ltype;
				$loading_array=array('id'=>$loading_recurring_id,
									'text'=>$loading_recurring_text);
				if($list){
					$loading_array=array('id'=>$loading_recurring_id);
				}
				return $loading_array;			
	}
	
function tep_loading_price($loading_price_dates,$start_date,$end_date,$start_time,$end_time,$booking_type,$final_price){
    if($start_date=="" && $end_date=="" && $start_time=="" && $end_time=="") return;
    $price="";	
    $start_time.=":00";
    $end_time.=":00";	
    $loading_price="";		
  
  if(is_array($loading_price_dates)){	
	for($i=0;$i<sizeof($loading_price_dates);$i++){
	  for($j=0;$j<sizeof($loading_price_dates[$i]);$j++){
			if($booking_type=='D'){
				$loading_start_time=split(" ",$loading_price_dates[$i][$j]['n_s_date']);	
				$loading_end_time=split(" " ,$loading_price_dates[$i][$j]['n_e_date']);
				$loading_start_time=$loading_start_time[0];
				$loading_end_time=$loading_end_time[0];
				$select_start_time=$start_date;
				$select_end_time=$end_date;
			}else{
				$loading_start_time=$loading_price_dates[$i][$j]['n_s_date'].' '.$loading_price_dates[$i][$j]['n_s_time'];
				$loading_end_time=$loading_price_dates[$i][$j]['n_e_date'].' '.$loading_price_dates[$i][$j]['n_e_time'];
				$select_start_time=$start_date.' '.$start_time;
				$select_end_time=$end_date.' '.$end_time;
			}
			$loading_price=$loading_price_dates[$i][$j]['price']; 
			$loading_type=$loading_price_dates[$i][$j]['loading_type'];
			if($loading_type=='P'){
				$loading_price=($final_price*$loading_price)/100;		
			}
			if((($select_start_time>=$loading_start_time and $select_end_time<=$loading_end_time) OR  ($select_end_time>=$loading_start_time and $select_end_time<=$loading_end_time) OR  ($select_start_time<=$loading_start_time and $select_end_time>=$loading_end_time))){
				$price+=$loading_price;	
				
			}
	       }
            }
     }	
	return $price;
}

	function tep_time_diff_in_format($from,$to,$format="D"){
		
  	   if ($from=="" || $to=="") return array();

	   $fromtime=@strtotime($from);
	   $totime=@strtotime($to);
	   $timediff = $totime-$fromtime;

	   //check for leap years in the middle
	   if ((int)date('Y',$fromtime)>0 && (int)date('Y',$totime)>0){
		   for($i=date('Y',$fromtime); $i<=date('Y',$totime); $i++){
			   if ((($i%4 == 0) && ($i%100 != 0)) || ($i%400 == 0)) {
				   $timediff -= 24*60*60;
			   }
		   }
	   }
	   $remain = $timediff;
	   $remain = $remain%(365*24*60*60);
		if ($format=="D"){
		   $result = ceil($remain/(24*60*60));
		} else if ($format=="H") {
		
			$remain = $remain = ceil($remain/(60*60));
			$result= $remain;
		}
		
		
	  return $result;
	}
	
	function tep_time_service_diff_in_format($from,$to,$format="D"){
		
  	   if ($from=="" || $to=="") return array();

	   $fromtime=@strtotime($from);
	   $totime=@strtotime($to);
	   $timediff = $totime-$fromtime;

	   //check for leap years in the middle
	   if ((int)date('Y',$fromtime)>0 && (int)date('Y',$totime)>0){
		   for($i=date('Y',$fromtime); $i<=date('Y',$totime); $i++){
			   if ((($i%4 == 0) && ($i%100 != 0)) || ($i%400 == 0)) {
				   $timediff -= 24*60*60;
			   }
		   }
	   }
	   $remain = $timediff;
	   $remain = $remain%(365*24*60*60);
		if ($format=="D"){
		   $result = ceil($remain/(24*60*60));
		} //else if ($format=="H") {
	  return $result;
	}
	
 function tep_get_service_booking_details($orders_id){
  if($orders_id==0) return;
   $get_details_query=tep_db_query("select op.products_name,os.start_date,os.end_date,os.start_time,os.end_time,os.resource_id,os.resource_name,op.products_quantity,op.products_id from ".TABLE_ORDERS_PRODUCTS . " op,".TABLE_ORDERS_SERVICES." os,".TABLE_ORDERS." o where op.orders_products_id=os.orders_products_id and o.orders_id=op.orders_id and os.products_id=op.products_id and os.orders_id=op.orders_id and os.orders_id='".(int)$orders_id."' and op.products_type='V' and op.orders_products_status!=5 and o.orders_id='".(int)$orders_id."' order by o.date_purchased");
     if(tep_db_num_rows($get_details_query)>0){
		$service_details=array();
		while($get_details=tep_db_fetch_array($get_details_query)){
			if($get_details['end_date'] && $get_details['end_time']) $date_time=@strtotime($get_details['end_date'] .' '.$get_details['end_time'])+60;
			if($date_time!='') {
				$get_details['end_date']=date('Y-m-d',$date_time);
				$get_details['end_time']=date('H:i',$date_time);
			}
			$service_details[]=array('start_date'=>$get_details['start_date'],'end_date'=>$get_details['end_date'],'start_time'=>$get_details['start_time'],'end_time'=>$get_details['end_time'],'resource_id'=>$get_details['resource_id'],'resource_name'=>$get_details['resource_name'],'products_quantity'=>$get_details['products_quantity'],'products_name'=>$get_details['products_name']);
		}
	 }
	 return $service_details;
  }

function get_loading_array($service_id){
 global $service,$nb_dates,$sInfo,$loading_type,$recurring_type;
 if($service_id=="") return;
 $loading_price_dates=array();
 $loading_query=tep_db_query("select loadings_start_date as no_booking_start_date, loadings_end_date as no_booking_end_date,loadings_start_time as no_booking_start_time,loadings_end_time as no_booking_end_time,recurring_type, recurring_details,loadings_price,loadings_type from " . TABLE_SERVICES_LOADINGS. "  where service_id= '" .(int)$service_id."' order by recurring_type,loadings_start_date");
 while($nbk=tep_db_fetch_array($loading_query)) {
    $sInfo=new objectInfo($nbk);
	$recurring_type=$sInfo->recurring_type;
	$nb_dates=service_get_dates_array($sInfo,$recurring_type);
	$price=$sInfo->loadings_price;
	$loading_type=$sInfo->loadings_type;
	$nb_dates['price']=round($price);
	$nb_dates['price_type']=$loading_type;
	$type_start_date=$nbk['no_booking_start_date'];
	$type_end_date=$nbk['no_booking_end_date'];
	$loading_price_dates[]=formated_type_dates('dates',true,true);
 }
 
  return $loading_price_dates;
}

function get_services_info($service_id,$lan_id="1"){
		if($service_id==0  && $lan_id==0) return;	
		$service_query=tep_db_query("select * from ".TABLE_SERVICES ." se, ".TABLE_SERVICES_DESCRIPTION." sed where sed.service_id=se.service_id and sed.language_id='".(int)$lan_id."' and se.service_id='".(int)$service_id."'".SERVICES_CONDITION_STATUS);
		$service_info=tep_db_fetch_array($service_query);
		return $service_info;
}
function tep_check_service_found($service_id,$start_date,$end_date,$start_time,$end_time,$type=""){
		global $service,$quantity,$resource_id;
		$service_info=$service;
		$reserved_quantity="";
		$where="";
		$error="";
		$return="";
		$booking_type=$service_info['booking_type'];
		$include_resource_price=$service_info['include_resource_price'];
		$service_quantity=(($service_info['include_resource']=='Y')?1:$service_info['quantity']);
		// get order edit products
		$reserved_quantity+=get_orders_products_quantity($service_id,$start_date,$end_date,$start_time,$end_time,$booking_type,$resource_id)+$quantity;
		// get current product quantity with order_edit_product
		$return=true;
		if($reserved_quantity>$service_quantity){
			$avil_quan=$service_quantity-($reserved_quantity-$quantity);
		   if($avil_quan!=0)
		   	$error=sprintf(ERR_QTY_EXICTED,$avil_quan);
		   else
		   	$error=ERR_TIME_ALREADY_RESERVED;	
			$return=false;
		}
		if($type=='error')
			return $error;
		else
			return $return;
	}
	function get_amount_for_orders($orders_id,$orders_products_id,$product_id){
		global $service,$languages_id;
		$product_cost="";
		if(!$service && $product_id) $service=get_services_info((int)$product_id,$languages_id);
		if($orders_id=="" && $orders_products_id=="" && $product_id=="") return;
		if($service)$total_service_time=(int)$service["service_total_time"];
		   $product_query=tep_db_query("select op.products_id,op.final_price,op.products_tax,products_quantity as quantity,os.start_date,os.start_time,os.end_date,os.end_time from ".TABLE_ORDERS." o,".TABLE_ORDERS_PRODUCTS." op,".TABLE_ORDERS_SERVICES." os where op.orders_id=os.orders_id and o.orders_id=op.orders_id and os.orders_id=op.orders_id and op.orders_products_id=os.orders_products_id and op.products_id=os.products_id and op.orders_products_status!=5 and op.orders_id='".(int)$orders_id."' and op.orders_products_id='".(int)$orders_products_id."' and op.products_id='".(int)$product_id."'");
		   if(tep_db_num_rows($product_query)>0){
		   $product=tep_db_fetch_array($product_query);
		   $ret=tep_time_diff($product['start_date'].' '.$product['start_time'],$product['end_date'].' '.$product['end_time']);
			if ($service["booking_type"]=="M")
				$total_book_time=(int)$ret["minutes"];
			else if ($service["booking_type"]=="H")
				$total_book_time=(int)$ret["hours"];
			else if ($service["booking_type"]=="D") 
				$total_book_time=(int)$ret["days"];			
			$product_cost=$product['quantity']*$product['final_price'];		
		 }
		  return tep_add_tax($product_cost,$product["products_tax"]);
	}
	
function services_dates($service_id,$type=''){
	global $service_id,$no_booking_sdate,$no_booking_edate,$no_booking_dates,$no_booking_stime,$no_booking_etime,$service_start_time,$service_week,$time_length,$nb_dates,$nb_dates_array,$sInfo,$block_dates,$no_booking_sdate_array,$service,$combo_start_date,$recurring_type,$type_start_date,$type_end_date;		
	$lan_id=1;	
	if($languages_id) $lan_id=$languages_id;
	if($service_id)$service_info=get_services_info($service_id,$lan_id="1");
	if($service_info) $service=new objectInfo($service_info);
				$current_date=getServerDate(true);
				$current_time=@strtotime($current_date);
				$combo_end_date=date('Y-m-d',tep_dateadd($current_time,"day",30));
				$combo_start_date=$current_date;
				$booking_type=$service->booking_type; 
			    $current_month=date("n",$current_time);
				$current_year=date("Y",$current_time);
				$year=date("Y",$current_time);
				$month=date("n",$current_time);
				$month_start_time=mktime(0,0,0,$month,1,$year);
				$week_day=date("w",$month_start_time);
				$total_days=date("t",$month_start_time);
				$month_end_time=mktime(0,0,0,$month,$total_days,$year);
				$month_end_date=date('Y-m-d',$month_end_time);
				$service_start_time="00:00:00";
				$service_end_time="24:00:00";
				$total_dates_nb=array();
				$total_dates_nbdates=array();
  if ($booking_type=='H' || $booking_type=='M'){
	$shour=0;
	$ehour=24;
	$no_booking_sdate='';
	$no_booking_edate='';
	$cur_time=date("H",$current_time) .':00:00';
	$span_days=$service->span_days;
	$service_end_time="24:00:00";	
	$bk_query="select no_booking_start_date,no_booking_end_date,no_booking_start_time,no_booking_end_time,recurring_type,recurring_details from ".TABLE_SERVICES_NO_BOOKING_DAYS ." snd where snd.service_id='".(int)$service_id."' and (('$combo_start_date'>=no_booking_start_date and '$combo_start_date'<=no_booking_start_date) OR  ('$combo_end_date'>=no_booking_start_date and '$combo_end_date'<=no_booking_end_date) OR ('$combo_start_date'<=no_booking_start_date and '$combo_end_date'>=no_booking_end_date)) order by no_booking_start_date,no_booking_end_date,no_booking_start_time,no_booking_end_time";
	$bk=tep_db_query($bk_query);
	$dates=array();
	$n_dates=array();
	//echo $combo_start_date.'-'.$combo_end_date;
	while($nbk=tep_db_fetch_array($bk)){					
	$recurring_type=$nbk['recurring_type'];				
	$sInfo=$nbk;													
	if($recurring_type!='DD'){ 
		$nb_dates=tep_get_dates_array($sInfo,$recurring_type);					
		$type_start_date=$combo_start_date;
		$type_end_date=$combo_end_date;			
		$nbd_array[]=formated_type_dates('dates');
		$nb_dates_array[]=formated_type_dates('n_dates');
	}else if($recurring_type=='DD'){
		 $tep_start_date=$combo_start_date;
		 $tep_end_date=$combo_end_date;
		 while($tep_start_date<=$tep_end_date){					    
		    if($nbk['no_booking_start_date']<=$tep_start_date && $nbk['no_booking_end_date']>=$tep_start_date){
		 		$no_b_stime=$nbk['no_booking_start_time'];
				$no_b_etime=$nbk['no_booking_end_time'];
				$no_b_sdate=$no_b_edate=$tep_start_date;
		 		if($no_b_etime<=$no_b_stime && $span_days=='Y') 
					$no_b_edate=date("Y-m-d",tep_dateadd(@strtotime($tep_start_date),"day",1));
				else if($no_b_etime<=$no_b_stime && $span_days=='N')
					$no_b_etime="24:00:00";
				if($tep_start_date<=$no_b_sdate && $tep_end_date>=$no_b_sdate){								
					$booking_total[]=array('start_date'=>$no_b_sdate,'end_date'=>$no_b_edate,'start_time'=>$no_b_stime,'end_time'=>$no_b_etime);								
					$nbd_array[][]=array('type'=>$recurring_type,'n_s_date'=>$no_b_sdate,'n_e_date'=>$no_b_edate,'n_s_time'=>$no_b_stime,'n_e_time'=>$no_b_etime);
				$nb_split=split(':',$no_b_stime);
				//echo date("d",mktime(($nb_split[0]+$time_length),$mt,0,1,1,1987)).'-'.$nb_split[0].'-'.$time_length.'-'.$mt.'<br>';  														 
				if($no_b_stime=='00:00:00' && ($no_b_etime>=(24-$time_length).':05:00' && $no_b_etime<='24:00:00') || (($booking_type=='H' || $booking_type=='M') && $time_length!=''  && date("d",mktime(($nb_split[0]+$time_length),$mt,0,1,1,1987))=="02"))
					$nb_dates_array[][format_date($no_b_sdate)]='full';
				if($no_b_stime<=$cur_time && ($no_b_etime>=(24-$time_length).':05:00' && $no_b_etime<='24:00:00') && $no_b_sdate<=$combo_start_date && $no_b_edate>=$combo_start_date)
					$nb_dates_array[][format_date($no_b_sdate)]='full';
			  }  	
		 	}					 	
		   if($tep_start_date) $tep_start_date=date('Y-m-d',tep_dateadd(@strtotime($tep_start_date),"day",1));
			 }
		}								
		}
		$block_dates=$nb_dates_array;				
		$dates_array=tep_get_service_dates_array($combo_start_date,$combo_end_date,$booking_type);
		$select_sdate=$start_date;
		$select_stime=$start_time;
		$select_edate=$end_date . " " . $end_time;
	  } else {
				$shour=0;
				$ehour=24;
				$no_booking_sdate='';
				$no_booking_edate='';
				$cur_time=date("H",$current_time) .':00:00';
				$span_days=$service->span_days;
				$service_end_time="24:00:00";
				//$bk_query="select recurring_type,recurring_details,no_booking_start_date,no_booking_end_date,no_booking_start_time,no_booking_end_time,recurring_type,recurring_details from ".TABLE_SERVICES_NO_BOOKING_DAYS ." snd where snd.service_id='". $service_id . "' order by recurring_type,no_booking_end_date";
				$bk_query="select no_booking_start_date,no_booking_end_date,no_booking_start_time,no_booking_end_time,recurring_type,recurring_details from ".TABLE_SERVICES_NO_BOOKING_DAYS ." snd where snd.service_id='".(int)$service_id."' and (('$current_date'>=no_booking_start_date and '$current_date'<=no_booking_start_date) OR  ('$combo_end_date'>=no_booking_start_date and '$combo_end_date'<=no_booking_end_date) OR ('$current_date'<=no_booking_start_date and '$combo_end_date'>=no_booking_end_date)) order by no_booking_start_date,no_booking_end_date,no_booking_start_time,no_booking_end_time";
				$bk=tep_db_query($bk_query);
				$dates=array();
				$n_dates=array();
				$sel_ssplit=split(" ",$current_date);
				$select_sdate=$sel_ssplit[0];
				while($nbk=tep_db_fetch_array($bk)){
					$recurring_type=$nbk['recurring_type'];					
					if($recurring_type!='DD'){ 
						$nb_dates=service_get_dates_array($sInfo,$recurring_type);					
						$type_start_date=$select_sdate;
						$type_end_date=$combo_end_date;					
						$nbd_array[]=formated_type_dates('dates');
						$nb_dates_array[]=formated_type_dates('n_dates');
					}else if($recurring_type=='DD'){					 					 					 	
					 	if($booking_type=='D') $no_booking_sdate_array[]=array('start_date'=>$nbk['no_booking_start_date'],'end_date'=>$nbk['no_booking_end_date']);					 						
					 	$tep_start_date=$select_sdate;											
					 	$tep_end_date=$combo_end_date;					 
					 	while($tep_start_date<=$tep_end_date){					   					    
						    if($nbk['no_booking_start_date']<=$tep_start_date && $nbk['no_booking_end_date']>=$tep_start_date){					 		
					 		$no_b_stime=$nbk['no_booking_start_time'];
							$no_b_etime=$nbk['no_booking_end_time'];													
							$no_b_sdate=$no_b_edate=$tep_start_date;
							if($booking_type=='D'){
								$no_b_stime="00:00:00";
								$no_b_etime="24:00:00";
								$nb_dates_array[][format_date($no_b_sdate)]='full';
							}
							//echo $tep_start_date.'-'.$no_b_sdate.'-'.$tep_end_date.'-'.$no_b_sdate.'<br>';								
					 		if($no_b_etime<=$no_b_stime && $span_days=='Y') 
								$no_b_edate=date("Y-m-d",tep_dateadd(@strtotime($tep_start_date),"day",1));
							else if($no_b_etime<=$no_b_stime && $span_days=='N')
								$no_b_etime="24:00:00";
							if($tep_start_date<=$no_b_sdate && $tep_end_date>=$no_b_sdate){								
								$booking_total[]=array('start_date'=>$no_b_sdate,'end_date'=>$no_b_edate,'start_time'=>$no_b_stime,'end_time'=>$no_b_etime);
								//$nbd_array[][]=array('type'=>$recurring_type,'n_s_date'=>$no_b_sdate,'n_e_date'=>$no_b_edate,'n_s_time'=>$no_b_stime,'n_e_time'=>$no_b_etime);
							$nb_split=split(':',$no_b_etime); 														 
							if($no_b_stime=='00:00:00' && ($no_b_etime>=(24-$time_length).':05:00' && $no_b_etime<='24:00:00') || (($booking_type=='H' || $booking_type=='M') && $time_length!='' && date("d",mktime(($nb_split[0]+$time_length),$mt,0,1,1,1987))=="02")){
								$nb_dates_array[][format_date($no_b_sdate)]='full';
							}		
							if($no_b_stime<=$cur_time && ($no_b_etime>=(24-$time_length).':05:00' && $no_b_etime<='24:00:00') && $no_b_sdate<=$combo_start_date && $no_b_edate>=$combo_start_date){
								$nb_dates_array[][format_date($no_b_sdate)]='full';
							}
						  }  	
					 	} 
					   if($tep_start_date) $tep_start_date=date('Y-m-d',tep_dateadd(@strtotime($tep_start_date),"day",1));
					 }
				}
			 }							
			$block_dates=$nb_dates_array;
			$granular=1;			
			$dates_array=tep_get_service_dates_array($current_date,$combo_end_date,$booking_type);
			$select_sdate=$start_date . ' ' . $start_time;
			$select_edate=$end_date . ' ' . $end_time;
		}
		$booking_total=array();
		for($i=0;$i<sizeof($nbd_array);$i++){
		   for($j=0;$j<sizeof($nbd_array[$i]);$j++)
				 $booking_total[]=array('start_date'=>$nbd_array[$i][$j]['n_s_date'],'end_date'=>$nbd_array[$i][$j]['n_e_date'],'start_time'=>$nbd_array[$i][$j]['n_s_time'],'end_time'=>$nbd_array[$i][$j]['n_e_time']);						
		}
		if($type=='service_dates')
			return $dates_array;
		else if($type=='no_booking_dates')
			return $booking_total;		
	}
		
	function tep_services_option($field,$values_id,$service_id) {
    global $languages_id;

    $values = tep_db_query("select ".$field." from " . TABLE_SERVICES_ATTRIBUTES . " sa, " . TABLE_SERVICES_OPTIONS_VALUES . " sov where sa.service_id = '" . $service_id . "' and sa.options_values_id = '" . $values_id . "' and sa.options_values_id = sov.services_options_values_id and sov.language_id = '" . $languages_id . "'" . " order by sa.services_options_sort_order, sa.options_values_price");
      $values_values = tep_db_fetch_array($values);

    return $values_values[$field];
  }
  function tep_get_service_info_tree($customer_id,$parent_id = '0', $spacing = '', $exclude = '', $service_category_tree_array = '', $include_itself = false) {
		global $languages_id,$currencies;
		
		if (!is_array($service_category_tree_array)) $service_category_tree_array = array();
		if ( (sizeof($service_category_tree_array) < 1) && ($exclude != '0') ) $service_category_tree_array[] = array('id' => '0', 'text' => TEXT_TOP);
		
		// if the category is to be included
		if ($include_itself) {
			$service_category_query = tep_db_query("select scd.services_categories_name from " . TABLE_SERVICES_CATEGORIES_DESCRIPTION . " scd where scd.language_id = '" . (int)$languages_id . "' and scd.services_categories_id = '" . (int)$parent_id . "'");
			$service_category = tep_db_fetch_array($category_query);
			$service_category_tree_array[] = array('id' => $parent_id, 'text' => $service_category['services_categories_name'],'mode'=>'C');
		}
		// recursively select the category
		$service_categories_query = tep_db_query("select sc.services_categories_id, scd.services_categories_name, sc.parent_id from " . TABLE_SERVICES_CATEGORIES . " sc, " . TABLE_SERVICES_CATEGORIES_DESCRIPTION . " scd where sc.services_categories_id = scd.services_categories_id and scd.language_id = '" . (int)$languages_id . "' and sc.parent_id = '" . (int)$parent_id . "' order by sc.sort_order, scd.services_categories_name");
		while ($service_categories = tep_db_fetch_array($service_categories_query)) {
			if ($exclude != $service_categories['services_categories_id']) $service_category_tree_array[] = array('id' => $service_categories['services_categories_id'], 'text' => $spacing . $service_categories['services_categories_name']);
			$service_category_tree_array = tep_get_service_info_tree($customer_id,$service_categories['services_categories_id'], $spacing . '&nbsp;&nbsp;&nbsp;', $exclude, $service_category_tree_array);
		}
		
		// select the service
		$service_query=tep_db_query("select sed.service_name,se.service_location,se.service_start_time,sed.service_id,se.service_costs,se.service_tax_class_id  from " . TABLE_SERVICES . ' se, ' . TABLE_SERVICES_DESCRIPTION . " sed, " . TABLE_SERVICES_TO_SERVICES_CATEGORIES . " scd where scd.services_categories_id='" . (int)$parent_id . "' and se.service_id=scd.service_id and se.service_id=sed.service_id  " . SERVICES_CONDITION_STATUS . " and sed.language_id = " . $languages_id . " order by sed.service_name");
		while ($service=tep_db_fetch_array($service_query))
		{
			$service_name=$service["service_name"];

		
			$tax=tep_get_tax_rate($service["service_tax_class_id"]);
			//$price=$currencies->display_price($service["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
			$service_category_tree_array[] = array('id' => $service['service_id'], 'text' => $spacing . $service_name . '&nbsp;<font color=' . $color . '>' . $price . '</font>&nbsp;&nbsp;&nbsp;' . $start_date . $discount_info,'mode'=>'V');
		}    
		
		return $service_category_tree_array;
	}	
	function tep_get_service_uprid($prid, $params) {
  if (is_numeric($prid)) {
    $uprid = $prid;
 
    if (is_array($params) && (sizeof($params) > 0)) {
      $attributes_check = true;
      $attributes_ids = '';
 
      reset($params);
      while (list($option, $value) = each($params)) {
        if (is_numeric($option) && is_numeric($value)) {
          $attributes_ids .= '{' . (int)$option . '}' . (int)$value;
        } else {
          $attributes_check = false;
          break;
        }
      }
 
      if ($attributes_check == true) {
        $uprid .= $attributes_ids;
      }
    }
  } else {
    $uprid = tep_get_prid($prid);
 
    if (is_numeric($uprid)) {
      if (strpos($prid, '{') !== false) {
        $attributes_check = true;
        $attributes_ids = '';
 
// strpos()+1 to remove up to and including the first { which would create an empty array element in explode()
        $attributes = explode('{', substr($prid, strpos($prid, '{')+1));
 
        for ($i=0, $n=sizeof($attributes); $i<$n; $i++) {
          $pair = explode('}', $attributes[$i]);
 
          if (is_numeric($pair[0]) && is_numeric($pair[1])) {
            $attributes_ids .= '{' . (int)$pair[0] . '}' . (int)$pair[1];
          } else {
            $attributes_check = false;
            break;
          }
        }
 
        if ($attributes_check == true) {
          $uprid .= $attributes_ids;
        }
      }
    } else {
      return false;
    }
  }
 
  return "V" . $uprid;
}
function tep_get_service_prid($uprid) {
  $uprid=substr($uprid,1);
  $pieces = explode('{', $uprid);
  if (is_numeric($pieces[0])) {
    return $pieces[0];
  } else {
    return false;
  }
}
//service discount start
	function services_discount($service_id){
		global $dates;
		$return=0;
		$service_amount=$dates['service_costs'];
		if($service_id!=""){
	//	echo "select discount_value,discount_type from ".TABLE_SERVICES_DISCOUNTS." where service_id='".(int)$service_id."' and ((discount_start_date<='".$dates['start_date']."' and discount_end_date>='".$dates['start_date']."') OR (discount_start_date<='".$dates['end_date']."' and discount_end_date>='".$dates['end_date']."')) and ((discount_start_time<='".$dates['start_time']."' and discount_end_time>='".$dates['start_time']."') OR (discount_start_time<='".$dates['end_time']."' and discount_end_time>='".$dates['end_time']."'))";
			$discount_query=tep_db_query("select discount_value,discount_type from ".TABLE_SERVICES_DISCOUNTS." where service_id='".(int)$service_id."' and ((discount_start_date<='".$dates['start_date']."' and discount_end_date>='".$dates['start_date']."') OR (discount_start_date<='".$dates['end_date']."' and discount_end_date>='".$dates['end_date']."')) and ((discount_start_time<='".$dates['start_time']."' and discount_end_time>='".$dates['start_time']."') OR (discount_start_time<='".$dates['end_time']."' and discount_end_time>='".$dates['end_time']."'))");
			if(tep_db_num_rows($discount_query)>0){							
				$discount=tep_db_fetch_array($discount_query);
				$discount_price=$discount['discount_value'];
				$discount_type=$discount['discount_type'];
				$return=$discount_price;
				if($discount_type!='A' && $service_amount!="") $return=$service_amount*$discount_price/100;
			}
		}
		
		return $return;
	} 

//end
?>
