<?php
/*

	osCommRes, Services Oline 
	http://www.oscommres.com 
	Copyright (c) 2005 osCommRes 
	
	Freeway eCommerce 
	http://www.zac-ware.com/freeway 
	Copyright (c) 2007 ZacWare 
	
	Released under the GNU General Public License
*/

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


   //error_reporting(E_ALL);
  // use condition in all event status checking 
  
  define('SERVICES_CONDITION_STATUS'," and (se.service_status>=1) and date_format(se.service_date_available,'%Y-%m-%d')<='".getServerDate()."'");
// Generate a path to services categories
	 
 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,$service_info,$service_id,$cart;
	$service_min_booking=(int)$service_info['service_total_time'];
	$service_total=tep_time_diff($date_begin.' '.'00:00:00',$date_end.' '.'23:59:59');	
	if($service_info['include_resource']=='N')
		$quantity=$service_info["quantity"];
	else{
		$quantity=1;
		$service_resource_query=tep_db_query("select count(*) as count from ".TABLE_SERVICES_TO_SERVICES_RESOURCES." sTr LEFT JOIN ".TABLE_SERVICE_RESOURCE." r on sTr.service_resource_id=r.resource_id, ".TABLE_SERVICE_RESOURCE_DESCRIPTIONS." red where red.resource_id=r.resource_id and red.resource_id=sTr.service_resource_id and sTr.service_id=".$service_id." and red.language_id='".(int)$languages_id."' group by service_id");
		if(tep_db_num_rows($service_resource_query)>0){
			$service_resource=tep_db_fetch_array($service_resource_query);
			$quantity=$service_resource['count'];
		}	
	}
 	if($booking_type=='D')
 		$service_total_time=round(($service_total["days"]/$service_min_booking));
 	else if($booking_type=='H')
		$service_total_time=round(((24/$service_min_booking)*$service_total["days"]));	
	else if($booking_type=='M')
		$service_total_time=round($service_total["minutes"]/$service_min_booking);				
 	if($service_id=='' && $languages_id=='') return;
    
	 if($type=='sale_time'){
	 $check="";
		$check=" and (o.orders_status>1 or date_add(o.date_purchased,interval se.pending_period day)>'" . date('Y-m-d H:i:s',getServerDate(false)) . "' 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",tep_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;
					   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 {
								//if($sale["start_date"]=='2007-02-23') echo $sale["start_date"];								
								$sale_dates[]=array('start_date'=>$temp_date,'start_time'=>$start_time,'end_time'=>$end_time,'quantity'=>$quantity);	
							}
							$temp_date=date("Y-m-d",tep_dateadd(@strtotime($temp_date),"day",1));
						} 
				  }
				}else if($sale["start_date"]==$sale["end_date"]) {	
					$sale_dates[]=array('start_date'=>$start_date,'start_time'=>$start_time,'end_time'=>$end_time,'quantity'=>$quantity);
				}		
			}
		}
	}
	$tot_time=1; 
	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=='D' && $service_min_booking && $ret1["days"] && $sale_dates[$i]["quantity"])
				$tot_time+=round(($sale_dates[$i]["quantity"] * $ret1["days"])/$service_min_booking);
		 	else if($booking_type=='H' && $service_min_booking && $ret1["hours"] && $sale_dates[$i]["quantity"])
		 		$tot_time+=round($sale_dates[$i]["quantity"]*($ret1["hours"]/$service_min_booking));
			else if($booking_type=='M' && $service_min_booking && $ret1["minutes"] && $sale_dates[$i]["quantity"])
				$tot_time+=round($sale_dates[$i]["quantity"]*($ret1["minutes"]/$service_min_booking));			
		}
	}
	
	$booking_customers_basket_edit=tep_db_query("select os.start_date,os.end_date,os.start_time,os.end_time,op.products_id,os.resource_id,op.customers_basket_quantity as quantity from ".TABLE_CUSTOMERS_BASKET." op,".TABLE_CUSTOMERS_BASKET_SERVICES ." os  where  op.products_id=os.products_id  and '$date_begin' BETWEEN os.start_date AND os.end_date ");
	if(tep_db_num_rows($booking_customers_basket_edit)>0){ 
	 	 while($booking_customers_basket_result=tep_db_fetch_array($booking_customers_basket_edit)){
	 	 		  $ret1=tep_time_diff($booking_customers_basket_result['start_date'].' '.$booking_customers_basket_result['start_time'],$booking_customers_basket_result['start_date'].' '. $booking_customers_basket_result['end_time']);
		 	 	  $pro_id=substr($booking_customers_basket_result['products_id'],1,strpos($booking_customers_basket_result['products_id'],"{")-1);
		 	 	  if($pro_id==$service_id){
		 	 	  	if($booking_type=='D' && $service_min_booking && $ret1["days"] && $booking_customers_basket_result["quantity"])
		 	 	  		$tot_time+=round($booking_customers_basket_result["quantity"]*($ret1["days"]/$service_min_booking));
		 	 	  	else if($booking_type=='H')
		 	 	  		$tot_time+=round($booking_customers_basket_result["quantity"]*($ret1["hours"]/$service_min_booking));
		 	 	    else  
		 	 	  		$tot_time+=round($booking_customers_basket_result["quantity"]*($ret1["minutes"]/$service_min_booking));		 	 	  	
		 	 	  }
		 	 }
		 } 
			 
			 $get_edit_order_product=tep_db_query("select os.start_date,os.end_date,os.start_time,os.end_time,os.resource_id,op.products_quantity as quantity from ".TABLE_ORDERS_EDIT_PRODUCTS." op,".TABLE_ORDERS_EDIT_SERVICES ." os  where op.orders_products_id=os.orders_products_id and  op.products_id=os.products_id and  op.products_id='".(int)$service_id."' and '$date_begin' BETWEEN os.start_date AND os.end_date ");
			 if(tep_db_num_rows($get_edit_order_product)>0){
	  			while($order_edit=tep_db_fetch_array($get_edit_order_product)){
	  				$ret1=tep_time_diff($order_edit['start_date'].' '.$order_edit['start_time'],$order_edit['start_date'].' '. $order_edit['end_time']);
		  			if($booking_type=='D' && $service_min_booking && $ret1["days"] && $order_edit["quantity"])
		  				$tot_time+=round($order_edit["quantity"]*($ret1["days"]/$service_min_booking));
					else if($booking_type=='H')
						$tot_time+=round($order_edit["quantity"]*($ret1["hours"]/$service_min_booking));								  			
		  			else 
		  				$tot_time+=round($order_edit["quantity"]*($ret1["minutes"]/$service_min_booking));
		  			
	  			}
			 }	 
			 $check_products=$cart->get_products();
			 if($check_products && !$customer_id){
			 	 for($i=0;$i<=sizeof($check_products);$i++){
					if($check_products[$i]['element_type']=='V' && $check_products[$i]['id']==$service_id){
						$ret1=tep_time_diff($check_products[$i]['others']['start_date'].' '.$check_products[$i]['others']['start_time'],$check_products[$i]['others']['end_date'].' '. $check_products[$i]['others']['end_time']);
						if($booking_type=='D' && $service_min_booking && $ret1["days"] && $check_products[$i]['others']['quantity'])
	  						$tot_time+=round($check_products[$i]['others']['quantity']*($ret1["days"]/$service_min_booking));
	  					else if($booking_type=='H')
	  						$tot_time+=round($check_products[$i]['others']['quantity']*($ret1["hours"]/$service_min_booking));
	  					else 
	  						$tot_time+=round($check_products[$i]['others']['quantity']*($ret1["minutes"]/$service_min_booking));
					 }
				  } 
			  }

	
	$return="0";
	if($type=='total_time'){		
		if($service_total_time)  {
			$return_ti=$service_total_time;
		}
		$return=(($quantity)?$quantity * $return_ti:$return_ti);
	}else if($type=='sale_time')  
		$return=$tot_time; 	
	
	return $return;
}
	 	
 function tep_get_services_path($current_services_category_id = '0') {
    global $secPath_array;
    
    if (tep_not_null($current_services_category_id)) {
      $ecp_size = sizeof($secPath_array);
      if ($ecp_size == 0) {
        $secPath_new = $current_services_category_id;
      } else {
        $secPath_new = '';
        $last_services_category_query = tep_db_query("select parent_id from " . TABLE_SERVICES_CATEGORIES . " where services_categories_id = '" . (int)$secPath_array[($sucp_size-1)] . "'");
        $last_services_category = tep_db_fetch_array($last_services_category_query);

        $current_services_category_query = tep_db_query("select parent_id from " . TABLE_SERVICES_CATEGORIES . " where services_categories_id = '" . (int)$current_services_category_id . "'");
        $current_services_category = tep_db_fetch_array($current_services_category_query);

        if ($last_services_category['parent_id'] == $current_services_category['parent_id']) {
          for ($i=0; $i<($sucp_size-1); $i++) {
            $secPath_new .= '_' . $secPath_array[$i];
          }
        } else {
          for ($i=0; $i<$sucp_size; $i++) {
            $secPath_new .= '_' . $secPath_array[$i];
          }
        }
        $secPath_new .= '_' . $current_services_category_id;

        if (substr($secPath_new, 0, 1) == '_') {
          $secPath_new = substr($secPath_new, 1);
        }
      }
    } else if(is_array($secPath_array)){
      $secPath_new = implode('_', $secPath_array);
    }

    return 'secPath=' . $secPath_new;
  }


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

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

    return $tmp_array;
  }
  
  function tep_get_services_name($service_id, $language_id = 0,$max=false) {
    global $languages_id;

    if ($language_id == 0) $language_id = $languages_id;
    $services_query = tep_db_query("select s.max_bookings,sd.service_name from " . TABLE_SERVICES_DESCRIPTION . " sd," . TABLE_SERVICES . " s where s.service_id=sd.service_id and s.service_id = '" . (int)$service_id . "' and sd.language_id = '" . (int)$language_id . "'");
    $services = tep_db_fetch_array($services_query);
    if($max){
	  return $services['max_bookings']; 
	}else { 
      return $services['service_name'];
    }
  }
  
  
  // function to get events display text
	function tep_get_services_display_text($services_name,$start_time,$location){
		$bolTest=true;
		if ($bolTest) return $services_name;
		$result=$services_name;
		
		$dayLight=strtolower(date("A",@strtotime($start_time)));
		$result.=" - " . ($dayLight=="pm"?"Night":"Day");
		$result.=" - " . $location;
		return $result;
	}

// send invite email to selected friends email address
function tep_send_services_invite_email(&$send_details){

	global $currencies,$languages_id;

	if (!is_array($send_details)) return;
	// fetch the services details
	$services_query=tep_db_query("select su.service_id,sud.service_name,su.service_costs,su.service_tax_class_id,su.service_location from " . 
								TABLE_SERVICES . " su, " . TABLE_SERVICES_DESCRIPTION .  " sud " .
								"where su.service_id='" . $send_details['service_id'] . "' and su.service_id=sud.service_id and sud.language_id='" . $languages_id . "'");
								
	if (tep_db_num_rows($services_query)<=0) return;

	$services_result=tep_db_fetch_array($services_query);
	
	$tax_rate=tep_get_tax_rate($services_result['service_tax_class_id']);

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

	$details=array();
	$details['type']=$send_details['mail_type'];
	$details['table']=TABLE_SERVICES_MESSAGES;
	$details['service_id']=$send_details['sID'];
	
	tep_get_template1($details);
	$services_location=tep_get_locations_name($services_result['service_location']);
	$replace_array=array(
		TEXT_SER_SN=>$services_result['service_name'],
		TEXT_SER_SC=>$currencies->format(tep_add_tax($services_result['service_cost'],$tax_rate)),
		TEXT_SER_SL=>$services_location,
		TEXT_RV=>'<a href="' . tep_href_link(FILENAME_SERVICES_SURVEYS_ANSWER,'R=1&type=RV&service_id=' . $services_result['service_id'],'NONSSL',false) . '">' . TEST_MAIL_RV . '</a>',
		TEXT_WV=>'<a href="' . tep_href_link(FILENAME_SERVICES_SURVEYS_ANSWER,'R=1&type=WV&service_id=' . $services_result['service_id'],'NONSSL',false) . '">' . TEST_MAIL_WV . '</a>',
		TEXT_FV=>'<a href="' . tep_href_link(FILENAME_SERVICES_SURVEYS_ANSWER,'R=1&type=FV&service_id=' . $services_result['service_id'],'NONSSL',false) . '">' . TEST_MAIL_FV . '</a>',
		TEXT_CF=>$customer_result['customers_firstname'],
		TEXT_CL=>$customer_result['customers_lastname'],
		TEXT_IC=>$send_details['comments'],
		TEXT_FE=>TEST_MAIL_FE,
		TEXT_IC=>TEST_MAIL_IC,
		TEXT_IF=>'<a href="mailto:' . $customer_result['customers_email_address'] . '"><u>' . $customer_result['customers_email_address'] .'</u></a>'
 	  );
   //replace template
	tep_replace_template($details,$replace_array);
	tep_strip_html($details);
	
	$email_array=&$send_details["address"];
	$name_array=&$send_details["name"];
	// send email
	$message = new email(array('X-Mailer: osCommres'));
	
	for ($icnt=0;$icnt<sizeof($email_array);$icnt++){
		$mes_content=$details['html_text'];
		$mes_text=eregi_replace("%%" . TEXT_FE . "%%",$name_array[$icnt] . "",$mes_content);
		
		$text=strip_tags($mes_text,'<br>');
		$text=str_replace('<br>',chr(13). chr(10),$text);
		$text=str_replace('<BR>',chr(13). chr(10),$text);
		
		if ($mes_text!='' && $email_array[$icnt]!=''){

			if ($mail_data_result['message_format'] != 'T') {
				$message->add_html($mes_text, $text);
			} else {
				$message->add_text($text);
			}
			$message->build_message();
			 
			if(HTTP_SERVER!='http://192.168.2.1:81' || HTTP_SERVER!='http://raga:81') $message->send($name_array[$icnt], $email_array[$icnt], $customer_result['customers_firstname'] . ' ' . $customer_result['customers_lastname'], $customer_result['customers_email_address'], $details['subject']);
		}
	}
}
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'];
  }
  
   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'];
  }

// replace the invite email content
function tep_replace_services_invite_mail_content($send_details){
global $currencies,$languages_id;
	if (!is_array($send_details)) return;

	// fetch the services details
	$services_query=tep_db_query("select su.service_id,sud.service_name,su.services_cost,su.service_tax_class_id from " . 
								TABLE_SERVICES . " su, " . TABLE_SERVICES_DESCRIPTION .  " sud " .
								"where su.service_id='" . $send_details['service_id'] . "' and su.service_id=sud.service_id and sud.language_id='" . $languages_id . "'");
	
	if (tep_db_num_rows($services_query)<=0) return;
	
	$services_result=tep_db_fetch_array($services_query);
	
	$tax_rate=tep_get_tax_rate($services_result['service_tax_class_id']);
	
	// fetch the customer detail
	$customer_query=tep_db_query("select customers_firstname,customers_lastname,customers_email_address from " . TABLE_CUSTOMERS . " where customers_id='" . $send_details['cID'] . "'");
	if (tep_db_num_rows($customer_query)<=0) return;
	$customer_result=tep_db_fetch_array($customer_query);

	
	// prepare the merge array
	$replace_array=array(TEXT_SER_SN=>$services_result['service_name'],
							TEXT_SER_SC=>$currencies->format(tep_add_tax($services_result['service_cost'],$tax_rate)),
							TEXT_CF=>$customer_result['customers_firstname'],
							TEXT_CL=>$customer_result['customers_lastname'],
							TEXT_IC=>$send_details['comments'],
							TEXT_FE=>TEST_MAIL_FE,
							TEXT_IC=>TEST_MAIL_IC,
							TEXT_IF=>'<a href="mailto:' . $customer_result['customers_email_address'] . '"><u>' . $customer_result['customers_email_address'] .'</u></a>'
							);

	$mes_content=$send_details['text'];

	// replace the merge details
	while (list($key, $value) = each($replace_array))
		$mes_content=eregi_replace("%%" . $key  . "%%",$value . "",$mes_content);

	return $mes_content;	
}

  function tep_find_services_category_path($category_id){
		$query=tep_db_query("SELECT parent_id,services_categories_id from " . TABLE_SERVICES_CATEGORIES . " where services_categories_id='" . $category_id . "'");
		
		if (tep_db_num_rows($query)<=0) return "";
		$result=tep_db_fetch_array($query);
		if ($result["parent_id"]==0){
			return $category_id;
		} else {
			return tep_find_services_category_path($result["parent_id"]) . "_" . $category_id;
		}
	}

// 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'];
  }  

// get location name by passing location_id
  function tep_get_service_provider_name($provider_id) {
    $provider_query = tep_db_query("select concat(provider_firstname,' ',provider_lastname) as provider_name from " . TABLE_SERVICES_PROVIDERS . " where provider_id = '" . (int)$provider_id . "'");
    $provider = tep_db_fetch_array($provider_query);

    return $provider['provider_name'];
  }  
function tep_get_times_array($start_time,$end_time,$interval_min,$type="list"){
	if ($interval_min<=0) return array();
	// 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 ($type=="list"){
			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);
		} else {
			$result[]=$time;
		}

		$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_interval_dates($start_date,$interval,$type="list"){
	if ($interval<=0) return;
	$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); 
		if ($type=="list"){
			$dates[]=array('id'=>$date,'text'=>format_date($date));
		} else {
			$dates[]=$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_dates_array($start_date,$end_date,$type="list"){
	if ($start_date=="" || $end_date=="") return;
	$date_splt=split("-",$start_date);
	$day=$date_splt[2];
	$month=$date_splt[1];
	$year=$date_splt[0];

	$dates=array();
	$total_days=0;
	while($start_date<=$end_date){
		// 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); 
		if ($type=="list"){
			$dates[]=array('id'=>$date,'text'=>format_date($date));
		} else {
			$dates[]=$date;
		}
		$day=$day+1;
		
		if ($day>$total_days){
			$day=1;
			$month=$month+1;
			if ($month>12){
				$month=1;
				$year=$year+1;
			}
		}
		$start_date=$date;
	}
	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,$block_dates,$time_length,$no_booking_sdate_array,$granular;
	$granular_cnt=$granular;
	if($type!='D') $granular_cnt=1;	
	$cur_date_string=getServerDate(false);     
	$nb_dates_array=$block_dates;
	if ($start_date=="" || $end_date=="" || $start_date<getServerDate() || $end_date<getServerDate()) 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);
	$dis_time_format="";
	if(defined('TIME_FORMAT')) $dis_time_format=TIME_FORMAT;
	$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",$cur_date_string),(date("d",$cur_date_string)+1),date("Y",$cur_date_string)));		
		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){
	  if($find_max_dates[sizeof($find_max_dates)-1]) $start_date=tep_convert_date_raw($find_max_dates[sizeof($find_max_dates)-1]);
	  else $start_date=date('Y-m-d',tep_dateadd(@strtotime($start_date),"day",30));
		$end_date=date('Y-m-d',tep_dateadd(@strtotime($start_date),"day",30));
		$dates=tep_get_service_dates_array($start_date,$end_date,$type);
	}
	return $dates;
}

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){
	global $curDate;
	$add_option="";
	if ($booking_type=="H") $add_option.=" and os.start_date='".$start_date."' and ((os.start_time>='" . $start_time . "' and os.start_time<='" . $end_time . "') or (os.end_time>='" . $start_time . "' and " . " os.end_time<='" . $end_time . "'))";
	else  
	     $add_option.=" and ((os.start_date>'" . $start_date . "' and os.start_date<'" . $end_date . "') or (os.start_date='".$start_date."' and os.start_time>='".$start_time."') or (os.end_date='" . $start_date. "' and os.end_date<'" . $end_date . "') or (os.end_date='".$end_date."' and os.end_time<='".$end_time."'))"; 
	if ($order_id>0) $add_option.=" and o.orders_id!='" . $order_id . "'";
 	$add_option.=" and (o.orders_status>1 or date_add(o.date_purchased,interval v.pending_period  day)>='".date('Y-m-d H:i:s',getServerDate(false))."' and op.orders_products_status!=5)";  
	$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_service_prid($uprid) {
  $uprid=substr($uprid,1);
  $pieces = explode('{', $uprid);
  if (is_numeric($pieces[0])) {
    return $pieces[0];
  } else {
    $pieces = explode('-', $uprid);
    if($pieces[0]) return $pieces[0];
    else return false;
  }
}
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;
}
// Return a provider name
  function tep_get_provider_name($id) {
   // $instructor_query = tep_db_query("select admin_firstname,admin_lastname from " . TABLE_ADMIN . " where admin_id='" . (int)$id  . "'");
   $sql = tep_db_query("select  provider_id, provider_firstname, provider_lastname  from ".TABLE_SERVICES_PROVIDERS." sep order by provider_firstname,provider_lastname");
    if ($provider=tep_db_fetch_array($sql))
        return $provider['provider_firstname'] . ' ' . $provider['provider_lastname'];
  }
// send sms to reserved user
  function tep_send_service_sms_email($replace_array,$send_details)
  {
		if ((int)SMS_ACTIVATE!=1) return false;

		// fetch the sms template details
		$sms_query=tep_db_query("SELECT message_text from " . TABLE_SERVICES_SMS_MESSAGES . " where service_id='" . (int)$send_details['service_id'] . "' and message_type='" . $send_details['mail_type'] . "'");
		
		if (tep_db_num_rows($sms_query)<=0) return false;
		
		$sms_result=tep_db_fetch_array($sms_query);
		
		$mes_text=$sms_result['message_text'];
		reset($replace_array);
	
		while (list($key, $value) = each($replace_array))
			$mes_text=eregi_replace("%%" . $key  . "%%",$value  . "",$mes_text);
		
		$text = strip_tags($mes_text,'<br>');
		$text = str_replace('<br>',chr(13) .chr(10),$text);
		$text = str_replace('<BR>',chr(13) .chr(10),$text);
		
		return send_sms($send_details['mobile'],$replace_array[TEXT_FN] . ' ' . $replace_array[TEXT_LN],$text,$send_details['country']);
  }
 



//service email

function tep_send_service_email($process_id,$mail_type){
global $currencies;

	if ((int)EMAIL_ACTIVATE!=1 && (int)SMS_ACTIVATE!=1) return;
	if ((int)$process_id<=0 || $mail_type=='')
		return;
		
		
		// fetch data
	$process_query=tep_db_query("select c.customers_id,c.customers_firstname,c.customers_lastname,c.customers_dob,c.customers_telephone,c.customers_fax,c.customers_second_telephone,c.customers_second_email_address,
				  o.customers_street_address,c.customers_email_address,o.customers_suburb,o.customers_postcode,o.customers_city,
				  o.customers_state,o.customers_country,op.final_price,op.products_id,s.start_date,e.events_payment,op.products_tax,op.products_name,
				  se.service_id,se.services_renewal_start,se.services_renewal_end,time_format(se.service_start_time,'%h:%i %p') as service_start_time,time_format(se.service_end_time,'%h:%i %p') as service_end_time,se.service_location,se.service_costs,se.service_tax_class_id,o.orders_id,o.date_purchased,o.billing_name,o.billing_street_address,o.payment_method from " . 
						   TABLE_CUSTOMERS . " c, " . TABLE_ORDERS_SERVICES . " s, " . TABLE_ORDERS . " o, " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_services . " se " . 
				   "where o.orders_id=op.orders_id and o.customers_id=c.customers_id and op.products_id=s.products_id and s.products_id=se.service_id and op.orders_products_id='" . $process_id . "'");

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

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

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

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

	if (sizeof($renewal_array)>0) $renewal_end=$renewal_array["end_date"];
 
	$service_location=tep_get_locations_name($process_result['service_location']);
	
	// prepare details for merge details
	$replace_array=array(	TEXT_FN=>$process_result['customers_firstname'],
							TEXT_LN=>$process_result['customers_lastname'],
							TEXT_DF=>format_date($process_result['customers_dob']),
							TEXT_EM=>'<a href="mailto:' . $process_result['customers_email_address'] . '"><u>' . $process_result['customers_email_address'] .'</u></a>',
							TEXT_TN=>$process_result['customers_telephone'],
							TEXT_FX=>$process_result['customers_fax'],
							TEXT_SA=>$process_result['customers_street_address'],
							TEXT_SU=>$process_result['customers_suburb'],
							TEXT_PC=>$process_result['customers_postcode'],
							TEXT_CT=>$process_result['customers_city'],
							TEXT_ST=>$process_result['customers_state'],
							TEXT_CY=>$process_result['customers_country'],
							TEXT_EN=>$process_result['products_name'],
							TEXT_SI=>$process_result['service_start_time'],
							TEXT_EI=>$process_result['service_end_time'],
							TEXT_EF=>$currencies->format(tep_add_tax($process_result['service_costs'],tep_get_tax_rate($process_result['service_tax_class_id']))),
							TEXT_IN=>tep_get_provider_name($process_result['provider']),
							TEXT_EL=>$service_location,
							TEXT_SD=>format_date($process_result['start_date']),
							TEXT_IV=>'<a href="' . tep_href_link(FILENAME_SERVICES_INVITE_FRIEND,'R=1&path=ACC&eID=' . $process_result['service_id'],'NONSSL',false) . '">' . TEXT_IV . '</a>',
							TEXT_UN=>'<a href="' . tep_href_link(FILENAME_SERVICES_UNSUBSCRIBE,'R=1&cID=' . $process_result['customers_id'],'NONSSL',false) . '">' . TEST_MAIL_UN . '</a>',
							TEXT_RL=>'<a href="' . tep_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RL . '</a>',
							TEXT_RM=>'<a href="' . tep_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_RM . '</a>',
							TEXT_RV=>'<a href="' . tep_href_link(FILENAME_SERVICES_SURVEYS_ANSWER,'R=1&type=RV&events_id=' . $process_result['service_id'],'NONSSL',false) . '">' . TEST_MAIL_RV . '</a>',
							TEXT_WV=>'<a href="' . tep_href_link(FILENAME_SERVICES_SURVEYS_ANSWER,'R=1&type=WV&events_id=' . $process_result['service_id'],'NONSSL',false) . '">' . TEST_MAIL_WV . '</a>',
							TEXT_FV=>'<a href="' . tep_href_link(FILENAME_SERVICES_SURVEYS_ANSWER,'R=1&type=FV&events_id=' . $process_result['service_id'],'NONSSL',false) . '">' . TEST_MAIL_FV . '</a>',
							TEXT_IL=>'<a href="' . tep_href_link(FILENAME_ACCOUNT_HISTORY_INFO,'R=1&order_id=' . $process_result['orders_id'],'NONSSL',false) . '">' . TEST_MAIL_IL . '</a>',
							TEXT_RE=>format_date($renewal_end),
							TEXT_ON=>$process_result['orders_id'],
							TEXT_OC=>$process_result['orders_comments'],
							TEXT_OD=>format_date($process_result['date_purchased']),
							TEXT_BT=>$process_result['billing_name'],
							TEXT_BA=>$process_result['billing_street_address'],
							TEXT_PY=>$process_result['payment_method'],
							TEXT_TX=>$process_result['products_tax'],
							TEXT_SB=>$currencies->format($process_result['final_price']),
							TEXT_SS=>sprintf(TEXT_FORMAT_SS,$process_result['products_name'],$process_result['service_start_time'],$process_result['service_end_time'],date('l, jS F', @strtotime($process_result['start_date'])),$events_location),
							TEXT_SSM=>format_date($process_result['start_date'],true),
							TEXT_TL=>$currencies->format(tep_add_tax($process_result['final_price'],$process_result['products_tax'])));

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

	tep_strip_html($details);

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

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

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


// replace the invite email content
	function tep_replace_service_invite_mail_content($send_details){
	global $currencies;
		if (is_array($send_details)==false)
			return;
		
		// fetch the event details
		
		$service_query=tep_db_query("select os.start_date,sd.service_name,time_format(os.start_time,'%h:%i %p') as start_time,os.end_time,s.service_location,s.service_tax_class_id,s.service_costs,s.service_id from " . 
									TABLE_ORDERS_SERVICES . " os, " . TABLE_SERVICES . " s, " . TABLE_SERVICES_DESCRIPTION .  " sd " .
									"where s.service_id='" . $send_details['sID'] . "' and os.products_id=s.service_id and s.service_id=sd.service_id order by os.start_date limit 1");

		if (tep_db_num_rows($service_query)<=0) return;
		$service_result=tep_db_fetch_array($service_query);
	
		// fetch the tax rate
		$tax_rate=tep_get_tax_rate($service_result['service_tax_class_id']);

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

		// prepare the merge array
		$services_location=tep_get_locations_name($service_result['service_location']);
		if($service_result['end_date'] && $service_result['end_time']) $end_date_string=strtotime($service_result['end_date'].' '.$service_result['end_time'])+60;
		$service_result['end_date']=date('Y-m-d',$end_date_string);
		$service_result['end_time']=date('h:i A',$end_date_string);
		$replace_array=array(
								TEXT_SER_SN=>$service_result['service_name'],
								TEXT_SER_ST=>$service_result['start_time'],
								TEXT_SER_ET=>$service_result['end_time'],
								TEXT_SER_SL=>$services_location,
								TEXT_RV=>'<a href="' . tep_href_link(FILENAME_SERVICES_SURVEYS_ANSWER,'R=1&type=RV&service_id=' . $service_result['service_id'],'NONSSL',false) . '">' . TEST_MAIL_RV . '</a>',
								TEXT_WV=>'<a href="' . tep_href_link(FILENAME_SERVICES_SURVEYS_ANSWER,'R=1&type=WV&service_id=' . $service_result['service_id'],'NONSSL',false) . '">' . TEST_MAIL_WV . '</a>',
								TEXT_FV=>'<a href="' . tep_href_link(FILENAME_SERVICES_SURVEYS_ANSWER,'R=1&type=FV&service_id=' . $service_result['service_id'],'NONSSL',false) . '">' . TEST_MAIL_FV . '</a>',
								TEXT_SER_SD=>format_date($service_result['start_date']),
								TEXT_SER_ED=>format_date($service_result['end_date']),
								TEXT_SS=>sprintf(TEXT_FORMAT_SS,$service_result['service_name'],$service_result['start_time'],$service_result['end_time'],date('l, jS F', @strtotime($service_result['start_date'])),$services_location),
								TEXT_SSM=>format_date($service_result['start_date'],true),
								TEXT_SER_SC=>$currencies->format(tep_add_tax($service_result['service_costs'],$tax_rate)),
								TEXT_CF=>$customer_result['customers_firstname'],
								TEXT_CL=>$customer_result['customers_lastname'],
								TEXT_FE=>TEST_MAIL_FE,
								TEXT_IC=>TEST_MAIL_IC,
								TEXT_IF=>'<a href="mailto:' . $customer_result['customers_email_address'] . '"><u>' . $customer_result['customers_email_address'] .'</u></a>'
								);
					
		$mes_content=$send_details['text'];
		// replace the merge details
		while (list($key, $value) = each($replace_array))
			$mes_content=eregi_replace("%%" . $key  . "%%",$value . "",$mes_content);
		return $mes_content;	
	}


// send service order email
function tep_send_service_order_email($i){
	global $currencies,$order,$customer_id,$insert_id,$languages_id;	
	if ((int)EMAIL_ACTIVATE!=1) return;

	// get subscription details	
	$service_query=tep_db_query("SELECT se.service_id,se.service_costs,se.service_location,se.service_tax_class_id,se.service_tax_class_id from " . 
								   TABLE_SERVICES . " se " . " where se.service_id='" . $order->products[$i]['id'] . "'");	 
	if (tep_db_num_rows($service_query)<=0) return;
 	$service_result=tep_db_fetch_array($service_query);
	
	// get mail template details
	$details=array();
	$details['type']='RCF';
	$details['table']=TABLE_SERVICES_MESSAGES;
	$details['service_id']=$service_result['service_id'];
	tep_get_template1($details);
	
	if ($details['html_text']=="") return;
	
	$url_home=(ENABLE_SSL == 'true'?HTTPS_SERVER . DIR_WS_HTTPS_CATALOG:HTTP_SERVER . DIR_WS_HTTP_CATALOG);
	$resource_id=$order->products[$i]['others']['resource_id'];
	$resource_name=tep_get_resource_name($resource_id,'resource_name',(int)$languages_id);
	
	// get some customer information 
	$order_query=tep_db_query("SELECT customers_fax,customers_dob from " . TABLE_CUSTOMERS . " where customers_id='" . (int)$customer_id . "'");
	$order_result=tep_db_fetch_array($order_query);
 	
	$selected_order_attributes="";
	for($j=0;$j<sizeof($order->products[$i]['attributes']);$j++)
	{
		$attributes=$order->products[$i]['attributes'];
		$selected_order_attributes.=$attributes[$j]['option'] . ' :  ' . $attributes[$j]['value'] . ' (' . $attributes[$j]['prefix'] . $currencies->format($attributes[$j]['price']) . ')' . '<br>';
	}
	if($order->products[$i]['others']['end_date'] && $order->products[$i]['others']['end_time']) $end_date_string=strtotime($order->products[$i]['others']['end_date'].' '.$order->products[$i]['others']['end_time'])+60;
	$order->products[$i]['others']['end_date']=date('Y-m-d',$end_date_string);
	$order->products[$i]['others']['end_time']=date('H:i:s',$end_date_string);
  	$replace_array=array(	TEXT_FN=>$order->customer['firstname'],
							TEXT_LN=>$order->customer['lastname'],
							TEXT_DF=>format_date($order_result['customers_dob']),
							TEXT_EM=>'<a href="mailto:' . $order->customer['email_address'] . '"><u>' . $order->customer['email_address'] .'</u></a>',
							TEXT_TN=>$order->customer['telephone'],
							TEXT_FX=>$order_result['customers_fax'],
							TEXT_SA=>$order->customer['street_address'],
							TEXT_SU=>$order->customer['suburb'],
							TEXT_PC=>$order->customer['postcode'],
							TEXT_CT=>$order->customer['city'],
							TEXT_ST=>$order->customer['state'],
							TEXT_CY=>$order->customer['country']['title'],
							TEXT_SER_SN=>$order->products[$i]['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($order->products[$i]['others']['start_date']),
							TEXT_SER_ED=>format_date($order->products[$i]['others']['end_date']),
							TEXT_SER_ST=>date('h:i A',@strtotime($order->products[$i]['others']['start_time'])),
							TEXT_SER_ET=>date('h:i A',@strtotime($order->products[$i]['others']['end_time'])),
							TEXT_SER_RN=>$resource_name,
							TEXT_SER_AD=>$selected_order_attributes,
							TEXT_SER_SL=>tep_get_service_location_name($service_result["service_location"]),
							TEXT_IV=>'<a href="' . tep_href_link(FILENAME_SERVICES_INVITE_FRIEND,'R=1&path=ACC&seID=' . $service_result['service_id'],'NONSSL',false) . '">' . TEST_MAIL_SUB_IV . '</a>',
							TEXT_UN=>'<a href="' . tep_href_link(FILENAME_SERVICES_UNSUBSCRIBE,'R=1&cID=' . $customer_id,'NONSSL',false) . '">' . TEST_MAIL_SUB_UN . '</a>',
							TEXT_RL=>'<a href="' . tep_href_link(FILENAME_ACCOUNT,'R=1','NONSSL',false) . '">' . TEST_MAIL_SUB_RL . '</a>',
							TEXT_IL=>'<a href="' . tep_href_link(FILENAME_ACCOUNT_HISTORY_INFO,'R=1&order_id=' . $insert_id,'NONSSL',false) . '">' . TEST_MAIL_SUB_IL . '</a>',
							TEXT_RV=>'<a href="' . tep_href_link(FILENAME_SERVICES_SURVEYS_ANSWER,'R=1&type=RV&service_id=' . $service_result['service_id'],'NONSSL',false) . '">' . TEST_MAIL_RV . '</a>',
							TEXT_WV=>'<a href="' . tep_href_link(FILENAME_SERVICES_SURVEYS_ANSWER,'R=1&type=WV&service_id=' . $service_result['service_id'],'NONSSL',false) . '">' . TEST_MAIL_WV . '</a>',
							TEXT_FV=>'<a href="' . tep_href_link(FILENAME_SERVICES_SURVEYS_ANSWER,'R=1&type=FV&service_id=' . $service_result['service_id'],'NONSSL',false) . '">' . TEST_MAIL_FV . '</a>',
							TEXT_SL=>'<a href="' . tep_href_link(FILENAME_DEFAULT) . '" style="font-family:Arial, Helvetica, sans-serif;font-size:13px;color:#3966B1;font-weight:bold;text-decoration:none;">' . STORE_OWNER . '</a>',
							TEXT_SP=>'<img src="' . $url_home . DIR_WS_TEMPLATES . TEMPLATE_NAME . '/images/' .COMPANY_LOGO . '" title="' . STORE_NAME . '">',
							TEXT_RE=>'',
							TEXT_ON=>$insert_id,
							TEXT_OC=>$order->info['comments'],
							TEXT_OD=>date(EVENTS_DATE_FORMAT),
							TEXT_BT=>$order->billing['firstname'] . ' ' . $order->billing['lastname'],
							TEXT_BA=>$order->billing['street_address'],
							TEXT_PY=>$order->info['payment_method'],
							TEXT_TX=>$currencies->format(tep_calculate_tax($order->products[$i]['final_price'],$order->products[$i]['tax'])*$order->products[$i]['qty']),
							TEXT_SB=>$currencies->format($order->products[$i]['final_price']*$order->products[$i]['qty']),
							TEXT_TL=>$currencies->format(tep_add_tax($order->products[$i]['final_price'],$order->products[$i]['tax'])*$order->products[$i]['qty'])
							);
     
	$sql_array=array(	'orders_id'=>$insert_id,
						'service_id'=>$service_result['service_id'],
						'customers_id'=>$customer_id,
						'message_type'=>'RCF',
						'message_mode'=>'E',
						'email_address'=>$order->customer['email_address'],
						'send_date'=>'now()'
					);
	tep_replace_template($details,$replace_array);
	tep_strip_html($details);
	// form the address array to send
	$details['to_name']=$order->customer['firstname'] . ' ' . $order->customer['lastname'];
	$details['to_email']=$order->customer['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);
}

	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'];
		}
	}
	// calculate the time difference
	function tep_time_diff($from, $to){
		global $start_time,$end_time;
	  if ($from=="" || $to=="") return array();
	   $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
	   $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;
	}
	
	// calculate the price for the service with optional price
	function tep_calc_service_cost($service,$book_stime,$book_etime,$option_price=0,$loading_dates="",$qty=1){		
		$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 
			$total_book_time=(int)$ret["days"];		
		$final_cost=($total_book_time/$total_service_time)*($option_price + $service["service_costs"]);		
		if($final_cost==0) $final_cost=$service["service_costs"];
		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;
	}
	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 
			$total_book_time=(int)$ret["days"];		
		$final_cost=(($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+$option_price);
			$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;
	}
	
	 function tep_get_page_params($include_array = '') {
		global $HTTP_GET_VARS;
	
		if (!is_array($include_array)) $include_array = array();
	
		$get_url = '';
		for ($icnt=0;$icnt<count($include_array);$icnt++){
			$key=$include_array[$icnt];
			if ( isset($HTTP_GET_VARS[$key]) && strlen($HTTP_GET_VARS[$key])>0) {
			  $get_url .= $key . '=' . urlencode(stripslashes($HTTP_GET_VARS[$key])) . '&';
			}
		}
	
		return $get_url;
	  }
	  
	    //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 = @gmmktime($delta_vars["hr"],
   $delta_vars["min"],
   $delta_vars["sec"],
   $delta_vars["mon"],
   $delta_vars["day"],
   $delta_vars["yr"]);
   return $timestamp + $delta;
} 
// function to add interval to given date
function dateadd($timestamp, $unit, $amount) {
		$timestring=date("Y-m-d H:i:s",$timestamp);

		$timestring = preg_replace("#\s#","",$timestring);
		$timestring = preg_replace("#\:#","",$timestring);
		$timestring = preg_replace("#\.#","",$timestring);
		$timestring = preg_replace("#\/#","",$timestring);
		$timestring = preg_replace("#\-#","",$timestring);
		$fac = ("-" == substr($timestring,0,1)) ? -1 : 1;
		$timestamp = ("-" == substr($timestring,0,1)) ? substr($timestring,1,strlen($timestring)-1) : $timestring;

		$array['yr']     = (6==strlen($timestamp)) ? $fac * substr($timestamp,0,2): $fac * substr($timestamp,0,4);
		$array['mon']     = (6==strlen($timestamp)) ? $fac * substr($timestamp,2,2): $fac * substr($timestamp,4,2);
		$array['day']        = (6==strlen($timestamp)) ? $fac * substr($timestamp,4,2): $fac * substr($timestamp,6,2);
		$array['hr']     = (12 > strlen($timestamp)) ? 0 : $fac * substr($timestamp, 8,2);
		$array['min']     = (12 > strlen($timestamp)) ? 0 : $fac * substr($timestamp, 10,2);
		$array['sec']     = (14 > strlen($timestamp)) ? 0 : $fac * substr($timestamp, 12,2);

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

// function to subtract interval to given date
function datesub($timestamp, $unit, $amount) {
$timestring=date("Y-m-d H:i:s",$timestamp);

		$timestring = preg_replace("#\s#","",$timestring);
		$timestring = preg_replace("#\:#","",$timestring);
		$timestring = preg_replace("#\.#","",$timestring);
		$timestring = preg_replace("#\/#","",$timestring);
		$timestring = preg_replace("#\-#","",$timestring);
		$fac = ("-" == substr($timestring,0,1)) ? -1 : 1;
		$timestamp = ("-" == substr($timestring,0,1)) ? substr($timestring,1,strlen($timestring)-1) : $timestring;

		$array['yr']     = (6==strlen($timestamp)) ? $fac * substr($timestamp,0,2): $fac * substr($timestamp,0,4);
		$array['mon']     = (6==strlen($timestamp)) ? $fac * substr($timestamp,2,2): $fac * substr($timestamp,4,2);
		$array['day']        = (6==strlen($timestamp)) ? $fac * substr($timestamp,4,2): $fac * substr($timestamp,6,2);
		$array['hr']     = (12 > strlen($timestamp)) ? 0 : $fac * substr($timestamp, 8,2);
		$array['min']     = (12 > strlen($timestamp)) ? 0 : $fac * substr($timestamp, 10,2);
		$array['sec']     = (14 > strlen($timestamp)) ? 0 : $fac * substr($timestamp, 12,2);

		$array[$unit]-=$amount;
		   $rtime = mktime ($array['hr'],$array['min'],$array['sec'],$array['mon'],$array['day'],$array['yr']);
	return $rtime;
}
function tep_service_categories_name($category_id,$display_type=''){
 $category=tep_db_query("select services_categories_name,services_categories_image,services_categories_description,services_categories_notes from ".TABLE_SERVICES_CATEGORIES." sec,".TABLE_SERVICES_CATEGORIES_DESCRIPTION . " secd where sec.services_categories_id='".$category_id."' and sec.services_categories_id=secd.services_categories_id");
 $category_result=tep_db_fetch_array($category);
 if($display_type=='name'){
    $return=$category_result['services_categories_name'];
 }else if($display_type=='description'){
    $return=$category_result['services_categories_description'];
 }else if($display_type=='notes'){
    $return=$category_result['services_categories_notes'];
 }else if($display_type=='image'){
   $return=$category_result['services_categories_image'];
 }
 return $return;
}

function tep_service_categories_list($language_id){
 $category=tep_db_query("select sec.services_categories_id,secd.services_categories_name from ".TABLE_SERVICES_CATEGORIES." sec,".TABLE_SERVICES_CATEGORIES_DESCRIPTION . " secd where sec.parent_id='0' and secd.language_id='".(int)$language_id."' group by secd.services_categories_id");
 $category_list=array();
 while($category_result=tep_db_fetch_array($category)){
   $category_list[]=array(array('services_categories_id'=>$category_result['services_categories_id']),array('services_categories_name'=>$category_result['services_categories_name']));
 }
 return $category_list;
}

function tep_convert_format_date($date,$format_date=''){
 $return_date=date('Y-m-d');
 if($date=="" || $format_date=="") return;
 $date=format_date($date);
 $date=split("-",$date);
 $format_date=split("-",$format_date);
 $format_date=$format_date[0].'-'.$format_date[1].'-'.$format_date[2];

  switch(EVENTS_DATE_FORMAT){
   case 'm-d-Y':
     if($format_date=='Y-m-d'){
	   $return_date=$date[2].'-'.$date[0].'-'.$date[1];
	 }else if($format_date=='d-m-Y') {
	   $return_date=$date[1].'-'.$date[0].'-'.$date[2];
	 }else{
	   $return_date=$date[0].'-'.$date[1].'-'.$date[2];
	 }
   break;
   case 'd-m-Y':
     if($format_date=='Y-m-d'){
	   $return_date=$date[2].'-'.$date[1].'-'.$date[0];
	 }else if($format_date=='m-d-Y') {
	   $return_date=$date[1].'-'.$date[0].'-'.$date[2];
	 }else{
	   $return_date=$date[0].'-'.$date[1].'-'.$date[2];
	 }
   break;
   case 'Y-m-d':
     if($format_date=='d-m-Y') {
	   $return_date=$date[2].'-'.$date[1].'-'.$date[0];
	 }else if($format_date=='m-d-Y'){
	   $return_date=$date[1].'-'.$date[2].'-'.$date[0];
	 }else {
	  $return_date=$date[0].'-'.$date[1].'-'.$date[2];
	 }
   break;
  }
  return $return_date;
}

function 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"];
	  $recur_details=$sInfo["recurring_details"];
	  
	  //daily type
	  if ($type=='DD')
	  {
      	  while ($caldate<=$edate)
		  {
		  	$result_dates[]=$caldate;
			$query = tep_db_query("select date_add('" . $caldate . "',interval '" . $recur_details . "' day) as datenew");
			$result=tep_db_fetch_array($query);
			$caldate=$result['datenew'];
		  }
	  }
	  // weekly type
	  else if ($type=='WW')
	  {
		 $week_splt=split(";",$recur_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(";",$recur_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(";",$recur_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(";",$recur_details); 
		 $day=$splt[1];
		 $month=$splt[0]+1;
		 $month=(($month<10)?'0'.$month:$month);
		 $year=$result['year'];
		 if ($day<$result['day'] && $month<=$result['month']) $year=$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(";",$recur_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 get_loading_array($service_id){
 global $service,$languages_id,$nb_dates,$sInfo,$start_date,$end_date;
 
 $service=get_services_info((int)$service_id,$languages_id);
 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=$nbk;
	$recurring_type=$sInfo["recurring_type"];
	/*$nb_dates=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; 
	$loading_price_dates[]=formated_type_dates('dates',true,true);*/
	 if($recurring_type!='DD'){ 
		$nb_dates=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;
		$start_date=$week_start_date;
		$end_date=$week_end_date; 
		$loading_price_dates[]=formated_type_dates('dates',true,true);
	 }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_week_start_date=$nbk['no_booking_start_date'];
		 $tep_week_end_date=$nbk['no_booking_end_date'];
		 		$no_b_stime=$nbk['no_booking_start_time'];
				$no_b_etime=$nbk['no_booking_end_time'];
				if($booking_type=='D'){
					$no_b_stime="00:00:00";
					$no_b_etime="24:00:00";
				}
				$no_b_sdate=$tep_week_start_date;
				$no_b_edate=$tep_week_end_date;
				$price=$nbk['loadings_price'];
				$loading_type=$nbk['loadings_type'];	
		 		/*if($no_b_etime<=$no_b_stime && $span_days=='Y')
					$no_b_edate=date("Y-m-d",tep_dateadd(@strtotime($tep_week_start_date),"day",1));
				else if($no_b_etime<=$no_b_stime && $span_days=='N')
					$no_b_etime="24:00:00";*/
				if($span_days=='Y' && $no_b_etime<$no_b_stime){
					$loading_price_dates[]=array('price'=>$price,'loading_type'=>$loading_type,'type'=>$recurring_type,'n_s_date'=>$no_b_sdate,'n_e_date'=>$no_b_sdate,'n_s_time'=>$no_b_stime,'n_e_time'=>'24:00:00');
					$loading_price_dates[sizeof($loading_price_dates)]=array('price'=>$price,'loading_type'=>$loading_type,'type'=>$recurring_type,'n_s_date'=>$no_b_edate,'n_e_date'=>$no_b_edate,'n_s_time'=>'00:00:00','n_e_time'=>$no_s_etime);
			  	}else {
			  		$loading_price_dates[]=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($tep_week_start_date) $tep_week_start_date=date('Y-m-d',tep_dateadd(@strtotime($tep_week_start_date),"day",1));
	}
 }

  return $loading_price_dates;
}
		
 function formated_type_dates($type='dates',$price_value=false,$loadingtype=false){
	global $service_id,$nb_dates,$sInfo,$combo_start_date,$recurring_type,$languages_id,$start_date,$end_date,$service;
	if($service_id) $service=get_services_info($service_id,$languages_id);
	$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<count($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){ 
		$nobsplit=split("-",$no_b_sdate);
		$no_b_sdate_mktime=mktime(0,0,0,$nobsplit[1],$nobsplit[2],$nobsplit[0]);
		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",tep_dateadd($no_b_sdate_mktime,"day",1));
		else if($no_b_etime<=$no_b_stime && $span_days=='N')
			$no_b_etime="24:00:00";
		//if($start_date<=$no_b_sdate || $no_b_sdate<=$end_date){
		if($no_b_sdate>=$start_date && $end_date>=$no_b_sdate){
			//$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);
			$total_dates_nb[]=array('price'=>$price,'loading_type'=>$loading_type,'type'=>$recurring_type,'n_s_date'=>$no_b_sdate,'n_e_date'=>$no_b_sdate,'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' && $time_length!='' && date("d",mktime(($nb_split[0]+$time_length),$mt,0,1,1,1987))=="02"))
				$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';
		 }
	  }
    }
    //print_r($total_dates_nb);
    if($type=='dates')
		return $total_dates_nb;
    else 
		return $total_dates_nbdates;	
  }
  	
  		function	tep_get_resource_name($res_id,$field,$lang_id=1){
  			global $languages_id;
  			$lang_id=$languages_id;
			$resource_name="";
			if($res_id=='' || $lang_id=='') return;
 			$res_query=tep_db_query("select  ".$field ." from " . TABLE_SERVICE_RESOURCE ." re," . TABLE_SERVICE_RESOURCE_DESCRIPTIONS ." red  where re.resource_id=red.resource_id and red.language_id='".(int)$lang_id."' and re.resource_id='".(int)$res_id."'");
			$res_resource=tep_db_fetch_array($res_query);
			if($res_resource[$field]!='')	$resource_name=$res_resource[$field];
			return $resource_name;
   		}

	 	function get_resource_detais($service_id,$start_date,$end_date,$start_time,$end_time,$booking_type){
				if($service_id==0) return;
				$resource_ids=array();
				$where="";
				$start_time.=':00';
				$end_time.=':00';
				$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_order=tep_db_query("select  os.resource_id 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."");
				$get_order_quantity=tep_db_query("select os.resource_id from " .TABLE_ORDERS_PRODUCTS." op,".TABLE_ORDERS_SERVICES ." os where os.products_id=op.products_id and os.orders_id=op.orders_id and op.products_type='V' and op.products_id='".(int)$service_id . "'".$where."");
									 
				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'];	
					}
				}
				return $resource_ids;
			}
	
	
	
// get the total no of reserved users
function tep_service_reserve_count($service_id,$start_date,$end_date,$start_time,$end_time,$pending_period)
{
	$count=0;
	$pending_option="";
	if ((int)$pending_period>0){
		$pending_option=" and (o.orders_status>1 or date_add(o.date_purchased,interval s.pending_period day)>='".date('Y-m-d H:i:s',getServerDate(false))."' and op.orders_products_status!=5)";
	}
	
	$query=tep_db_query("select count(os.orders_id) as total_count from " . TABLE_ORDERS . " o, " .TABLE_ORDERS_SERVICES." os, ". TABLE_SERVICES. " s, ".
						TABLE_ORDERS_PRODUCTS . " op where o.orders_id=op.orders_id and op.orders_id=os.orders_id and s.service_id=os.products_id and ". 
						"date_format(os.start_date,'%Y-%m-%d')='".$start_date."' and date_format(os.end_date,'%Y-%m-%d')='".
						$end_date."' and time_format(os.start_time,'%H:%i') ='".$start_time."' and time_format(os.end_time,'%H:%i') ='".
						$end_time."' and op.products_id=os.products_id and op.products_type='V'  and op.products_id='" . $service_id ."' " . $pending_option.
						"  and s.include_resource='N'");
	$result=tep_db_fetch_array($query);
	$count+=(int)$result['total_count'];

	return $count;
}
	
function tep_get_resource($field,$resource_id,$language_id){
	global $languages_id;
	$language_id=$languages_id;

    if($field=='' && $resource_id=='' && $language_id=='') return;
 	$resource_query=tep_db_query("select " .$field . " from " . TABLE_SERVICE_RESOURCE . " re," . TABLE_SERVICE_RESOURCE_DESCRIPTIONS . " 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_services_info($service_id,$lan_id=''){
		global $languages_id; 
		if($lan_id) $lan_id=$languages_id;
		if($service_id==0  && $lan_id==0) return;	
		$service_query=tep_db_query("select se.*,sed.* 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 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=$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="";	
    $loading_price="";
   if(is_array($loading_price_dates)){
	for($i=0;$i<sizeof($loading_price_dates);$i++){
	  if($loading_price_dates[$i]['type']=='DD'){
  	 		if($booking_type=='D'){
				$loading_start_time=split(" ",$loading_price_dates[$i]['n_s_date']);	
				$loading_end_time=split(" " ,$loading_price_dates[$i]['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_date=$loading_price_dates[$i]['n_s_date'];
				$loading_start_time=$loading_price_dates[$i]['n_s_time'];
				$loading_end_date=$loading_price_dates[$i]['n_e_date'];
				$loading_end_time=$loading_price_dates[$i]['n_e_time'];
				$select_start_date=$start_date;
				$select_start_time=$start_time;
				$select_end_date=$end_date;
				$select_end_time=$end_time;
				/*if($booking_type=='H'){
					$loading_start_time=$loading_start_date.' '.$loading_start_time;
					$loading_end_time=$loading_end_date.' '.$loading_end_time;	
					$select_start_time=$start_date.' '.$start_time;
					$select_end_time=$end_date.' '.$end_time;	
				}*/
			}
			//echo $loading_start_time.'-'.$loading_end_time .'-'.$select_start_time.'-'.$select_end_time.'<br>';
			$loading_price=$loading_price_dates[$i]['price']; 
			$loading_type=$loading_price_dates[$i]['loading_type'];
			if($loading_type=='P'){
				$loading_price=($final_price*$loading_price)/100;		
			}
			/*if((($select_start_date>=$loading_start_date and $select_start_time>=$loading_start_time and $select_start_date<=$loading_end_date and  $select_start_time<=$loading_end_time) OR  ($select_end_date>=$loading_start_date and $select_end_time>=$loading_start_time and $select_end_date<=$loading_end_date and $select_end_time<=$loading_end_time) OR  ($select_start_date<=$loading_start_date and $select_start_time<=$loading_start_time and $select_end_date>=$loading_end_date and $select_end_time>=$loading_end_time))){
				$price+=$loading_price;
			}*/
			/*if((($select_start_date>=$loading_start_date and $select_start_time>=$loading_start_time) OR ($select_start_date<=$loading_end_date and  $select_start_time<=$loading_end_time) OR  ($select_end_date>=$loading_start_date and $select_end_time>=$loading_start_time and $select_end_date<=$loading_end_date and $select_end_time<=$loading_end_time) OR  ($select_start_date<=$loading_start_date and $select_start_time<=$loading_start_time and $select_end_date>=$loading_end_date and$select_end_time>=$loading_end_time))){
				$price+=$loading_price; 	
		    }*/
			if($booking_type=='H' && (($select_start_time>=$loading_start_time and $select_start_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;	
		    }else  if($booking_type=='D' && (($select_start_date>=$loading_start_date and $select_start_time>=$loading_start_time and $select_start_date<=$loading_end_date and  $select_start_time<=$loading_end_time) OR  ($select_end_date>=$loading_start_date and $select_end_time>=$loading_start_time and $select_end_date<=$loading_end_date and $select_end_time<=$loading_end_time) OR  ($select_start_date<=$loading_start_date and $select_start_time<=$loading_start_time and $select_end_date>=$loading_end_date and$select_end_time>=$loading_end_time))){
				$price+=$loading_price; 	
		    }
	  }else {	  
		  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;
				}
				//echo $loading_start_time .' - '. $loading_end_time .' <br> '.$select_start_time .' - '. $select_end_time.'<br>';
				$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 get_resource_ids($service_id,$start_date,$end_date,$start_time,$end_time,$return_type='',$resource_id=''){
    global $check_products,$languages_id;
	if($service_id) $services=get_services_info((int)$service_id,(int)$languages_id);
	if($service_id==0) return;
	$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 '".$services['pending_period']."' day)>'" . date('Y-m-d H:i:s',getServerDate(false)) . "' and op.orders_products_status!=5)";
	$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))) and op.products_id='".$service_id."'";
	$get_edit_order=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_product=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 op.orders_products_id=os.orders_products_id and  op.products_id=os.products_id and  op.products_id='".(int)$service_id."'".$where."");
	$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 o.orders_id = os.orders_id and o.orders_id = op.orders_id and op.orders_products_id and 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.products_id='".(int)$service_id . "'".$where.$check);
	if(tep_db_num_rows($get_edit_order_product)>0){
	  while($order_edit=tep_db_fetch_array($get_edit_order_product)){
		$resource_ids[].=$order_edit['resource_id'];
		$resource_dates[].=$order_edit['end_date'].' '.$order_edit['end_time'];
	  }
	}			 
	if(tep_db_num_rows($get_edit_order)>0){
	  while($order_edit_quantity=tep_db_fetch_array($get_edit_order)){
	    $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_order_quantity)>0){
		while($order_quantity=tep_db_fetch_array($get_order_quantity)){
			$resource_ids[].=$order_quantity['resource_id'];	
			$resource_dates[].=$order_quantity['end_date'].' '.$order_quantity['end_time'];
		}
	}
	if($check_products){
		for($i=0;$i<=sizeof($check_products);$i++){
			if($check_products[$i]['element_type']=='V'){
				if($end_date && $end_time) $end_time_string=tep_dateadd(strtotime($end_date.' '.$end_time),'hr',1);
				$end_date=date('Y-m-d',$end_time_string);
				$end_time=date('H:i:s',$end_time_string);				
				if((($start_date.' '.$start_time>=$check_products[$i]['others']['start_date'].' '.$check_products[$i]['others']['start_time'] and  $start_date.' '.$start_time <=$check_products[$i]['others']['end_date'].' '.$check_products[$i]['others']['end_time']) OR ($end_date.' '.$end_time>=$check_products[$i]['others']['start_date'].' '.$check_products[$i]['others']['start_time'] and $end_date . ' '.$end_time<=$check_products[$i]['others']['end_date'].' '.$check_products[$i]['others']['end_time']) OR ($start_date.' '.$start_time<=$check_products[$i]['others']['start_date'].' '.$check_products[$i]['others']['start_time'] and $end_date.' '.$end_time>=$check_products[$i]['others']['end_date'].' '.$check_products[$i]['others']['end_time']))) { 	
				 	$resource_ids[].=$check_products[$i]['others']['resource_id'];
				 	if($resource_id && $resource_id==$check_products[$i]['others']['resource_id'])	$resource_ids[].=$check_products[$i]['others']['resource_id'];
				 	if($return_type=='dates' && $resource_id==$check_products[$i]['others']['resource_id']) $resource_dates[].=$check_products[$i]['others']['end_date'].' '.$check_products[$i]['others']['end_time'];
				}
			}
		}
	}
	if($return_type=='dates')
	return $resource_dates;
	else if($return_type=='')
	return $resource_ids;
}

function tep_get_service_booking_details($orders_id){
  if($orders_id==0) return;
	 $get_details_query=tep_db_query("select 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 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 o.orders_id='".(int)$orders_id."' and op.orders_products_status!=5 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)){
			$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'],'products_id'=>$get_details['products_id'],'resource_id'=>$get_details['resource_id'],'resource_name'=>$get_details['resource_name'],'products_quantity'=>$get_details['products_quantity']);
		}
	 }
	 return $service_details;
  }
 
 function tep_check_service_found($service_id,$start_date,$end_date,$start_time,$end_time,$type=""){
		global $service_info,$check_products,$services,$resource_id;
		$reserved_quantity="";
		$where="";
		$error="";
		$return="";
		$avil_quan="";
		$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']);
		$resource_id=""; 
		if($services->resource_id) $resource_id=$services->resource_id;			
		// get order edit products
		$reserved_quantity=get_orders_products_quantity((int)$service_id,$start_date,$end_date,$start_time,$end_time,$booking_type,$resource_id,$check_products);
		// get current product quantity with order_edit_product
		if($services && $services->qty) $reserved_quantity+=$services->qty;
		$return=true; 
		if($reserved_quantity>$service_quantity){ 
		   $avil_quan=(int)$service_quantity-$reserved_quantity;		   
		   if($service_quantity-($reserved_quantity-$services->qty)>0){
		   	 $error=sprintf(ERR_QTY_EXICTED,$service_quantity-($reserved_quantity-$services->qty));
		   	 $return=false;	
		   }else if($avil_quan<=0){
		   	$error=ERR_TIME_ALREADY_RESERVED;
		   	if($service_info['include_resource']=='N') $error="The selected period for the service is already reserved. Select other period";	
			$return=false;
		   }
		} 
		if($type=='error')
			return $error;
		else
			return $return;
	}
	
	function get_orders_products_quantity($service_id,$start_date,$end_date,$start_time,$end_time,$booking_type='H',$resource_id=0,$check_products=""){
		if($service_id==0) return;
		global $services,$languages_id;
		if($service_id) $services_info=get_services_info($service_id,$languages_id);
		$quantity="";
		$res_quantity="";
		$service_id_string="";
		if($resource_id>0)$where="and os.resource_id='".(int)$resource_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))) group by op.products_id";
		$orders_edit_products_quantity=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."");
		if(tep_db_num_rows($orders_edit_products_quantity)>0){
			$order_edit_quantity=tep_db_fetch_array($orders_edit_products_quantity);
			$res_quantity+=$order_edit_quantity['quantity'];
		}
		//$get_edit_order=tep_db_query("select op.customers_basket_quantity as quantity,op.products_id,os.start_date,os.end_date,os.start_time,os.end_time from ".TABLE_CUSTOMERS_BASKET." op,".TABLE_CUSTOMERS_BASKET_SERVICES ." os  where  op.products_id=os.products_id ".$where."");
		//echo "select op.customers_basket_quantity as quantity,op.products_id,os.start_date,os.end_date,os.start_time,os.end_time from ".TABLE_CUSTOMERS_BASKET." op,".TABLE_CUSTOMERS_BASKET_SERVICES ." os  where  op.products_id=os.products_id ".$where.""; 
		$get_order_quantity=tep_db_query("select sum(op.products_quantity) as quantity from " .TABLE_ORDERS_PRODUCTS." op,".TABLE_ORDERS_SERVICES ." os," .TABLE_ORDERS ." o where o.orders_id=op.orders_id and o.orders_id=os.orders_id and (o.orders_status>1 or date_add(o.date_purchased,interval '".$services_info['pending_period']."' day)>'".date('Y-m-d H:i:s',getServerDate(false))."') and op.orders_products_id=os.orders_products_id and os.orders_id=op.orders_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."");
		//echo "select sum(op.products_quantity) as quantity from " .TABLE_ORDERS_PRODUCTS." op,".TABLE_ORDERS_SERVICES ." os," .TABLE_ORDERS ." o where o.orders_id=op.orders_id and o.orders_id=os.orders_id and (o.orders_status>1 or date_add(o.date_purchased,interval '".$services_info['pending_period']."' day)>'".date('Y-m-d H:i:s',getServerDate(false))."') and op.orders_products_id=os.orders_products_id and os.orders_id=op.orders_id and os.products_id=op.products_id and os.orders_id=op.orders_id and op.products_type='V' and op.products_id='".(int)$service_id . "'".$where."";		 
		// get quantity customer basket
		/*if(tep_db_num_rows($get_edit_order)>0){
			while($order_edit_quantity=tep_db_fetch_array($get_edit_order)){
			 $pro_id=tep_get_service_prid($order_edit_quantity['products_id']);
		  	 if($pro_id==$service_id){
			   $res_quantity+=$order_edit_quantity['quantity'];
			  
			 }
			}
		}*/
		// get quantity from order table 			 
		if(tep_db_num_rows($get_order_quantity)>0){
			$order_quantity=tep_db_fetch_array($get_order_quantity);
			$res_quantity+=$order_quantity['quantity'];
				
		}
		// get quantity from cart
		/*if($check_products && !tep_session_is_registered('customer_id')){
			for($i=0;$i<=sizeof($check_products);$i++){
				if($check_products[$i]['element_type']=='V'){
				 //$product_id = tep_get_service_prid($check_products[$i]['id']);
				 $product_id = $check_products[$i]['id'];
				if($product_id==$service_id && ((($start_date.' '.$start_time>=$check_products[$i]['others']['start_date'].' '.$check_products[$i]['others']['start_time']) && ($start_date.' '.$start_time<=$check_products[$i]['others']['end_date'].' '.$check_products[$i]['others']['end_time'])) || (($end_date.' '.$end_time>=$check_products[$i]['others']['start_date'].' '.$check_products[$i]['others']['start_time']) && ($end_date.' '.$end_time<=$check_products[$i]['others']['end_date'].' '.$check_products[$i]['others']['end_time'])) || (($start_date.' '.$start_time<=$check_products[$i]['others']['start_date'].' '.$check_products[$i]['others']['start_time']) && ($end_date.' '.$end_time>=$check_products[$i]['others']['end_date'].' '.$check_products[$i]['others']['end_time'])))){
					$res_quantity+=$check_products[$i]['quantity'];	
					
				}
			  }
			}
		} */ 
		return $res_quantity;
	}
	
	function get_cart_contents_quantity($service_id,$week_start_date,$week_end_date){
				global $service_info,$cart;
				$check_products=$cart->get_products();
				$booking_quantity="";
				if($service_id=='' && $week_start_date=='' && $week_end_date=='') return;
				$where=" and (('".$week_start_date."'>=os.start_date and '".$week_start_date."'<=os.end_date) OR ('".$week_end_date."'>=os.start_date and '".$week_end_date."'<=os.end_date) OR ('".$week_start_date."'<=os.start_date and '".$week_end_date."'>=os.end_date)) group by op.products_id";
				$get_edit_order=tep_db_query("select sum(op.customers_basket_quantity) as quantity,os.start_date,os.end_date,os.start_time,os.end_time from ".TABLE_CUSTOMERS_BASKET." op,".TABLE_CUSTOMERS_BASKET_SERVICES ." os  where  op.products_id=os.products_id and  op.products_id='".(int)$service_id."'".$where."");
				if(tep_db_num_rows($get_edit_order)>0){
					$order_edit_quantity=tep_db_fetch_array($get_edit_order);
					$booking_quantity+=$order_edit_quantity['quantity'];
				}			 
				if($check_products){
					for($i=0;$i<=sizeof($check_products);$i++){
						if($check_products[$i]['element_type']=='V'){
						//$product_id = tep_get_service_prid($check_products[$i]['id']);
						$product_id = $check_products[$i]['id'];
						if($product_id==$service_id && ((($week_start_date>=$check_products[$i]['others']['start_date']) && ($week_start_date<=$check_products[$i]['others']['end_date'])) || (($week_end_date>=$check_products[$i]['others']['start_date']) && ($week_end_date<=$check_products[$i]['others']['end_date'])) || (($week_start_date<=$check_products[$i]['others']['start_date']) && ($week_end_date>=$check_products[$i]['others']['end_date'])))){
							$booking_quantity+=$check_products[$i]['quantity'];	
						}
					}
				  }
				}
	}
	function get_valid_resource($service_id,$resource_id,$start_date,$end_date,$start_time,$end_time){
	    global $check_products,$languages_id;
		if($service_id) $services=get_services_info((int)$service_id,(int)$languages_id);
		if($service_id==0) return;
		$resource_ids=array();
		$where="";
		$start_time.=':00';
		$end_time.=':00';
		$check="";
		$check=" and (o.orders_status>1 or date_add(o.date_purchased,interval '".$services['pending_period']."' day)>'" . date('Y-m-d H:i:s',getServerDate(false)) . "' and op.orders_products_status!=5 )";
		$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))) and op.products_id='".$service_id."'";
		$get_edit_order=tep_db_query("select op.products_id,os.resource_id from ".TABLE_CUSTOMERS_BASKET." op,".TABLE_CUSTOMERS_BASKET_SERVICES ." os  where  op.products_id=os.products_id ".$where."");
		$get_edit_order_product=tep_db_query("select os.resource_id from ".TABLE_ORDERS_EDIT_PRODUCTS." op,".TABLE_ORDERS_EDIT_SERVICES ." os  where op.orders_products_id=os.orders_products_id and  op.products_id=os.products_id and  op.products_id='".(int)$service_id."'".$where."");
		$get_order_quantity=tep_db_query("select os.resource_id from ".TABLE_ORDERS . " o," .TABLE_ORDERS_PRODUCTS." op,".TABLE_ORDERS_SERVICES ." os where o.orders_id = os.orders_id and o.orders_id = op.orders_id and op.orders_products_id and 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.products_id='".(int)$service_id . "'".$where.$check);
		if(tep_db_num_rows($get_edit_order_product)>0){
		  while($order_edit=tep_db_fetch_array($get_edit_order_product)){
			$resource_ids[].=$order_edit['resource_id'];
		  }
		}			 
		if(tep_db_num_rows($get_edit_order)>0){
		  while($order_edit_quantity=tep_db_fetch_array($get_edit_order)){
		    $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']; 
			}
		  }
		}
		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($check_products){
			for($i=0;$i<=sizeof($check_products);$i++){
				if($check_products[$i]['element_type']=='V'){
					if((($start_date.' '.$start_time>=$check_products[$i]['others']['start_date'].' '.$check_products[$i]['others']['start_time'] and  $start_date.' '.$start_time <=$check_products[$i]['others']['end_date'].' '.$check_products[$i]['others']['end_time']) OR ($end_date.' '.$end_time>=$check_products[$i]['others']['start_date'].' '.$check_products[$i]['others']['start_time'] and $end_date . ' '.$end_time<=$check_products[$i]['others']['end_date'].' '.$check_products[$i]['others']['end_time']) OR ($start_date.' '.$start_time<=$check_products[$i]['others']['start_date'].' '.$check_products[$i]['others']['start_time'] and $end_date.' '.$end_time>=$check_products[$i]['others']['end_date'].' '.$check_products[$i]['others']['end_time']))) {
					 	$resource_ids[].=$check_products[$i]['others']['resource_id'];
					}
				}
			}
		}
	return $resource_ids;
	}
	function tep_get_parent_service_categories(&$categories, $categories_id) {
   
  // echo "select parent_id from " . TABLE_SERVICES_CATEGORIES . " where services_categories_id = '" . (int)$categories_id . "'";
    $parent_categories_query = tep_db_query("select parent_id from " . TABLE_SERVICES_CATEGORIES . " where services_categories_id = '" . (int)$categories_id . "'");
    while ($parent_categories = tep_db_fetch_array($parent_categories_query)) {
      if ($parent_categories['parent_id'] == 0) return true;
      $categories[sizeof($categories)] = $parent_categories['parent_id'];
      if ($parent_categories['parent_id'] != $categories_id) {
        tep_get_parent_categories($categories, $parent_categories['parent_id']);
      }
    }
  }  
  
	function tep_get_service_path($products_id) {
    $cPath = '';
	$category_sql = "select s2c.services_categories_id from " . TABLE_SERVICES . " s, " . TABLE_SERVICES_TO_SERVICES_CATEGORIES . " s2c where s2c.services_categories_id = '" . (int)$products_id . "' and s.service_status = '1' and s.service_id = s2c.service_id limit 1";
	$category_query = tep_db_query($category_sql);
    if (tep_db_num_rows($category_query)) {
      $category = tep_db_fetch_array($category_query);

      $categories = array();
      tep_get_parent_service_categories($categories, $category['services_categories_id']);

      $categories = array_reverse($categories);

      $cPath = implode('_', $categories);

      if (tep_not_null($cPath)) $cPath .= '_';
      $cPath .= $category['services_categories_id'];
    }

    return $cPath;
  }
  
  // services tree structure
function tep_get_service_output_tree($parent_id = '0',&$content,$default,$service_category_id=0) {
    global $languages_id,$selected_name,$login_id,$login_groups_type;

	// iterate with nested category

	$service_where = '';
	if($service_category_id>0)$service_where = " and sc.services_categories_id='" . $service_category_id . "'";

	$service_category_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 . "' " . $service_where . " order by sc.sort_order, scd.services_categories_name");
	
	while ($service_category = tep_db_fetch_array($service_category_query)) {
		$content.= '<optgroup style="color:#0000FF" label="' . write_services_category_space($service_category['services_categories_id']) . tep_output_string($service_category['services_categories_name'], array('"' => '&quot;', '\'' => '&#039;', '<' => '&lt;', '>' => '&gt;')) . '">';
		// select the list of service of particular category
		$service_query=tep_db_query("select sed.service_name,sed.service_id from " . TABLE_SERVICES . ' se, ' . TABLE_SERVICES_DESCRIPTION . " sed, " . TABLE_SERVICES_TO_SERVICES_CATEGORIES . " scd where scd.services_categories_id='" . $service_category['services_categories_id'] . "' and sed.language_id = " . (int)$languages_id . " " . SERVICES_CONDITION_STATUS. " and se.service_id=scd.service_id and se.service_id=sed.service_id order by sed.service_name");
		while ($service=tep_db_fetch_array($service_query))
		{
			$content .= '<option style="color:#000000" value="' . tep_output_string($service['service_id']) . '"';
			if ($default == $service['service_id']){
				$selected_name=$service['service_name'];
				$content .= ' SELECTED';
			}
			$content .= '>' . tep_output_string($service['service_name'], array('"' => '&quot;', '\'' => '&#039;', '<' => '&lt;', '>' => '&gt;')) . '</option>';
		}    
		tep_get_service_output_tree($service_category['services_categories_id'], $content,$default);
		$content.='</optgroup>';
	}

}
	function write_services_category_space($category_id){
	    global $languages_id,$selected_name,$login_id,$login_groups_type;
		$sql = "select parent_id,sc.services_categories_id,services_categories_name 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.services_categories_id=" . $category_id;
		$query = tep_db_query($sql);
		$result = tep_db_fetch_array($query);
		if($result['parent_id']>0){
			return "&nbsp;&nbsp;" . write_services_category_space($result['parent_id']);
		}else{
			return "";
		}
	}
	// Output a form pull down menu
	function tep_draw_service_select_menu($name, $values, $default = '', $parameters = '', $required = false,$initial_category_id=0,$need_all=true,$initial_parent_id=0) {
		global $selected_name;
		$field = '<select name="' . tep_output_string($name) . '"';
	
		if (tep_not_null($parameters)) $field .= ' ' . $parameters;
	
		$field .= '>';
		if($need_all)
		$field .= '<option style="color:#000000" value="-1">' . TEXT_SELECT . '</option>';
		
		if (empty($default) && isset($GLOBALS[$name])) $default = stripslashes($GLOBALS[$name]);
	
		$content="";
		tep_get_service_output_tree($initial_parent_id,$content,$default,$initial_category_id);
		$field.=$content;
	$field .= '</select>';
	
	if ($required == true) $field .= TEXT_FIELD_REQUIRED;
	
	return $field;
	}
	// service tree
	function tep_get_service_array_single($first=''){
		global $languages_id;
		$service_array=array();
		$service_query=tep_db_query("SELECT se.service_id,sed.service_name from " . TABLE_SERVICES . " se, " . TABLE_SERVICES_DESCRIPTION . " sed where se.service_id=sed.service_id and language_id='" . $languages_id . "' " . SERVICES_CONDITION_STATUS . " order by sed.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;
	} 
	
	//service discount start
	function services_discount($service_id){
		global $dates;
		$return=0;
		$service_amount=$dates['service_costs'];
		if($service_id!=""){
			$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
?>
