<?php
/*
	osCommRes, Services Oline 
	http://www.oscommres.com 
	Copyright (c) 2005 osCommRes 
	
	Freeway eCommerce 
	http://www.zac-ware.com/freeway 
	Copyright (c) 2007 ZacWare
	
	Released under the GNU General Public License
*/
    // Set flag that this is a parent file
	define( '_FEXEC', 1 );
	require('includes/application_top.php');
	require(DIR_WS_LANGUAGES . $language . '/' . FILENAME_SERVICE_RESOURCES);
	set_time_limit(15);
	$service_id=(isset($HTTP_GET_VARS["service_id"])?(int)$HTTP_GET_VARS["service_id"]:0);
	$service_info=get_services_info((int)$service_id,(int)$languages_id);
	if ($service_id<=0) tep_redirect(FILENAME_DEFAULT);
	$check_products=$cart->get_products();
	if($HTTP_SESSION_VARS['time_details']) $HTTP_POST_VARS=$HTTP_SESSION_VARS['time_details'];
	if($services->qty) $HTTP_POST_VARS['products_qty']=$services->qty;
	if($service_info['booking_type']=='D' && $HTTP_POST_VARS['end_times']){
		$start_times=tep_db_prepare_input($HTTP_POST_VARS['start_times']);
		$end_times=tep_db_prepare_input($HTTP_POST_VARS['end_times']);
		$start_times_splt=split(" ",$start_times);
		$HTTP_POST_VARS['start_date']=$start_times_splt[0];
		$HTTP_POST_VARS['start_time']=$start_times_splt[1];
		$end_times_splt=split(" ",$end_times);
		$HTTP_POST_VARS['end_date']=$end_times_splt[0];
		$HTTP_POST_VARS['end_time']=$end_times_splt[1];
	}
	$start_tm=tep_db_prepare_input($HTTP_POST_VARS['start_time']);
	$end_tm=tep_db_prepare_input($HTTP_POST_VARS['end_time']);
	$end_tm_split=split(":",$end_tm);
	if($end_tm_split[1]!='' && substr($end_tm_split[1],1,1)!=9) $HTTP_POST_VARS['end_time']=date("H:i",@strtotime(tep_db_prepare_input($HTTP_POST_VARS['end_time']))-60);	 
	$start_date=tep_db_prepare_input($HTTP_POST_VARS['start_date']);
	$error="";
	if($HTTP_GET_VARS['action_edit']!='edit'){	
	$start_time=isset($HTTP_POST_VARS['start_time'])?tep_db_prepare_input($HTTP_POST_VARS['start_time']):'';
	$start_hour=split(":",$start_time);
	if($start_hour[0]<10 && strlen($start_hour[0])<2) $start_time="0".tep_db_prepare_input($start_time);		
	$end_time=isset($HTTP_POST_VARS['end_time'])?tep_db_prepare_input($HTTP_POST_VARS['end_time']):'';
	if($start_time=="24:00") $start_time="12:00";
    $start_date=isset($HTTP_POST_VARS['start_date'])?tep_db_prepare_input($HTTP_POST_VARS['start_date']):'';
    $end_date=isset($HTTP_POST_VARS['end_date'])?tep_db_prepare_input($HTTP_POST_VARS['end_date']):'';
	$quantity=isset($HTTP_POST_VARS['products_qty'])?tep_db_prepare_input($HTTP_POST_VARS['products_qty']):1;
	if ($start_date=="" || $start_time=="" || $end_date=="" || $end_time=="") tep_redirect(tep_href_link(FILENAME_DEFAULT));
	if (strlen($start_time)==5) $start_time.=":00";
	if (strlen($end_time)==5) $end_time.=":00";
		$services->service_id=tep_db_prepare_input($service_id);
		$services->start_date=tep_db_prepare_input($start_date);
		$services->end_date=tep_db_prepare_input($end_date);
		$services->start_time=tep_db_prepare_input($start_time);
		$services->end_time=tep_db_prepare_input($end_time);
		$services->booking_type=tep_db_prepare_input($HTTP_POST_VARS['booking_type']);
		$services->qty=(int)$HTTP_POST_VARS['products_qty'];
		$time_booking=tep_time_diff($start_date.' ' .$start_time,$end_date.' ' . $end_time);		
        $booking=$time_booking['hours'];        
        if($service_info['booking_type']=='M') $booking=$time_booking['minutes'];
        else if($service_info['booking_type']=='D') $booking=$time_booking['days'];
		if($booking) $services->bookings=$booking;
		if($HTTP_POST_VARS['resource_costs']){
			//service discount start
			$dates['service_costs']=tep_db_prepare_input($HTTP_POST_VARS['resource_costs']);
			$services->resource_costs=tep_db_prepare_input($HTTP_POST_VARS['resource_costs'])-services_discount($service_id);
			//end
			//$services->resource_costs=$HTTP_POST_VARS['resource_costs'];
			$services->tax_class_id=tep_db_prepare_input($HTTP_POST_VARS['tax_class_id']);	
		}
	}
	if($HTTP_GET_VARS['action_edit']=='edit'){
		$start_date=$services->start_date;	
		$start_tm=$services->start_time;
		$start_time=$services->start_time;
		$end_time=$services->end_time;
		$end_date=$services->end_date;
	 	$end_tm=$services->end_time;			
	} 
	$start_time_get=$start_tm;
	$end_time_get=$end_tm;
	if($start_time_get=="24:00")  $start_time_get="12:00";
	$start_time_session=date("h:i A",@strtotime($start_time_get));
	$end_time_session=date("h:i A",@strtotime($end_time_get));
	$service=get_services_info((int)$service_id,(int)$languages_id);
	if($service['include_resource']=='N' && $service['multiple_purchase']=='Y') {
		$service_info=$service;
		$er="";
		$er=tep_check_service_found($service_id,$start_date,$end_date,$start_time,$end_time,"error");
		if($er!='') tep_redirect(tep_href_link(FILENAME_SERVICES_INFO,'service_id='.$service_id.'&error='.urlencode($er)));  
	}
	// get reserved resource 
	$reserved_resource_id="";
	$book_buffer='N';
	$booking_buffer=$service['booking_buffer'];
	$booking_buffer_split=split(",",$booking_buffer);	
    $book_buffer_minute=0;
	if($reserved_resource){
		while(list($key,$value)=each($reserved_resource))
		  if($value>0) $reserved_resource_id.=str_replace(",",",",$value.((sizeof($reserved_resource)==$key+1)?"":','));
	}	
	if($service['include_resource']=='Y'){
		if(!$reserved_resource_id) $reserved_resource_id=0;
		$resource_query=tep_db_query("select red.resource_name,red.resource_description,re.resource_id,re.resource_costs,re.resource_tax_class_id from " . TABLE_SERVICE_RESOURCE . " re, " . TABLE_SERVICE_RESOURCE_DESCRIPTIONS . " red," .  TABLE_SERVICES_TO_SERVICES_RESOURCES . " seTre where seTre.service_id='" . tep_db_input($service_id) . "' and re.resource_id not in(".$reserved_resource_id.") and  seTre.service_resource_id=re.resource_id and re.resource_id=red.resource_id and red.language_id='". (int)$languages_id."' order by red.resource_name");
		$resource=true;
		if($service_info['include_resource']=='Y' && $error==''  && tep_db_num_rows($resource_query)<=0) $error=ERR_TIME_ALREADY_RESERVED;
	}		 
	// check service is exist
	if($service_info['include_resource']=='N') tep_redirect(tep_href_link(FILENAME_SERVICES_ATTRIBUTES,'service_id=' . $service_id));
	$content = CONTENT_SERVICE_RESOURCES;
	$javascript = 'popup_window.js';
	$display_mode="";
	require(DIR_WS_TEMPLATES . TEMPLATE_NAME . '/' . TEMPLATENAME_MAIN_PAGE);
	require(DIR_WS_INCLUDES . 'application_bottom.php');
	include(DIR_WS_INCLUDES."date_format_js.php");
	
?>
<script language="javascript">
if("<?php echo $error;?>" && document.getElementById("resource_header"))  document.getElementById("resource_header").innerHTML="<?php echo '<font size=2px color=#FB1112>'.$error.'</font>';?>";		
var include_resource="<?php echo $service_info['include_resource'];?>";
var include_resource_price="<?php echo $service_info['include_resource_price'];?>";
var frm=document.services_resource.elements["resource_name[]"];
var book_type="<?php echo $service_info['booking_type'];?>";
var resource_id=0;
var tempCheck=1;
resource_cost_array=new Array();
	<?php
		for($i=0;$i<sizeof($resource_price_array);$i++){
			$price=tep_get_resource('resource_costs',$resource_price_array[$i]['id'],$languages_id)-services_discount($service_id);
			$tax_class_id=tep_get_resource('resource_tax_class_id',$resource_price_array[$i]['id'],$languages_id);
			$service=$services_info;
			if($services_info['include_resource_price']=='N'){
				$price=$services_info['service_costs']-services_discount($service_id);
				$tax_class_id=$services_info['service_tax_class_id'];
			}
			$loading_price_dates=get_loading_array($service_id);
			$loading_price=tep_loading_price($loading_price_dates,$services->start_date,$services->end_date,$services->start_time,$services->end_time,$service["booking_type"],$price);
			if($loading_price<0) $loading_price=0;
			if($loading_price)	$price=$loading_price + $price;
			$price=tep_add_tax($price,tep_get_tax_rate($tax_class_id));
		?>
			resource_cost_array[<?php echo $resource_price_array[$i]['id'];?>]="<?php echo $price;?>";	
   <?php } ?>
function selectRowEffect(object, buttonSelect) {
  if (!selected) {
    if (document.getElementById)
      selected = document.getElementById('defaultSelected');
    else
      selected = document.all['defaultSelected'];
  }
  if (selected) selected.className = 'moduleRow';
  object.className = 'moduleRowSelected';
  selected = object;

// one button is not an array
  if (document.checkout_payment.payment[0]) {
    document.checkout_payment.payment[buttonSelect].checked=true;
  } else {
    document.checkout_payment.payment.checked=true;
  }
}

function rowOverEffect(object) {    
  if (object.className == 'moduleRow') object.className = 'moduleRowOver';  
}

function rowOutEffect(object) {  
  var index=0;
  var sel_obj=document.services_resource.elements["resource_name[]"];  	 
   if(object && object.childNodes[1].childNodes[0] && !object.childNodes[1].childNodes[0].checked && object.className == 'moduleRowOver') object.className="moduleRow";     
}
  do_radio(0);
  function do_radio(cou){	 
	 var st_date=document.getElementById("div_start_date");
	 var et_date=document.getElementById("div_end_date");
	 var st_time=document.getElementById("div_start_time");
	 var et_time=document.getElementById("div_end_time");
	 var sel_obj=document.services_resource.elements["resource_name[]"];
	 var dis_time_format='';
	 dis_time_format="<?php if(defined('TIME_FORMAT')) echo TIME_FORMAT; ?>";
	 var qty="<?php echo $service_quantity;?>"; 
	 var disply_costs=resource=0;
	 //change row class
	  if(sel_obj){
		for(;resource<sel_obj.length;resource++)
			if(sel_obj[resource] && resource!=cou && sel_obj[resource].parentNode.parentNode) sel_obj[resource].parentNode.parentNode.className="moduleRow";
	  }			
	 //change row class
	 if(frm){
	  if(frm.length>0 && ((cou) || cou==0)){ frm[cou].checked=true;  } else {frm.checked=true; }  
		if(frm.length>1){
			for(i=0;i<frm.length;i++){
			 if(frm[i].checked==true){
			  resource_split=frm[i].value;
			  resource_st=resource_split.split('#');
			  resource=resource_st[0].split('-');
			  resource_id=resource[1];
			  costs=resource[2];
			  tax_class_id=resource[3];
			  st_time_string=resource_st[1];
			  et_time_string=resource_st[2]; 	
			  st_time_string_spt=st_time_string.split(" ");		
			  et_time_string_spt=et_time_string.split(" ");
			  start_date=st_time_string_spt[0];
			  start_time=st_time_string_spt[1];
			  end_date=et_time_string_spt[0];
			  end_time=et_time_string_spt[1];
			  formatdate=dateAdd('n', 1,et_time_string_spt[0]+" "+et_time_string_spt[1]);
			  formatdate_splt=formatdate.split(" ");
			  var s_time=convert_to_stime(start_time);
			  var e_time=convert_to_stime(formatdate_splt[1]);
			  	if(dis_time_format!="") {
					if(dis_time_format=='24') {
						s_time=start_time;
						e_time=formatdate_splt[1];
					}
			  }
			  if(st_date && st_time_string_spt[0]) st_date.innerHTML=date_format(start_date,'Y-m-d','<?php echo EVENTS_DATE_FORMAT;?>');
			  if(st_time && st_time_string_spt[1]) st_time.innerHTML=s_time;  
			  if(et_date && et_time_string_spt[0]) et_date.innerHTML=date_format(formatdate_splt[0],'Y-m-d','<?php echo EVENTS_DATE_FORMAT;?>');
			  if(et_time && et_time_string_spt[1]) et_time.innerHTML=e_time;
			 }
		    }
		 } else{
		 	 if(frm.checked==true){
			 resource_split=frm.value;
			 resource_st=resource_split.split('#');
			 resource=resource_st[0].split('-');
			 resource_id=resource[1];
			 costs=resource[2];		
			 tax_class_id=resource[3]; 
			 st_time_string=resource_st[1];
			 et_time_string=resource_st[2];
			 st_time_string_spt=st_time_string.split(" ");		
			 et_time_string_spt=et_time_string.split(" ");
			 start_date=st_time_string_spt[0];
			 start_time=st_time_string_spt[1];
			 end_date=et_time_string_spt[0];
			 end_time=et_time_string_spt[1];
			 formatdate=dateAdd('n', 1,et_time_string_spt[0]+" "+et_time_string_spt[1]);
			 formatdate_splt=formatdate.split(" ");
			 
			 var s_time=convert_to_stime(start_time);
			 var e_time=convert_to_stime(formatdate_splt[1]);
				if(dis_time_format!="") {
				  if(dis_time_format=='24') {
					s_time=start_time;
					e_time=formatdate_splt[1];
				  }	
			 }
			 if(st_date && st_time_string_spt[0]) st_date.innerHTML=date_format(start_date,'Y-m-d','<?php echo EVENTS_DATE_FORMAT;?>');
			 if(st_time && st_time_string_spt[1]) st_time.innerHTML=s_time;
			 if(et_date && et_time_string_spt[0]) et_date.innerHTML=date_format(formatdate_splt[0],'Y-m-d','<?php echo EVENTS_DATE_FORMAT;?>');
			 if(et_time && et_time_string_spt[1]) et_time.innerHTML=e_time;
			 }
		 }
	 if(include_resource=='Y' && include_resource_price=='Y') {
	    var qty="<?php echo round($services->qty*($services->bookings/$service_info['service_total_time']));?>";
		tax_rate=getTaxRate(tax_class_id);
		pro_costs=updateGross(costs,tax_rate,false);
		if(document.getElementById("txt_price")) document.getElementById("txt_price").style.display="";
		temp_cost=costs;
		if(resource_cost_array[resource_id]) temp_cost=resource_cost_array[resource_id];
		if(document.getElementById("no_resource")) document.getElementById("no_resource").innerHTML=dollarAmount(qty*temp_cost);	
	  } 
	 document.services_resource.resource_ids.value=resource_id;
	 document.services_resource.resource_costs.value=costs; 	 	
	 document.services_resource.tax_class_id.value=tax_class_id;
	 document.services_resource.start_date.value=start_date;
	 document.services_resource.start_time.value=start_time;
	 document.services_resource.end_date.value=end_date;
	 document.services_resource.end_time.value=end_time;
	}
   }
function validate(){
	var error_result="";
	for(i=0;i<frm.length;i++){
	      if(frm[i].checked==true){
		      resource_split=frm[i].value;
		      resource=resource_split.split('-');
		      resource_id=resource[1];
		      costs=resource[2];		
	     }
	}
	if(resource_id==0)
	 	error_result+="<?php echo TEXT_SELECT_RESOURCE_ERROR; ?>\n";
	if(document.services_resource.elements['agreed']) {
		if (!document.services_resource.agreed.checked)
			error_result+="<?php echo TEXT_TERMS_AND_CONDITION; ?>";
	}	
	if(error_result!=""){
		alert(error_result);
		return false;
	}else{ 
		return true;
	}
}
function dateAdd(p_Interval, p_Number, p_Date){	
				if(isNaN(p_Number)){return false;}
				//convert date elements
				if (book_type=="H"){ 
					splt_hours=p_Date.split(" ");
					if(splt_hours[1]) splt_times=splt_hours[1].split(":");
					splt=splt_hours[0].split("-");  
					m=parseInt(splt[1],10);
					if (tempCheck==0) {
					  m--;
					  tempCheck=1;					  
					}
					var dt=new Date(parseInt(splt[0],10),parseInt(splt[1],10)-1,parseInt(splt[2],10),parseInt(splt_times[0],10),parseInt(splt_times[1],10));
				} else {
					splt_hours=p_Date.split(" ");
					if(splt_hours[1]) splt_times=splt_hours[1].split(":");
					splt=splt_hours[0].split("-");
					var dt=new Date(parseInt(splt[0],10),parseInt(splt[1],10)-1,parseInt(splt[2],10),parseInt(splt_times[0],10),parseInt(splt_times[1],10));
				}				
				p_Number = new Number(p_Number);
				switch(p_Interval.toLowerCase()){
					case "yyyy": {// year
						dt.setFullYear(dt.getFullYear() + p_Number);
						break;
					}
					case "q": {		// quarter
						dt.setMonth(dt.getMonth() + (p_Number*3));
						break;
					}
					case "m": {		// month
						dt.setMonth(dt.getMonth() + p_Number);
						break;
					}
					case "y":		// day of year
					case "d":		// day
					case "w": {		// weekday	
						dt.setDate(dt.getDate() + p_Number);
						break;
					}
					case "ww": {	// week of year
						dt.setDate(dt.getDate() + (p_Number*7));
						break;
					}
					case "h": {		// hour
						dt.setHours(dt.getHours() + p_Number);
						break;
					}
					case "n": {		// minute
						dt.setMinutes(dt.getMinutes() + p_Number);
						break;
					}
					case "s": {		// second
						dt.setSeconds(dt.getSeconds() + p_Number);
						break;
					}
					case "ms": {		// second
						dt.setMilliseconds(dt.getMilliseconds() + p_Number);
						break;
					}
					default: {
						return "invalid interval: '" + p_Interval + "'";
					}
				}
				
				/*if (book_type=="H") {
					hour=dt.getHours();
					minute=dt.getMinutes();
					if (hour<10) hour="0"+hour;
					if (minute<10) minute="0"+minute;
					return dt.getFullYear()+"-"+month+"-"+day+" "+hour+":"+minute;
				} else {
					hour=dt.getHours();
					minute=dt.getMinutes();
					if (hour<10) hour="0"+hour;
					if (minute<10) minute="0"+minute;
					day=dt.getDate();
					month=dt.getMonth()+1;
					if (day<10) day="0"+day;
					if (month<10) month="0"+month;
					return dt.getFullYear()+"-"+month+"-"+day+" "+hour+":"+minute;
				}*/
				hour=dt.getHours();
				minute=dt.getMinutes();
				if (hour<10) hour="0"+hour;
				if (minute<10) minute="0"+minute;
				day=dt.getDate();
				month=dt.getMonth()+1;
				if (day<10) day="0"+day;
				if (month<10) month="0"+month;
				return dt.getFullYear()+"-"+month+"-"+day+" "+hour+":"+minute;
			}
	function convert_to_stime(stime){
					splt=stime.split(":");
					hour=parseInt(splt[0],10);
					minutes=parseInt(splt[1],10);
					if (hour>=12 || (hour==12 && minutes>0)){
						if (hour>12) hour=hour-12;
						rtime=" PM";
					} else {
						rtime=" AM";
					}
					if (hour<10) hour="0"+hour;
					if (minutes<10) minutes="0"+minutes;
					rtime=((hour==00)?12:hour)+":"+minutes+rtime;
					return rtime;
	}		
</script> 
