<?php
// Set flag that this is a parent file
	define( '_FEXEC', 1 );
	
   require('includes/application_top.php');
   require(DIR_WS_CLASSES . 'currencies.php');
   include(DIR_WS_FUNCTIONS . 'events_sessions.php');
   include(DIR_WS_LANGUAGES . $language . "/" . FILENAME_CHECKOUT_ATTENDEES);
   define('BLOCKED_USER_ERROR','Blocked User');
   define('SUSPENDED_USER_ERROR','User Suspended Temporarily');
   $server_date = getServerDate(true);
   $command=isset($HTTP_GET_VARS['command'])?tep_db_prepare_input($HTTP_GET_VARS['command']):'';
   $step=isset($HTTP_GET_VARS['step'])?tep_db_prepare_input($HTTP_GET_VARS['step']):'';
   $customers_id=(isset($HTTP_POST_VARS["customers_id"])?(int)$HTTP_POST_VARS["customers_id"]:(int)$HTTP_GET_VARS["cID"]);
   $currency=DEFAULT_CURRENCY;
   $currencies=new currencies;
   $action = isset($HTTP_POST_VARS['action'])?tep_db_prepare_input($HTTP_POST_VARS['action']):'';
   if($action=='event_browse'){
   $HTTP_SESSION_VARS['param_event'] = tep_db_prepare_input($HTTP_POST_VARS['param_event']);
   $HTTP_SESSION_VARS['param_session'] = tep_db_prepare_input($HTTP_POST_VARS['param_session']);
   }
		
	//ajax start
	if($command!="")
	{
		switch($command){
			case 'show_state':
			   $zone_ids="";
			   $zone_name="";
			   $country=isset($HTTP_GET_VARS['country_id'])?(int)$HTTP_GET_VARS['country_id']:0; 
			   $zones_query = tep_db_query("select zone_id,zone_name from " . TABLE_ZONES . " where zone_country_id = '" . tep_db_input($country) . "' order by zone_name");
			   while ($zones_values = tep_db_fetch_array($zones_query)) {
				   $zone_ids.=$zones_values['zone_id'].",";
				   $zone_name.=$zones_values['zone_name'].",";
			   }
			   if(isset($HTTP_GET_VARS['cnt'])) $content= 'show_attendee_state||'.substr($zone_ids,0,-1)."^".substr($zone_name,0,-1)."^".$zone."^".tep_db_prepare_input($HTTP_GET_VARS['cnt']);
			   else  $content='show_state||'.substr($zone_ids,0,-1)."^".substr($zone_name,0,-1);    
			   echo $content; 
			   break;
		  case 'fetch_customers_details':
	  			$cnt=tep_db_prepare_input($HTTP_GET_VARS['cnt']);
				$cust_id=tep_db_prepare_input($HTTP_GET_VARS['cust_id']);
				$customer_query=tep_db_query("select c.customers_firstname,c.customers_lastname,c.customers_email_address as email_address,a.entry_postcode as postcode,a.entry_city as city,a.entry_zone_id as state,a.entry_country_id as country,a.entry_street_address as street_address,a.entry_state from ".TABLE_CUSTOMERS ." c LEFT JOIN ".TABLE_ADDRESS_BOOK." a on(c.customers_id=a.customers_id) where c.customers_id='" . tep_db_input($cust_id) . "'");
				if(tep_db_num_rows($customer_query)>0){
					$customer=tep_db_fetch_array($customer_query);
					$first_name=$customer['customers_firstname'];
					$last_name=$customer['customers_lastname'];
					$email_address=$customer['email_address'];
					$street_address=$customer['street_address'];
					$city=$customer['city'];
					$post_code=$customer['postcode'];
					$state=tep_get_zone_name($customer['country'],$customer['state'],$customer['entry_state']);
					$country=$customer['country'];
					$customer_list=$first_name."^".$last_name."^".$email_address."^".$street_address."^".$city ."^".$customer['postcode']."^".$state."^".$country;
				}
				echo 'customer_list||'.$customer_list.'##'.$cnt;
				break;
			case 'show_state_billing':
				$type=isset($HTTP_GET_VARS['type'])?tep_db_prepare_input($HTTP_GET_VARS['type']):'B';
				$country=isset($HTTP_GET_VARS['country_id'])?(int)$HTTP_GET_VARS['country_id']:0;
				$id=isset($HTTP_GET_VARS['id'])?(int)$HTTP_GET_VARS['id']:'';
				$zone_ids="";
				$zone_name="";
				$zones_query = tep_db_query("select zone_id,zone_name from " . TABLE_ZONES . " where zone_country_id = '" . tep_db_input($country) . "' order by zone_name");
				while ($zones_values = tep_db_fetch_array($zones_query)) {
					$zone_ids.=$zones_values['zone_id'].",";
					$zone_name.=$zones_values['zone_name'].",";
				}
				$content='show_state_billing||'.substr($zone_ids,0,-1)."^".tep_output_string(substr($zone_name,0,-1))."^".$zone."^".$type;    
				echo $content;	   	   	   
				break;
			case 'update_cart_details':
				break;
			case 'show_customer_details':
   				$customers_id=(int)$HTTP_GET_VARS["cID"];
				echo $command ."||";
				out_customer_details($customers_id);
				break;
			case 'update_customer':
				tep_update_customers($customers_id);
				break;
			case 'new_product':
				require(FILENAME_ADDPRODUCTS_NEW);
				break;
			case 'new_product_step2':
				$prd_id=(int)$HTTP_GET_VARS["add_product_products_id"];
				$products_query=tep_db_query("select is_attributes,products_price_break from " . TABLE_PRODUCTS . " where products_id='" . $prd_id . "'");
				$products_result=tep_db_fetch_array($products_query);
				$pattrb='{enabled:false,count:0}';
				$ppbreaks='{enabled:false}';
				if($products_result['is_attributes']=='Y')
					$pattrb=set_product_values($prd_id,false);
				if($products_result['products_price_break']	=='Y')
					$ppbreaks=tep_get_products_breaks($prd_id);
				$JS_DETAILS=array();
				echo 'new_product_step2||' .  $prd_id . '{@@}' . tep_get_products_stock($prd_id) . '{@@}' . $ppbreaks . '{@@}' . $pattrb  . '{@@}' . "{symbolLeft:'" .$currencies->currencies[$currency]['symbol_left'] . "',symbolRight:'" . $currencies->currencies[$currency]['symbol_right'] . "'}" . '||';
				out_product_details($prd_id);
				echo '||' . $JS_DETAILS["SALEMAKER_DATAS"];
				break;
			case 'new_event':
				require(FILENAME_ADDEVENTS_NEW);
				break;
			case 'new_event_step2':
				$event_id=(int)$HTTP_GET_VARS["event_id"];
				$show_period=(isset($HTTP_GET_VARS["show_period"])?true:false);
				$override=(isset($HTTP_GET_VARS["override_reserve"])?true:false);
				$overbook=(isset($HTTP_GET_VARS["overbook_reserve"])?true:false);
				$no_attendees=isset($HTTP_GET_VARS["no_attendees"])?(int)$HTTP_GET_VARS['no_attendees']:1;
				echo 'new_event_step2||';
				out_event_details($event_id,$show_period,$override,$overbook,$no_attendees);
				break;
			case 'show_attendees':
				echo 'show_attendees||';
				$no_attendees=isset($HTTP_GET_VARS["no_attendees"])?(int)$HTTP_GET_VARS['no_attendees']:1;
				out_attendees_details($no_attendees);
				break;
			case 'check_attendees':	
				$event_id=(int)$HTTP_GET_VARS["events_id"];
				$type=isset($HTTP_GET_VARS["type"])?tep_db_prepare_input($HTTP_GET_VARS['type']):0;
				$sessions=isset($HTTP_GET_VARS["session"])?tep_db_prepare_input($HTTP_GET_VARS['session']):'';
				$no_of_sessions=isset($HTTP_GET_VARS["type"])?(int)$HTTP_GET_VARS['type']:1;
				$no_attendees=isset($HTTP_GET_VARS["no_attendees"])?(int)$HTTP_GET_VARS['no_attendees']:1;				
				echo 'check_attendees||';
				check_dates($event_id,$no_attendees,$type,$sessions);
				break;
			case 'new_subscription':
				require(FILENAME_ADDSUBSCRIPTIONS_NEW);
				break;
			case 'new_subscription_step2':
				$subs_id=(int)$HTTP_GET_VARS["subscriptions_id"];
				echo 'new_subscription_step2||';
				out_subscription_details($subs_id);
				break;
			case 'new_service':
				require(FILENAME_ADDSERVICES_NEW);
				break;
			case 'new_service_step2':
				$service_id=(int)$HTTP_GET_VARS["service_id"];
				echo 'new_service_step2||';
				out_service_details($service_id);
				break;
			case 'new_service_step3':
			 	$service_id=(int)$HTTP_GET_VARS["service_id"];
				echo 'new_service_step3||';
				out_service_details_step3($service_id);
				break;
			case 'show_shipping_details':
			case 'submit_shipping_details':
				echo "checkout_shipping_details||";
				require(FILENAME_CHECKOUT_SHIPPING);
				break;
			case 'show_payment_details':
				echo "checkout_payment_details||";
				require(FILENAME_CHECKOUT_PAYMENT_NEW);
				break;

			case 'submit_payment_details':
			case 'coupon_details':
				$GLOBALS["EXECUTE_PAYMENT"]=1;
				echo "payment_confirm||";
				require(FILENAME_CHECKOUT_CONFIRM_NEW);
				break;			
			case 'show_payment_address':
			    //manual price adjustment
			    $modify_price_prefix=isset($HTTP_GET_VARS["modify_price_prefix"])?tep_db_prepare_input($HTTP_GET_VARS["modify_price_prefix"]):'';
			    $sign=isset($HTTP_GET_VARS["sign"])?tep_db_prepare_input($HTTP_GET_VARS["sign"]):'';
				$purpose=isset($HTTP_GET_VARS["purpose"])?tep_db_prepare_input($HTTP_GET_VARS["purpose"]):'';
				$manual_option=isset($HTTP_GET_VARS["manual_option"])?tep_db_prepare_input($HTTP_GET_VARS["manual_option"]):'';
				
				if($sign=='plus') {
				$sign='+'; }
				else {
				$sign='-'; 
				$modify_price_prefix=$modify_price_prefix*-1;
				}
				// setting session values for manual price adjustment
				tep_set_session_value('modify_price_prefix',$modify_price_prefix);
				tep_set_session_value('sign',$sign);
				tep_set_session_value('purpose',$purpose);
				tep_set_session_value('manual_option',$manual_option);
				echo "show_payment_address||";
				require(FILENAME_CHECKOUT_PAYMENT_ADDRESS);
				break;
			case 'submit_payment_address':
			    echo "show_payment_address||";
				require(FILENAME_CHECKOUT_PAYMENT_ADDRESS);
				break;
			case "show_shopping":
				echo "step2||";
				out_shopping_cart_details();
				break;
			case 'process_order':
				echo "process_order||";
				require(FILENAME_CHECKOUT_PROCESS_NEW);
				break;
			case 'fetch_attrib_qty':
				 $attrib = (isset($HTTP_GET_VARS['attrib'])?tep_db_prepare_input($HTTP_GET_VARS['attrib']):'');
				$value = (isset($HTTP_GET_VARS['value_array'])?tep_db_prepare_input($HTTP_GET_VARS['value_array']):'');
				$add_product_products_id = (isset($HTTP_GET_VARS['add_prd_id'])?(int)$HTTP_GET_VARS['add_prd_id']:''); 
				 $attrib_value = array();
				 $attrib_array = split(',',$attrib);
				 $value_array = split(',',$value);
				 for($icnt=0;$icnt<count($attrib_array);$icnt++){
					$attrib_value ["$attrib_array[$icnt]"] = $value_array[$icnt];
					}
				  if($aid == ""){
					$aid = array();
					if($attrib_value){
					 foreach($attrib_value as $key => $value)
						$aid[$key]= $value; 
						}
					}			
					if (is_array($aid)){
					  while (list($key, $value) = each ($aid)) {
						 $attrb.= $key."{".$value."}-";
							} 
					$rest = substr($attrb, 0, -1); 
					}
					if($rest!="")
					{
						$rest=tep_get_sorted_attribute_ids($rest);
						$out_of_stock=tep_check_attribute_stock($add_product_products_id, $rest,0);
						if($out_of_stock=="")
							$instock_quantity=tep_get_attributes_stock($add_product_products_id, $rest);
					}
					echo 'fetch_attrib_qty||' . $instock_quantity;
					break;
			case "fetch_attrib_val":
					echo "fetch_attrib_val||";
					$att_id = (isset($HTTP_GET_VARS['sel_attrib'])?tep_db_prepare_input($HTTP_GET_VARS['sel_attrib']):'');
					$prd_id = (isset($HTTP_GET_VARS['product_id'])?(int)$HTTP_GET_VARS['product_id']:'');
					$combo_name = (isset($HTTP_GET_VARS['combo_name'])?tep_db_prepare_input($HTTP_GET_VARS['combo_name']):'');
					$pre_id = (isset($HTTP_GET_VARS['previous_id'])?(int)$HTTP_GET_VARS['previous_id']:'');
					$sort_order = array();
					if($pre_id != ""){
						$chk_pre = strpos($pre_id,',');
						if($chk_pre != ""){
						$pre_id = substr($pre_id,0,-1);
						$pre_ids = split(',',$pre_id);
						}else{
						$pre_ids = array();
						$pre_ids[] = $pre_id;
						}
					}
					$p = count($pre_ids);
					if($att_id==0){
						$content = 0 .':'. '-- Select --' . '#';
						echo $content . '@' . $combo_name;
						exit;
					}
					$sort_order_query=tep_db_query("select distinct popt.products_options_id, popt.products_options_name, popt.products_options_sort_order from products_options popt, products_attributes patrib where patrib.products_id = " .(int)$prd_id ."  and patrib.options_id = popt.products_options_id and popt.language_id = 1 order by popt.products_options_sort_order");
					while($sort_orders = tep_db_fetch_array($sort_order_query)){
							$sort_order[]= $sort_orders['products_options_id'];
					}
					$m = count($sort_order);
					$count = 0;
					$products_options_query = tep_db_query("select products_options_id from products_options_values_to_products_options where products_options_values_id= " . (int)$att_id);	
					$products_option = tep_db_fetch_array($products_options_query);
					$second_attrib_query = tep_db_query("select attributes_id from products_stock where attribute_status=1 and products_id = " . (int)$prd_id);
					while($second_attrib = tep_db_fetch_array($second_attrib_query)){
						$temp=split('-',$second_attrib['attributes_id']);
						$n = count($temp);
						$temp_sort = array();
						// converting attributes list as sorted list order
						for($k=0;$k<$m;$k++){
							for($i=0;$i<$n;$i++){
								$id_pos = strpos($temp[$i],'{');
								$chk_sort = substr($temp[$i],0,$id_pos);
								if($sort_order[$k] == $chk_sort)
									   $temp_sort[] = $temp[$i];
								}
						 }		
					    if(is_array($pre_ids)){
						    for($k=0;$k<$p;$k++){
								 $split = split('{',$temp_sort[$k]);
								 $id_pos1 = strpos($split[1],'}');
								 $chk_split = substr($split[1],0,$id_pos1);
								// echo 'chk:' . $chk_split;
								 if($chk_split == $pre_ids[$k]){
									$count = $count + 1;
									if($pre_ids[$k+1])
									   continue;
									else {
									   $final_split = split('{',$temp_sort[$k+1]);
									   $id_pos2 = strpos($final_split[1],'}');
									   if($final_split[0] == $sort_order[$k+1])
									   $load_ids .= substr($final_split[1],0,$id_pos2) .',' ;
									}
									continue;
								 }else break;
						 }
					  }
					}
				$load_ids = substr($load_ids,0,-1);
				if($load_ids==""){
				 echo '@'. 'last';
				 exit;
			   }
				$load_query = tep_db_query("select distinct pov.products_options_values_id,pov.products_options_values_name,pa.options_values_price,pa.price_prefix from products_options_values pov,products_attributes pa where language_id=1 and products_options_values_id  in( " . $load_ids .") and products_id= ". (int)$prd_id ." and pov.products_options_values_id =pa.options_values_id");
				$content .= '0' .':' . '-- Select --' . '#';
					if(tep_db_num_rows($load_query)){
						while($load = tep_db_fetch_array($load_query)){
							$content .= $load['products_options_values_id'] . ':' . $load['products_options_values_name']    .'#';
						 }
					} 
			 echo $content . '@' . $combo_name;
			 break;
			 case 'check_attrib_stock':
			 	echo "check_attrib_stock||";
				$attrib_ids=isset($HTTP_GET_VARS["attrib_ids"])?tep_db_prepare_input($HTTP_GET_VARS["attrib_ids"]):'';
				$products_id=isset($HTTP_GET_VARS["products_id"])?tep_db_prepare_input($HTTP_GET_VARS["products_id"]):'';
				$quan=isset($HTTP_GET_VARS["quan"])?(int)$HTTP_GET_VARS["quan"]:1;
				if ($attrib_ids!=''){
					$temp_array=split("-",$attrib_ids);
					usort($temp_array,"ucmp");
					$attrib_ids=join("-",$temp_array);
					$stock_query=tep_db_query("SELECT attributes_id from " . TABLE_PRODUCTS_STOCK . " where attribute_status='1' and  products_id=" . tep_db_input($products_id) . " and attributes_id='" . tep_db_input($attrib_ids) . "' and products_quantity>=" . $quan);
					if (tep_db_num_rows($stock_query)>0) echo "1";
					else echo "0";
				}
				
				
				
			 break;
		} 
		tep_session_close();
		exit();
	} 
 //ajax end  
 
	if(tep_session_is_registered('order_id'))
   		tep_session_unregister('order_id');
	if(tep_session_is_registered('customer_id'))
		tep_session_unregister('customer_id');
	if(tep_session_is_registered('cart'))
		tep_session_unregister('cart'); 
		
	if(tep_session_is_registered('cartID'))
		tep_session_unregister('cartID');
		if(tep_session_is_registered('modify_price_prefix'))
		tep_session_unregister('modify_price_prefix');
		if(tep_session_is_registered('sign'))
		tep_session_unregister('sign');
		if(tep_session_is_registered('purpose'))
		tep_session_unregister('purpose');
		if(tep_session_is_registered('modify_option'))
		tep_session_unregister('modify_option');
		
		//print_r ($cart);
 
 	if(!isset($HTTP_GET_VARS['payment_error_flag']))
	{ 
      //tep_session_unregister('cart');	
     // tep_session_unregister('customer_id');
	  //tep_session_unregister('order_id');
	 }
	  if(isset($HTTP_GET_VARS['oID']))
	  {
	  	tep_session_register('order_id');
		$order_id=(int)$HTTP_GET_VARS['oID'];
		$sql_query=tep_db_query("select customers_id,payment_method,orders_status from " . TABLE_ORDERS . " where orders_id='" . (int)$order_id . "'");	
		if(tep_db_num_rows($sql_query)>0)
		{
			$row=tep_db_fetch_array($sql_query);
			$customers_id=$row['customers_id'];
			tep_session_register('order_status');
			$order_status=(int)$row['orders_status'];
			tep_session_register('cart');
		    $cart = new shoppingCart;
			$cart->load_products($order_id);
		}
	  }
	   else
	  {
  			tep_session_register('order_status');
			$order_status=1;
	  }	  
	tep_get_last_access_file();            
                                                                                       // #### Get Available Customers
	require(DIR_WS_LANGUAGES . $language . '/' . FILENAME_CREATE_ORDER_PROCESS);
	?>	

	<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN">
	<html <?php echo HTML_PARAMS; ?>>
	<head>
	<meta http-equiv="Content-Type" content="text/html; charset=<?php echo CHARSET; ?>">
<?php
	// BOF: WebMakers.com Changed: Header Tag Controller v1.0
	// Replaced by header_tags.php
	if ( file_exists(DIR_WS_INCLUDES . 'header_tags.php') ) {
		require(DIR_WS_INCLUDES . 'header_tags.php');
	} else {
?>   
	<title>Create Order</title>
	<style>
	.checkoutBarCurrent { font-family: Verdana, Arial, sans-serif; font-size: 10px; color: #000000; }
	.checkoutBarFrom, .checkoutBarTo { font-family: Verdana, Arial, sans-serif; font-size: 10px; color: #8c8c8c; }
	</style>
	<link rel="stylesheet" type="text/css" href="includes/stylesheet.css">
	<?php require('includes/form_check.js.php'); ?>
	<?php include('includes/date_format_js.php');?>
	</head>
	<body onResize="resize()" marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF"  class=" yui-skin-sam">
	<!-- header //-->
	<?php  require(DIR_WS_INCLUDES . 'header.php');	?>
	<!-- header_eof //-->
	<table  border="0" width="100%" cellspacing="2" cellpadding="1">
	<tr>
	<!-- body_text //-->
	<td  valign="top" width="100%">
		<table border="0" width="100%" cellspacing="0" cellpadding="0">
<script language="javascript" src="includes/http.js"></script>
<script language="javascript" src="includes/menu.js"></script>
<script language="javascript" src="includes/general.js"></script>
<script language="javascript" src="includes/date-picker.js"></script>
<script language="javascript">
		var sessions=Array();
		var selectedCount='<?php echo $sessions_count;?>';
		var fees_reserve=<?php echo tep_add_tax($events_result["events_fees"],$tax_rate);?>;
		var fees_vip=<?php echo tep_add_tax($events_result["waitfee_vip"],$tax_rate);?>;
		var fees_firstcome=<?php echo tep_add_tax($events_result["waitfee_firstcome"],$tax_rate);?>;
		var fees_custom=<?php echo tep_add_tax($events_result["waitfee_custom"],$tax_rate);?>;
		var nb_dates=Array();	
		var products=new Object();	
		var ppbvalues='';
		var pIntervalId;
		var max_attendees=0;
		var shop_price;
		//var shop_updated_price;
	function do_result(result){ 
		var icnt;
		cmds_splt=result.split("{}");
		for (icnt=0;icnt<(cmds_splt.length);icnt++){
			cmd_splt=cmds_splt[icnt].split("||");
			switch(cmd_splt[0]){
				case "show_state":
					result=cmd_splt[1];
					var textArr=new Array();
					var valueArr=new Array();
					splt=result.split("^");
					valueArr=splt[1].split(",");		
					textArr=splt[1].split(",");
					sel_zone=splt[2];
					var sel=document.getElementById("state");
					if(valueArr.length==1) {
						document.getElementById("state1").style.display="";
						sel.style.display="none";
					}else {
						document.getElementById("state1").value="";
						document.getElementById("state1").style.display="none";
						sel.style.display="";
						optionElement=sel;
						// clear the previous details
						while(optionElement.options.length>0){
							optionElement.remove(optionElement.options.length - 1);
						}
						//create the new details
						for (cnt=0;cnt<textArr.length;cnt++){
						  var option = document.createElement('option');
						  option.text = textArr[cnt];
						  option.value = valueArr[cnt];
						  try {
							optionElement.add(option, null); // standards compliant; doesn't work in IE
						  }
						  catch(ex) {
							optionElement.add(option); // IE only
						  }
						}
					}
					break;
				case "show_attendee_state":
						result=cmd_splt[1];
						splt=result.split("^");
						valueArr=splt[1].split(",");		
						textArr=splt[1].split(",");
						cnt=parseInt(splt[3]);
						 var frm=document.select_session;
						 var frm_attendees=frm.elements["attendee[]"];
						if(frm_attendees){
							if(frm_attendees && frm_attendees.checked) return;
							else if(frm_attendees[cnt]  && frm_attendees[cnt].checked) return;
						} 
						if(frm.elements["first_name[]"].length>1){
							state=frm.elements["state[]"][cnt];
							state1=frm.elements["state1[]"][cnt];
						} else{
							state=frm.elements["state[]"];
							state1=frm.elements["state1[]"];
						}	
						if(valueArr.length==1) {	
							state1.style.display="";
							 state.style.display="none";
						}else {
								state1.style.display="none";
							 state.style.display="";
							optionElement=state;
							while(optionElement.options.length>0){
								optionElement.remove(optionElement.options.length - 1);
							}
							for (icnt=0;icnt<textArr.length;icnt++){
							  var option = document.createElement('option');
							  option.text = textArr[icnt];
							  option.value = valueArr[icnt];
							  try {
								optionElement.add(option, null); // standards compliant; doesn't work in IE
							  }
							  catch(ex) {
								optionElement.add(option); // IE only
							  }
							}
						}
					break;
				case "show_state_billing":
						result=cmd_splt[1];
						var textArr=new Array();
						var valueArr=new Array();
						splt=result.split("^");
						valueArr=splt[1].split(",");		
						textArr=splt[1].split(",");
						sel_zone=splt[2];
						type=splt[3];
						if(type=='B' && document.getElementById("update_billing_state")) var sel=document.getElementById("update_billing_state");
						else if(type=='D' &&  document.getElementById("update_delivery_state")) var sel=document.getElementById("update_delivery_state");
						else if(type=='C' &&  document.getElementById("update_customer_state")) var sel=document.getElementById("update_customer_state");
						if(type=='B' &&  document.getElementById("update_billing_state1")) state1=document.getElementById("update_billing_state1");
						else if(type=='D' &&  document.getElementById("update_delivery_state1")) state1=document.getElementById("update_delivery_state1");
						else if(type=='C' &&  document.getElementById("update_customer_state1")) state1=document.getElementById("update_customer_state1");
						if(valueArr.length==1) {
							if(state1) state1.style.display="";
							if(sel)	sel.style.display="none";
						}else if(valueArr.length>1){
							if(state1){
								state1.value="";
								state1.style.display="none";
							} 
							sel.style.display="";
							optionElement=sel;
							// clear the previous details
							while(optionElement.options.length>0){
								optionElement.remove(optionElement.options.length - 1);
							}
							//create the new details
							for (icnt=0;icnt<textArr.length;icnt++){
							  var option = document.createElement('option');
							  option.text = textArr[icnt];
							  option.value = valueArr[icnt];
							  try {
								optionElement.add(option, null); // standards compliant; doesn't work in IE
							  }
							  catch(ex) {
								optionElement.add(option); // IE only
							  }
						}
						if(typeof(default_zone) != "undefined")
						for(i=0;i<optionElement.options.length;i++){
							if(optionElement.options[i].value==default_zone)
								optionElement.options[i].selected = true;
						}
						if(document.getElementById("state1") && typeof(default_country) != "undefined")
						if(default_country!=document.getElementById("country"))
							document.getElementById("state1").value="";
					}
					break;
				case "attendee_error":
					result=cmd_splt[1];
					splt=result.split("^");
					for(er=0;er<splt.length;er++)
					{
						if(splt[er]!='')
						{
							error_control=document.getElementById("error_box_" + er);
							if(error_control)
							{
								error_control.innerHTML=splt[er];
								error_control.style.display="";
							}
						}
					}
					break;
				case "customer_list":
					result=cmd_splt[1];
					 res=result.split('##');
					 var val=new Array('','','','','','','','');
					 if(res[0]!='') val=res[0].split("^");
	 				if(res[1]!='') fetch_details(val,res[1]); 
					break;
				case "show_customer_details":
					//merge 
				    if((document.getElementById("img_process1") && document.getElementById("ajx_load_content_img")))	
						document.getElementById("img_process1").innerHTML=""; //merge
					document.getElementById('customer_details').innerHTML=cmd_splt[1];
					break;
				case "create_order_details":
					document.getElementById('create_order_details_show').innerHTML=cmd_splt[1];
					break;
				case "new_product":
					document.getElementById('new_product').innerHTML=cmd_splt[1];
					break;
				case "new_product_step2":
					var pvalue=cmd_splt[1];
					if(cmd_splt[2]!='') {
						pvalue=cmd_splt[2];
						var prd_splt=Array();
						prd_splt=cmd_splt[1].split('{@@}');
						ppbvalues=prd_splt;
						products={0:0};
						products={'id':prd_splt[0],'stock':prd_splt[1],'priceBreaks':prd_splt[2],'priceCalc':['getProductsPrice()','getAttributePrice(-1)'],valid:false};
						eval('products.priceBreaks=' + prd_splt[2]);
						eval('products.priceAttr=' + prd_splt[3]);
						eval('products.currency=' + prd_splt[4]);
					}
					if (cmd_splt[3]!=''){
						eval('products.saleMaker=' + cmd_splt[3]);
					}
					document.getElementById('new_product_step2').innerHTML=pvalue;
					document.getElementById('show_product_save_icon_up').style.display='';
					document.getElementById('show_product_save_icon_down').style.display='';
					setQuantity('',1);
					if(!products.priceBreaks.enabled) {
						checkStock('');
					}	
					break;
				case "new_event":
					document.getElementById('new_event').innerHTML=cmd_splt[1];
					break;
				case "new_event_step2":
					document.getElementById('new_event_step2').innerHTML=cmd_splt[1];
					if(document.getElementById('show_event_save_icon_down'))
					{
						if(cmd_splt[1].indexOf('name="sessions_id[]"')>=0 && document.select_session.no_attendees.value<=1)
						{
							document.getElementById('show_event_save_icon_up').style.display='';
							document.getElementById('show_event_save_icon_down').style.display='';
						}
					}
					if (document.getElementById("event_process_show")) document.getElementById("event_process_show").style.display="none";
					if (document.getElementById("event_process_show2"))	document.getElementById("event_process_show2").style.display='none';
					break;
				case "show_attendees":
					document.getElementById('new_event_step1').style.display='none';
					document.getElementById('new_event_step2').style.display='none';
					document.getElementById('show_attendees').innerHTML=cmd_splt[1];
					if(document.getElementById('show_event_save_icon_down')){
						document.getElementById('show_event_save_icon_up').style.display='';
						document.getElementById('show_event_save_icon_down').style.display='';
					}
					break;
				case "check_attendees":
					document.getElementById('partly_full').innerHTML=cmd_splt[1];
					if(cmd_splt[1]==""){
						command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'');?>?command=show_attendees&no_attendees=" + document.select_session.no_attendees.options[document.select_session.no_attendees.selectedIndex].value;
						do_get_command(command);	
					}
					break;
				case "new_subscription":
					document.getElementById('new_subscription').innerHTML=cmd_splt[1];
					break;
				case "new_subscription_step2":
					document.getElementById('new_subscription_step2').innerHTML=cmd_splt[1];
					document.getElementById('show_subscription_save_icon_up').style.display='';
					document.getElementById('show_subscription_save_icon_down').style.display='';
					break;
				case "new_service":
					document.getElementById('new_service').innerHTML=cmd_splt[1];
					break;
				case "new_service_step2":
					document.getElementById('new_service_step2').innerHTML=cmd_splt[1];
					document.getElementById('show_service_save_icon_up').style.display='none';
					document.getElementById('show_service_save_icon_down').style.display='none';
					break;
				case "new_service_step3":
					document.getElementById('new_service_step3').innerHTML=cmd_splt[1];
					document.getElementById('show_service_save_icon_up').style.display='';
					document.getElementById('show_service_save_icon_down').style.display='';
					on_select(0);
					break;
				case "service_error":
					document.getElementById('service_error').innerHTML='<span class="errortext">' + cmd_splt[1] + '</span>';
					break;
				case "process_order":

					if(cmd_splt[1]=="redirect_page")
						location.href=cmd_splt[2];
					else
						alert(cmd_splt[1]);				
					break;
				case "show_payment_address":
					var disable_shipping='';
					if(document.getElementById('disable_shipping') && document.getElementById('disable_shipping').checked==true)
						disable_shipping=1;
					else
						disable_shipping=0;
					
					if(document.getElementById('step4_show'))
						document.getElementById('step4_show').innerHTML=""
					if(cmd_splt[1]=="step3")
					{
						command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'');?>?command=show_shipping_details&disable_shipping=" +disable_shipping;
						do_get_command(command);	
					}
					else
					{
						document.getElementById('step3_show').innerHTML=cmd_splt[1];
						show_step_number(3);
					}
					break;
				case "step2":
				//shopping
					shop_content= cmd_splt[3];
					if(shop_content)
						shop_temp_arr=shop_content.split('#');
					for(h=0;h<shop_temp_arr.length;h++)
					{
						temp_arr=shop_temp_arr[h].split('^');
						switch(temp_arr[0])
						{
						//	case 'updated_amount':
							//	shop_updated_price=temp_arr[1];
							//	break;
							case 'net_total':
								shop_price=temp_arr[1];
								break;
						}
					}
					//alert(shop_price);
					//alert(shop_updated_price);
					document.getElementById('step2_show').innerHTML=cmd_splt[1];
					if(cmd_splt[2]!='undefined') 
						max_attendees=cmd_splt[2];
						
					show_step_number(2);
					break;
				case "checkout_shipping_details":
					if(cmd_splt[1]=="redirect_page")
					{
						location.href=cmd_splt[2];	
					}
					else if(cmd_splt[1]=="step4")
					{
						command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'command=show_payment_details');?>";
						do_get_command(command);
						document.getElementById('step4_show').innerHTML="";
					}
					else if(cmd_splt[1]=="step5")
					{
						command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'command=show_payment_details');?>";
						do_get_command(command);
					}
					else
					{						
						document.getElementById('step4_show').innerHTML=cmd_splt[1];
						show_step_number(4);
					}
					break;
				case "checkout_payment_details":
					if(cmd_splt[1]=="redirect_page")
					{
						command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'');?>?command=" + cmd_splt[2];
						do_get_command(command);	
					}else{ 
						document.getElementById('step5_show').innerHTML=cmd_splt[1];
						show_step_number(5);
						if(document.edit_order && document.edit_order.elements["payment"]){
							var pay_selection=document.edit_order.elements["payment"];
							var sel_payment=false;
							for(i=0;i<pay_selection.length;i++){
								if(!sel_payment && pay_selection[i].checked) {									
									if(document.getElementById("defaultSelected")) selectRowEffect2(document.getElementById("defaultSelected"),i,pay_selection[i].value);
									else if(document.getElementById("defaultunSelected")) selectRowEffect2(document.getElementById("defaultunSelected"),i,pay_selection[i].value);									
									sel_payment=true;									
								}
							}
						}
					}
					break;
				case "payment_confirm":
					if(cmd_splt[1]=="redirect_page")
					{
						command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'');?>?command=" + cmd_splt[2];
						do_get_command(command);	
					}
					else if(cmd_splt[1]=="payment_error")
					{  
					
						document.getElementById("button_confirm5").src="<?php echo DIR_WS_LANGUAGES . $language . '/images/buttons/button_continue.gif';?>";
						if(document.getElementById("img_process5"))document.getElementById("img_process5").innerHTML="";
						document.getElementById('show_payment_error').style.display="";
						document.getElementById('payment_error_text').innerHTML=cmd_splt[2];
						document.getElementById('payment_error_text').style.display='';
						if(document.getElementById("credit_result")) document.getElementById("credit_result").style.display='none';
					}
					else if(cmd_splt[1]=="coupon_details")
					{  
						document.getElementById("credit_result").style.display="";
						document.getElementById("credit_result").innerHTML=cmd_splt[2];
						if(document.getElementById('payment_error_text')){
						 document.getElementById('payment_error_text').style.display="none";
						 document.getElementById('show_payment_error').style.display="none";
						 document.getElementById('credit').style.display="none";
						 }
					}
					else
					{ 
						//document.getElementById('step4_show').style.display="";
						document.getElementById('step6_show').innerHTML=cmd_splt[1];
						show_step_number(6);
					}
					break;
				case "fetch_attrib_qty":
					if(validateproductquantity(cmd_splt[1]))
					{
						do_page_fetch("product_submit");
					}
					break;
				case "selectedCount":
					selectedCount =cmd_splt[1]; 
					break;
				case "fees_reserve":
					fees_reserve =cmd_splt[1]; 
					break;
				case "fees_vip":
					fees_vip =cmd_splt[1]; 
					break;
				case "fees_firstcome":
					fees_firstcome =cmd_splt[1]; 
					break;
				case "fees_custom":
					fees_custom =cmd_splt[1]; 
					break;
				case "call_functions" :
					add_start_times();
					add_end_times();
					break;
				case "max_bookings" : 
					max_bookings =parseInt(cmd_splt[1]);					
					break;
				case "time_length" : 
					time_length=parseInt(cmd_splt[1]); 
					break;
				case "book_type" :
					book_type =cmd_splt[1]; 
					break;
				case "book_granular" :
					book_granular =parseInt(cmd_splt[1]); 
					break;
				case "service_quantity":
					service_quantity =parseInt(cmd_splt[1]); 
					break;
				case "span_days" :
					span_days=cmd_splt[1];					
					break;
				case "cur_hour" :
					cur_hour =cmd_splt[1]; 
					break;
				case "cur_date" :
					cur_date =cmd_splt[1]; 
					break;
				case "include_attributes":
					include_attributes=cmd_splt[1];
					break;
				case "include_resource" :
					include_resource =cmd_splt[1]; 
					if(include_resource!='Y' && include_attributes!="true")
					{
						document.getElementById('show_service_save_icon_up').style.display='';
						document.getElementById('show_service_save_icon_down').style.display='';
						document.getElementById('show_select_step3').style.display='none';
					}
					break;
				case "multiple_purchase" : 
					multiple_purchase =cmd_splt[1]; 
					break;
				case "st_time" :
					st_time =cmd_splt[1]; 
					break;
				case "et_time" :
					et_time =cmd_splt[1]; 
					break;
				case "book_buffer":
					book_buffer =cmd_splt[1]; 
					break;
	    		case "book_buffer_minute":
					book_buffer_minute =cmd_splt[1]; 
					break;
				case "nb_dates":
					temp=cmd_splt[1];
					temp_arr=temp.split('?');
					for (cnt=0;cnt<temp_arr.length-1;cnt++)
						nb_dates[cnt]=temp_arr[cnt];
					break;
				case "attributes_array":
					temp=cmd_splt[1];
					temp_arr=temp.split('?');
					for (cnt=0;cnt<temp_arr.length-1;cnt++)
						attribute_array[cnt]=temp_arr[cnt];
					break;
				case "error":
				  if(cmd_splt[1]!=""){
				    document.getElementById('show_service_save_icon_up').style.display='none';
					document.getElementById('show_service_save_icon_down').style.display='none';
				  }
				break;   	
				case "dates_array":
					temp=cmd_splt[1];
					temp_arr=temp.split('^');
					//Ticket#: 2008070321000026
					sessions=Array();
					for (cnt=0;cnt<temp_arr.length-1;cnt++) { 
						temp_arr2=temp_arr[cnt].split('?');
						sessions[cnt]=Array();
						sessions[cnt][0]=temp_arr2[0];
						sessions[cnt][1]=temp_arr2[1];
						sessions[cnt][2]=temp_arr2[2];
						sessions[cnt][3]=temp_arr2[3];
					}	
					break;
				case "fetch_attrib_val":
					result=cmd_splt[1];
					valueArr = Array();
					textArr= Array();
					dtextArr = Array();
					dvalueArr = Array();
					combo = result.split('@');
					if(combo[1]!='last'){
						combo_spt = combo[1].split('[');
						combo_cnt = parseInt(combo_spt[1].substring(combo_spt[1],1,1));
						var frm = document.getElementById('add_products_options');
						temp=result.split('#');
							for(i=0;i<temp.length-1;i++){
									content=temp[i];
									temp2=content.split(':');
									textArr[i]=temp2[1];
									valueArr[i]=temp2[0];
								}
							cnt=0;
							for(j=0;j<attrib.length;j++){
								if(attrib[j]==combo_cnt)
								cnt=j+1;
							}
							add_options(textArr,valueArr,document.getElementById("add_products_options["+attrib[cnt]+"]"));
						
						for(k=cnt+1;k<attrib.length;k++){
							dtextArr[0] = "-- Select --";
							dvalueArr[0] = 0;
							add_options(dtextArr,dvalueArr,document.getElementById("add_products_options["+attrib[k]+"]"));
						}
						 
						if(document.getElementById("add_products_options["+attrib[cnt]+"]").value==0){
							dtextArr[0] = "-- Select --";
							dvalueArr[0] = 0;
							for(j=cnt+1;j<attrib.length;j++){
								add_options(dtextArr,dvalueArr,document.getElementById("add_products_options["+attrib[j]+"]"));	
							}
						}
						if(temp[1].substring(temp[1],1,1)=='@'){
							for(j=2;j<attrib.length;j++)
								add_options(textArr,valueArr,document.getElementById("add_products_options["+attrib[j]+"]"));
						}
					}
					break;
					case 'check_attrib_stock':
						if (cmd_splt[1]=="1") toggleOutStock(true);
						else toggleOutStock(false);
						toggleLoadMsgs("stockProductQuan",1);
						toggleLoadMsgs("stockAttrQuan",1);
					break;
					default :
					break;
				 }
			}
	}
	
	function shipping_status(){
		if(document.getElementById('shipping_estimator_id')){
		if(document.getElementById('disable_shipping').checked==true)
			document.getElementById('shipping_estimator_id').style.display='none';
		else
			document.getElementById('shipping_estimator_id').style.display='';
		}
			
	}
	
	function show_step_number(id)
	{
		if(id==4)  //shipping
		{
			if(document.getElementById('step4_show') && document.getElementById('step4_show').innerHTML=="")
				return;
		}
		if(document.getElementById('step' + id + '_show') && document.getElementById('step' + id + '_show').innerHTML=="")
		{
			switch(id)
			{
				case 1:
					break;
				case 2:
					command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'command=show_shopping');?>";
					alert (command);
					do_get_command(command);	
					break;
			}
			return;
		}
		for(i=1;i<=6;i++)
		{
			if(document.getElementById('step' + i + '_show'))
		    	document.getElementById('step' + i + '_show').style.display="none";
		}
		document.getElementById('step' + id + '_show').style.display="";
		if(id!=6)
		{
		   if(document.getElementById("button_confirm" + id)) document.getElementById("button_confirm" + id).src="<?php echo DIR_WS_LANGUAGES . $language . '/images/buttons/button_continue.gif';?>";
			if(document.getElementById("img_process" + id))document.getElementById("img_process" + id).innerHTML="";
		}
	}
function update_cart(){
		command = "command=update_cart_details";
		command +="&" + get_cart_details("cart_quantity_p","product");
		command +="&" +get_cart_details("cart_quantity_e","event");
		command +="&" +get_cart_details("cart_quantity_s","subscription");
		command +="&" +get_cart_details("cart_quantity_v","service");
		do_get_command(command);
	}
function get_cart_details(formname,caption)
{
	var command=caption + "=";
	if(document.forms[formname]){
		var frm=document.forms[formname];
		if(frm.elements['cart_delete[]'])
		{
			obj=frm.elements['cart_delete[]'];
			qty=frm.elements['cart_quantity[]'];
			id=frm.elements['product_id[]'];
			txtname=frm.elements['txt_name[]'];
			txttax=frm.elements['txt_tax[]'];
			txtprice=frm.elements['txt_price[]'];
			command += "#$#S#!#";
			if(obj[0])
			{
				for(var i=0;i<obj.length;i++)
				{
					if(id[i].value!='')command += id[i].value + "#@#" + qty[i].value + "#@#" + txtname[i].value + "#@#" + txttax[i].value +  "#@#" + txtprice[i].value +"#!#";
				}
			}
			else
			{
				if(id.value!='')command += id.value + "#@#" + qty.value + "#@#" + txtname.value + "#@#" + txttax.value +  "#@#" + txtprice.value +"#!#";
			}
		}
	}
	return(command);
}

	function do_page_fetch(cmd)
	{
		switch(cmd)
		{
			case "update_customer":
				if(check_form())
				{
					command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'command=update_customer');?>";
					do_post_command("customers",command); 	
				}
				break;
			case "new_product":
				if(document.getElementById("new_product"))
					document.getElementById("new_product").style.display="";
				//merge	
				if(document.getElementById('product_edit'))document.getElementById('product_edit').style.display = 'none';
				if(document.getElementById('event_edit'))document.getElementById('event_edit').style.display = '';
				if(document.getElementById('subscription_edit'))document.getElementById('subscription_edit').style.display = '';
				if(document.getElementById('service_edit'))document.getElementById('service_edit').style.display = '';
				//merge
				if(document.getElementById("new_product") && document.getElementById("ajx_load_content_img"))
					document.getElementById("new_product").innerHTML=document.getElementById("ajx_load_content_img").innerHTML;
				command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'command=new_product');?>";
				do_get_command(command);	
				if(document.getElementById('new_event'))document.getElementById('new_event').style.display = 'none';
				if(document.getElementById('new_subscription'))document.getElementById('new_subscription').style.display = 'none';
				if(document.getElementById('new_service'))document.getElementById('new_service').style.display = 'none';
				break;
			case "new_product_step2":
				add_product_products_id=document.new_product.add_product_products_id.value;
				command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'');?>?command=new_product_step2&add_product_products_id=" + add_product_products_id;
				do_get_command(command);	
				break;
			case "product_submit":
				products={0:0};
				if(document.getElementById("product_submit"))
				document.getElementById("product_submit").innerHTML=document.getElementById("ajx_load_content_img").innerHTML;
				command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'product_action=add_product&command=show_shopping');?>";
				do_post_command("new_product",command);	
				break;
			case "update_cart":
				command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'product_action=update_product&command=show_shopping');?>";
				do_post_command("cart_quantity_p",command);	
				break;
			case "new_event":
				if(document.getElementById("new_event"))
					document.getElementById("new_event").style.display="";
				//merge	
				if(document.getElementById('product_edit'))document.getElementById('product_edit').style.display = '';
				if(document.getElementById('event_edit'))document.getElementById('event_edit').style.display = 'none';
				if(document.getElementById('subscription_edit'))document.getElementById('subscription_edit').style.display = '';
				if(document.getElementById('service_edit'))document.getElementById('service_edit').style.display = '';
				//merge
				if(document.getElementById("new_event") && document.getElementById("ajx_load_content_img"))
					document.getElementById("new_event").innerHTML=document.getElementById("ajx_load_content_img").innerHTML;
				command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'command=new_event');?>";
				do_get_command(command);	
				if(document.getElementById('new_product'))document.getElementById('new_product').style.display = 'none';
				if(document.getElementById('new_subscription'))document.getElementById('new_subscription').style.display = 'none';
				if(document.getElementById('new_service'))document.getElementById('new_service').style.display = 'none';
				break;
			case "new_event_step2":
				event_id=document.select_session.events_name.value;
				param='&';
				if(document.select_session.overbook_reserve)
					if(document.select_session.overbook_reserve.checked)
						param+="overbook_reserve=1&"
				if(document.select_session.override_reserve)
					if(document.select_session.override_reserve.checked)
						param+="override_reserve=1&"
				
				if (document.getElementById("event_process_show")) document.getElementById("event_process_show").style.display='';
				command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'');?>?command=new_event_step2&event_id=" + event_id +param;
				do_get_command(command);	
				break;
			case "new_event_step3":
				event_id=document.select_session.events_name.value;
				if(document.select_session.no_attendees){
					var sel_attendees=document.select_session.no_attendees.value;
					if(max_attendees>0 && ((max_attendees<sel_attendees) || (max_attendees>sel_attendees)) ) {
					   alert("Cart already has an event with " + max_attendees + " attendees. Number of Attendees for this event must be equal to " +  max_attendees);
					   return;
					 }  
				}
				param='&';
				if(document.select_session.overbook_reserve)
					if(document.select_session.overbook_reserve.checked)
						param+="overbook_reserve=1&"
				if(document.select_session.override_reserve)
					if(document.select_session.override_reserve.checked)
						param+="override_reserve=1&"
				
				if (document.getElementById("event_process_show2"))	document.getElementById("event_process_show2").style.display='';
				param+="show_period=1&no_attendees=" + document.select_session.no_attendees.value +'&';
				command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'');?>?command=new_event_step2&event_id=" + event_id +param;
				//alert(command);
				do_get_command(command);	
				break;
			case "show_attendees":
				var frm =document.select_session;
				var att=frm.elements["sessions_id[]"];
				var events_id = frm.events_id.value;
				var type = frm.session_type.value;
				var sessions_ids = '';
				
				for(icnt=0;icnt<att.length;icnt++){ 
					if(att[icnt].checked){
						sessions_ids += att[icnt].value + ',';
						//alert(att[icnt].value);
					}
				}//alert(frm.session_type.value + 'ID:' +frm.events_id.value);
				//if(sessions_ids!='') sessions_ids = sessions_ids.substr(0,-1);				
				if(frm.no_attendees.options[document.select_session.no_attendees.selectedIndex].value>1){
					command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'');?>?command=check_attendees&no_attendees=" + frm.no_attendees.options[document.select_session.no_attendees.selectedIndex].value + '&events_id=' +events_id +'&type='+type+'&session='+sessions_ids;
					do_get_command(command);
				}
				if(validateeventForm(document.forms['select_session']))
				{
					
					//command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'');?>?command=show_attendees&no_attendees=" + document.select_session.no_attendees.options[document.select_session.no_attendees.selectedIndex].value;
					//do_get_command(command);	
				}
				break;
			case "event_submit":
				if(validateeventForm(document.forms['select_session']))
				{
					submitform=true;
					if(document.select_session.no_attendees.value>1)
						if(check_attendee_form('select_session'))
							submitform=true;
						else
							submitform=false;
					if(submitform)
					{
					if (document.getElementById("event_process_show3")) {
						document.getElementById("event_process_show3").style.display='';
					}
					command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'event_action=buy_product&command=show_shopping');?>";
					do_post_command("select_session",command);
					}
				}
				break;
			case "new_subscription":
				if(document.getElementById("new_subscription"))	
					document.getElementById("new_subscription").style.display="";
				//merge	
				if(document.getElementById('product_edit'))document.getElementById('product_edit').style.display = '';
				if(document.getElementById('event_edit'))document.getElementById('event_edit').style.display = '';
				if(document.getElementById('subscription_edit'))document.getElementById('subscription_edit').style.display = 'none';
				if(document.getElementById('service_edit'))document.getElementById('service_edit').style.display = '';
				//merge
				if(document.getElementById("new_subscription") && document.getElementById("ajx_load_content_img"))	
					document.getElementById("new_subscription").innerHTML=document.getElementById("ajx_load_content_img").innerHTML;
				command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'command=new_subscription');?>";
				do_get_command(command);	
				if(document.getElementById('new_product'))document.getElementById('new_product').style.display = 'none';
				if(document.getElementById('new_event'))document.getElementById('new_event').style.display = 'none';
				if(document.getElementById('new_service'))document.getElementById('new_service').style.display = 'none';
				break;
			case "new_subscription_step2":
				subscriptions_id=document.add_new_subscription.subscriptions_id.value;
				command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'');?>?command=new_subscription_step2&subscriptions_id=" + subscriptions_id;
				do_get_command(command);	
				break;
			case "subscription_submit":
				 	if(document.getElementById("subscription_submit"))
							document.getElementById("subscription_submit").innerHTML=document.getElementById("ajx_load_content_img").innerHTML;
				command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'subs_action=add_subscription&command=show_shopping');?>";
				do_post_command("add_new_subscription",command);	
				break;
			case "new_service":
				document.getElementById("new_service").style.display="";
				//merge
				if(document.getElementById('product_edit'))document.getElementById('product_edit').style.display = '';
				if(document.getElementById('event_edit'))document.getElementById('event_edit').style.display = '';
				if(document.getElementById('subscription_edit'))document.getElementById('subscription_edit').style.display = '';
				if(document.getElementById('service_edit'))document.getElementById('service_edit').style.display = 'none';
				//merge
				if(document.getElementById("new_service") && document.getElementById("ajx_load_content_img")) document.getElementById("new_service").innerHTML=document.getElementById("ajx_load_content_img").innerHTML;
				command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'command=new_service');?>";
				do_get_command(command);	
				if(document.getElementById('new_product'))document.getElementById('new_product').style.display = 'none';
				if(document.getElementById('new_event'))document.getElementById('new_event').style.display = 'none';
				if(document.getElementById('new_subscription'))document.getElementById('new_subscription').style.display = 'none';
				break;
			case "new_service_step2":
				service_id=document.select_resource.service_name.value;
				command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'');?>?command=new_service_step2&service_id=" + service_id;
				do_get_command(command);	
				break;
			case "new_service_step3":
				service_id=document.select_resource.service_name.value;
				command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'');?>?command=new_service_step3&service_id=" + service_id;
				do_post_command("select_resource",command);	
				break;
			case "service_submit":
				if(ValidateserviceForm())
				{
				  
				  	if(document.getElementById("service_submit"))
							document.getElementById("service_submit").innerHTML=document.getElementById("ajx_load_content_img").innerHTML;
					service_id=document.select_resource.service_name.value;
					command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'service_action=buy_service&command=show_shopping');?>&service_id=" + service_id;
					do_post_command("select_resource",command);	
				}
				break;
			case "show_payment_address":
			    var disable_shipping=0;
				var pp_result="";

				
				//manual price adjustment start
				var manual_option;
				if(document.getElementById('modify_price_prefix')) var modify_price_prefix=document.getElementById("modify_price_prefix").value;
				if(document.getElementById('sign')) var sign=document.getElementById("sign").value;
				if(document.getElementById('purpose')) var purpose=document.getElementById("purpose").value;
				//if(document.getElementById('manual_priceadjust_option')) manual_option=document.getElementById("manual_priceadjust_option").value;
				if(document.getElementById('manual_priceadjust_option').checked==true){
						manual_option='Y';
						if (purpose=="")
       					  pp_result="Enter the Purpose";
     					else if (modify_price_prefix=="")
       					  pp_result="Enter the Price Adjustment";
						}
						else {
						manual_option='N';
						}
	
				if(sign=='+') 
				{sign='plus';}
				else {sign='minus';}
				
				
				
				
				if(document.getElementById('disable_shipping') && document.getElementById('disable_shipping').checked==true)
					disable_shipping=1;
				else
					disable_shipping=0;
				if(!document.getElementById('disable_shipping')) disable_shipping=1;
				if(document.getElementById("button_confirm2"))
					document.getElementById("button_confirm2").src="<?php echo DIR_WS_LANGUAGES . $language . '/images/buttons/button_process.gif';?>";
				if(document.getElementById("img_process2") && document.getElementById("ajx_load_content_img"))
					document.getElementById("img_process2").innerHTML=document.getElementById("ajx_load_content_img").innerHTML;
				
				
				 if (pp_result!=""){
        		 alert(pp_result); 
				 }else{
				command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'');?>?command=show_payment_address&disable_shipping="+disable_shipping+"&modify_price_prefix="+modify_price_prefix+"&sign="+sign+"&purpose="+purpose+"&manual_option="+manual_option;
				do_get_command(command);
				
				}
				
				break;	
			case "submit_payment_address":
				if(document.getElementById('update_billing_name').value==''){
				alert('Customer Name is required');
				}else{
				if(document.getElementById("button_confirm3"))
					document.getElementById("button_confirm3").src="<?php echo DIR_WS_LANGUAGES . $language . '/images/buttons/button_process.gif';?>";
				if(document.getElementById("img_process3") && document.getElementById("ajx_load_content_img"))
					document.getElementById("img_process3").innerHTML=document.getElementById("ajx_load_content_img").innerHTML;
				command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'command=submit_payment_address&action=update_address');?>";
				do_post_command("payment_address",command);	
				}
				break;
			case "show_shipping_details":
				document.getElementById("button_confirm3").src="<?php echo DIR_WS_LANGUAGES . $language . '/images/buttons/button_process.gif';?>";
				if(document.getElementById("img_process3").innerHTML=document.getElementById("ajx_load_content_img"))
					document.getElementById("img_process3").innerHTML=document.getElementById("ajx_load_content_img").innerHTML;
				command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'');?>?command=show_shipping_details";
				do_get_command(command);	
				break;
			case 'submit_shipping_details1':
				if(document.getElementById("button_confirm3"))
					document.getElementById("button_confirm3").src="<?php echo DIR_WS_LANGUAGES . $language . '/images/buttons/button_process.gif';?>";
				if(document.getElementById("img_process3") && document.getElementById("ajx_load_content_img"))
					document.getElementById("img_process3").innerHTML=document.getElementById("ajx_load_content_img").innerHTML;
					//do_get_command("<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'command=submit_shipping_details&disable_shipping=1'); ?>");
					command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'command=show_payment_details');?>";
					do_get_command(command);
				break;
			case "submit_shipping_details":
				/*document.getElementById("button_confirm4").src="<?php echo DIR_WS_LANGUAGES . $language . '/images/buttons/button_process.gif';?>";
				if(document.getElementById("img_process4").innerHTML=document.getElementById("ajx_load_content_img"))*/
				document.getElementById("img_process4").innerHTML=document.getElementById("ajx_load_content_img").innerHTML;
				command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'command=submit_shipping_details');?>";
				do_post_command("checkout_shipping",command);					
				break;
			case "submit_payment_details":
				document.getElementById('show_payment_error').style.display="none";
				document.getElementById("button_confirm5").src="<?php echo DIR_WS_LANGUAGES . $language . '/images/buttons/button_process.gif';?>";
				if(document.getElementById("img_process5").innerHTML=document.getElementById("ajx_load_content_img"))
				document.getElementById("img_process5").innerHTML=document.getElementById("ajx_load_content_img").innerHTML;
				command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'command=submit_payment_details');?>";
				do_post_command("edit_order",command);	
				break;
			case "process_order":
		
				if(document.checkout_confirmation){
					if(document.getElementById('confirm_button')) document.getElementById('confirm_button').style.display="none";
				document.checkout_confirmation.submit();
				}
				else{
					location.href="<?php echo tep_href_link(FILENAME_CHECKOUT_PROCESS_NEW);?>";	
				}
				break;			
			case "ajx_close_product_new":
				document.getElementById('new_product').style.display="none";
				if(document.getElementById('product_edit'))document.getElementById('product_edit').style.display = ''; //merge
				break;
			case "ajx_close_subscription_new":
				document.getElementById('new_subscription').style.display="none";
				if(document.getElementById('subscription_edit'))document.getElementById('subscription_edit').style.display = ''; //merge
				break;	
			case "ajx_close_event_new":
				if(document.getElementById('event_edit'))document.getElementById('event_edit').style.display = ''; //merge
				document.getElementById('new_event').style.display="none";
				break;
			case "ajx_close_service_new":
				if(document.getElementById('service_edit'))document.getElementById('service_edit').style.display = ''; //merge
				document.getElementById('new_service').style.display="none";
				break;
			case "product_delete":
				do_delete_action("cart_quantity_p",'P');
				break;
			case "event_delete":
				do_delete_action("cart_quantity_e",'E');
				break;
			case "subscription_delete":
				do_delete_action("cart_quantity_s",'S');
				break;
			case "service_delete":
				do_delete_action("cart_quantity_v",'V');
				break;
		}
	}
	function refund_amount(){
	location.href="<?php echo tep_href_link(FILENAME_CHECKOUT_PROCESS_NEW,'refund_flag=1');?>";	
	}
function do_delete_action(frmname,type)
{
	<?php //if($order_status==1){ ?>
		var frm=document.forms[frmname];
		var select_box=frm.elements["cart_delete[]"];
		sflag=0;
		if (select_box[0]){
			for (icnt=0;icnt<select_box.length;icnt++){
				if (select_box[icnt].checked){
					sflag=1;
					 break;
				}
			}
		} else {
			if (select_box.checked){
				sflag=1;
			}
		}
		if (sflag==0){
			alert("<?php echo ERR_SELECT_DELETE;?>");
			return;
		}
		command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'');?>?command=show_shopping&event_action=update_cart&type=" + type;
		do_post_command(frmname,command);
		<?php //}else{ ?>
		//alert("<?php echo ERR_PROCESSING_DELETE;?>");
	<?php //} ?>	
	
	
}
</script> 

<script language="JavaScript">
	function selectEventItem(boxname,id,index){
		var element=document.getElementById(boxname+id);
		var field=document.select_session.elements[boxname+"_index"];
		field.value=index;
		field=document.select_session.elements[boxname];
		if (field.value!=''){
			document.getElementById(boxname+field.value).style.backgroundColor="#FFFFFF";
		}
		field.value=id;
		element.style.backgroundColor="#D8EDFB";
	}
	function selectSessionItem(boxname,id,index){
		var element=document.getElementById(boxname+id);
		var session_type=document.select_session.session_type.value;
		var bgcolor="#FFFFFF";
		var pindex=0;
		var index_field;

		field=document.select_session.elements[boxname+"_index"];
		if (field.value!="") pindex=parseInt(field.value);
		field.value=index;
		if (session_type!="S")
			field=document.select_session.elements[boxname+"_field"];
		else
			field=document.select_session.elements[boxname+"[]"];
		
		if (field.value!=''){
			if (sessions[pindex][3]==0) bgcolor="#F5F5F5";
			document.getElementById(boxname+field.value).style.backgroundColor=bgcolor;

		}
		element.style.backgroundColor="#D8EDFB";
		field.value=id;
	}
	function setElementPos(){
		var boxnames=Array("events_name","sessions_id");
		var ids=Array("<?php echo $events_id;?>","<?php echo $sessions_id;?>");
		var box;
		var element;
		for (icnt=0;icnt<boxnames.length;icnt++){
			box=document.getElementById(boxnames[icnt]+"_box");
			element=document.getElementById(boxnames[icnt]+ids[icnt]);
			if (box!=null && element!=null)
				box.scrollTop=element.offsetTop;
		}
	}
	
	function sel_attendees(){
	  var val="<?php echo sizeof($edit_cart->attendees);?>";
	  var no_atten=document.select_session.no_attendees.value;
	  if(val>0){
	   if(val!=no_atten){
	    alert("Already has an event with " + val + " attendees." + " " + "Number of Attendees for this event must be equal to" + " " + no_atten );
		return false;
	   }else {
	    return true;
	   }
	  }else { 
	   return true;
	  }
	}
</script>
<script>
	function selectServiceItem(boxname,id,index){
		var element=document.getElementById(boxname+id);
		var field=document.select_resource.elements[boxname+"_index"];
		field.value=index;
		field=document.select_resource.elements[boxname];
		if (field.value!=''){
			document.getElementById(boxname+field.value).style.backgroundColor="#FFFFFF";
		}
		field.value=id;
		element.style.backgroundColor="#D8EDFB";
	}
	
	function setElementPos(){
		var boxnames=Array("service_name","service_date","start_time_hours","end_time_hours");
		var ids=Array("<?php echo $service_id;?>","<?php echo $start_date;?>","<?php echo $start_time;?>","<?php echo $end_time;?>");
		var box;
		var element;
	
		for (icnt=0;icnt<boxnames.length;icnt++){
			box=document.getElementById(boxnames[icnt]+"_box");
			element=document.getElementById(boxnames[icnt]+ids[icnt]);
			if (box!=null && element!=null)
				box.scrollTop=element.offsetTop;
		}
	}

	function rowOverEffect(object) {	
	 	if (object.className == 'RowEven') object.className = 'RowOdd';
	}

	function rowOutEffect(object) {
	  	if (object.className == 'RowOdd') object.className = 'RowEven';
	}
	function on_select(cou){
	   if(document.select_resource){
	  	var frm=document.select_resource.elements["resource[]"];
		var resource_id="";
		if(frm){ 
		 if(frm.length){
			frm[0].checked=true;
			frm[cou].checked=true;
			for(i=0;i<frm.length;i++){
			 if(frm[i].checked){ 
			  resource_split=frm[i].value.split('#');
			  resource=resource_split[0].split('-');
			  st_time_string=resource_split[1];
			  et_time_string=resource_split[2];
			  start_date=getDatePart(st_time_string,'D');
			  start_time=getDatePart(st_time_string,'H');
			  end_date=getDatePart(et_time_string,'D');
			  end_time=getDatePart(et_time_string,'H');
			  end_times=et_time_string;
			  resource_id=resource[0];
			  costs=resource[1];
			 }
		   } 
		 }else { 
		 	frm.checked=true;
		 	if(frm.checked) {
		 		resource_split=frm.value.split('#');
			    resource=resource_split[0].split('-');
		 	}
			resource_id=resource[0];
			st_time_string=resource_split[1]; 
			et_time_string=resource_split[2]; 	
			start_date=getDatePart(st_time_string,'D');
			start_time=getDatePart(st_time_string,'H');
			end_date=getDatePart(et_time_string,'D');
			end_time=getDatePart(et_time_string,'H');
			end_times=et_time_string;
			costs=resource[1];
		 } 
		 document.select_resource.resource_ids.value=resource_id;
		 document.select_resource.resource_costs.value=costs;
		/* if(document.select_resource.start_date)
		 {
		 		 document.select_resource.start_date.value=start_date;
		 		 document.select_resource.start_time.value=start_time;
		}
		else if(document.select_resource.start_times)
		{
   		  document.select_resource.start_times.value=st_time_string;
		} */
		 document.select_resource.end_times.value=end_times;
		 //alert(end_times + " " + end_date + " " +end_time);
		 formatdate=dateAdd('n',1,end_times,true);
		 if(document.getElementById("div_dates")) document.getElementById("div_dates").innerHTML="<span class=smalltext><?php echo '<b>'.TEXT_START_DATE.'</b>&nbsp;';?>"+date_format(start_date,'Y-m-d','<?php echo EVENTS_DATE_FORMAT;?>')+" "+convert_to_stime(start_time)+"<?php echo '&nbsp;  &nbsp;&nbsp;&nbsp;<b>'.TEXT_END_DATE.'</b>&nbsp;';?>"+date_format(getDatePart(formatdate,'D'),'Y-m-d','<?php echo EVENTS_DATE_FORMAT;?>')+" "+convert_to_stime(getDatePart(formatdate,'H'))+"</span>";
		}
	  }
	}
	
</script>
<!--Step1 script-->
		<script language="javascript"> 
	function update_values(oid,products_id,attributes_id,ths,str_update){
		command="<?php echo tep_href_link(FILENAME_EDIT_ORDERS);?>?command="+str_update+"&orders_id="+oid+"&orders_products_id="+products_id+"&attributes_id="+attributes_id+ths;
 		setTimeout('do_get_command(command)',2000); 		 		 		
 		clearTimeout();	
 	} 	
   function validateaddressForm(){
      var error_result="";
      var select_payment=0;
      if (document.edit_order.update_billing_name.value=="")
         error_result="<?php echo tep_db_input(ERR_BILLING . ERR_NAME); ?>";
      else if (document.edit_order.update_billing_street_address.value=="")
         error_result="<?php echo tep_db_input(ERR_BILLING . ERR_ADDRESS); ?>";
      else if (document.edit_order.update_billing_city.value=="")
         error_result="<?php echo tep_db_input(ERR_BILLING . ERR_CITY); ?>";
      else if ((document.edit_order.update_billing_state.style.display!='none' && document.edit_order.update_billing_state.value=="")||(document.edit_order.update_billing_state1.style.display!='none' && document.edit_order.update_billing_state1.value==""))
         error_result="<?php echo tep_db_input(ERR_BILLING . ERR_STATE); ?>";
      else if (document.edit_order.update_billing_postcode && document.edit_order.update_billing_postcode.value=="")
         error_result="<?php echo tep_db_input(ERR_BILLING . ERR_POSTCODE); ?>";
      else if (document.edit_order.update_billing_country.value=="")
         error_result="<?php echo tep_db_input(ERR_BILLING . ERR_COUNTRY); ?>";
     if (error_result==""){
      if (document.edit_order.update_delivery_name.value=="")
         error_result="<?php echo tep_db_input(ERR_DELIVERY . ERR_NAME); ?>";
      else if (document.edit_order.update_delivery_street_address.value=="")
         error_result="<?php echo tep_db_input(ERR_DELIVERY . ERR_ADDRESS); ?>";
      else if (document.edit_order.update_delivery_city.value=="")
         error_result="<?php echo tep_db_input(ERR_DELIVERY . ERR_CITY); ?>";
      else if ((document.edit_order.update_delivery_state.style.display!='none' && document.edit_order.update_delivery_state.value=="")|| (document.edit_order.update_delivery_state1.style.display!='none' && document.edit_order.update_delivery_state1.value==""))
         error_result="<?php echo tep_db_input(ERR_DELIVERY . ERR_STATE); ?>";
      else if (document.edit_order.update_delivery_postcode.value=="")
         error_result="<?php echo tep_db_input(ERR_DELIVERY . ERR_POSTCODE); ?>";
      else if (document.edit_order.update_delivery_country.value=="")
         error_result="<?php echo tep_db_input(ERR_DELIVERY . ERR_COUNTRY); ?>";
      else if (document.edit_order.update_customer_telephone.value=="")
         error_result="<?php echo tep_db_input(ERR_TELEPHONE_NUMBER); ?>";
      else if (document.edit_order.update_customer_email_address.value.indexOf("@")==-1 || document.edit_order.update_customer_email_address.value.indexOf(".")==-1)
         error_result="<?php echo tep_db_input(ERR_EMAIL_ADDRESS); ?>";
      else if (document.edit_order.update_customer_second_email_address.value!="" && (document.edit_order.update_customer_second_email_address.value.indexOf("@")==-1 || document.edit_order.update_customer_second_email_address.value.indexOf(".")==-1))
     		error_result="<?php echo tep_db_input(ENTRY_SECOND_EMAIL_ADDRESS_CHECK_ERROR); ?>";	
     }
      if (error_result!=""){
         alert(error_result); 
	 	 return false;
	 }
      return true;
   }


	function showComment(obj)
	{
		if(obj.checked)
			document.all.show_comments.style.display="";
		else
			document.all.show_comments.style.display="none";
	}
	function submitFunction()
	{ 
		command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'command=coupon_details&do_action=get_counpon_details');?>";
		do_post_command('edit_order',command);
	}
	function hide_credit(mode){  
		if(mode==1)document.edit_order.coupon.checked=false;
		document.getElementById("credit").style.display="none";
		if(document.edit_order.coupon.checked==true){
			document.getElementById("credit").style.display="";
		}else{
			document.edit_order.gv_redeem_code.value="";
			document.getElementById("credit_result").style.display="none";
		}
	}
		function setpayment(pid)
		{
			document.edit_order.payment.value=pid;
		}
		function show_state(zone){
		document.getElementById("state1").style.display="none";
		document.getElementById("state").style.display="";
		var this_=document.getElementById("country");
		id=this_.options[this_.selectedIndex].value;
		if(id){
			command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'command=show_state');?>&country_id="+id;
			do_get_command(command);	
		}
	}
	function show_state_billing(do_this){ 
		var this_=do_this;
		id=this_.options[this_.selectedIndex].value;
		type=(this_.name.indexOf('billing')>0)?'B':((this_.name.indexOf('customer')>0)?'C':'D');
		if(id){
			command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'command=show_state_billing');?>&country_id="+id+"&type="+type;
			do_get_command(command);
			if(do_this.name.indexOf('billing')>0) document.getElementById("update_billing_state").innerHTML="Loading...";
			else if(do_this.name.indexOf('delivery')>0) document.getElementById("update_delivery_state").innerHTML="Loading...";
		}else{
			if(do_this.name.indexOf('billing')>0) document.getElementById("update_billing_state").innerHTML="Loading...";
			else if(do_this.name.indexOf('delivery')>0) document.getElementById("update_delivery_state").innerHTML="Loading...";
		}
	}

		 var submitProcessFlag=false;
		 function check_form() {
		  var error = 0;
		  var error_message = "<?php echo JS_ERROR; ?>";
		  var customers_firstname = document.customers.firstname.value;
		  var customers_lastname = document.customers.lastname.value;
		<?php //if (ACCOUNT_COMPANY == 'true') echo 'var entry_company = document.customers.company.value;' . "\n"; ?>
		  var customers_email_address = document.customers.email_address.value;
		  var customers_confirm_email_address = customers_email_address; //document.customers.confirm_email_address.value;
		<?php //if (ACCOUNT_SECOND_PHONE == 'true') echo 'var customers_second_telephone = document.customers.second_telephone.value;' . "\n"; ?>
		<?php //if (ACCOUNT_SECOND_EMAIL == 'true') echo 'var customers_second_email_address =  document.customers.second_email_address.value;' . "\n"; ?>
		 if(document.customers.second_email_address) var customers_second_email_address =  document.customers.second_email_address.value;
		 if(document.customers.second_telephone) var customers_second_telephone = document.customers.second_telephone.value;
		 if(document.customers.company)  var entry_company = document.customers.company.value;
		  if(customers_second_email_address!='')
		  	customers_second_confirm_email_address=customers_second_email_address; //document.customers.second_confirm_email_address.value;
		  	
		  var entry_street_address = document.customers.street_address.value;
		  var entry_postcode = document.customers.postcode.value;
		  var entry_city = document.customers.city.value;
		  var customers_telephone = document.customers.telephone.value;
		
		  if (document.customers.customers_id.value=="") {
			alert("<?php echo JS_SELECT_CUSTOMER; ?>");
			return false;
		  }
		  if (customers_firstname == "" || customers_firstname.length < <?php echo ENTRY_FIRST_NAME_MIN_LENGTH; ?>) {
			error_message = error_message + "<?php echo JS_FIRST_NAME; ?>";
			error = 1;
		  }
		  if (customers_lastname == "" || customers_lastname.length < <?php echo ENTRY_LAST_NAME_MIN_LENGTH; ?>) {
			error_message = error_message + "<?php echo JS_LAST_NAME; ?>";
			error = 1;
		  }
		  if (customers_email_address == "" || customers_email_address.length < <?php echo ENTRY_EMAIL_ADDRESS_MIN_LENGTH; ?>) {
			error_message = error_message + "<?php echo JS_EMAIL_ADDRESS; ?>";
			error = 1;
		  }
		  if (customers_email_address!=customers_confirm_email_address) {
				error_message = error_message + "<?php echo JS_EMAIL_CONFIRM_ADDRESS; ?>";
				error = 1;
		  }
		  if(customers_second_email_address!=''){
		  	if (customers_second_email_address!=customers_second_confirm_email_address){
				error_message = error_message + "<?php echo JS_SECONDEMAIL_CONFIRM_ADDRESS; ?>";
				error = 1;
		  	}else if(customers_email_address==customers_second_email_address){
		  		error_message = error_message + "<?php echo JS_SECOND_EMAIL_ADDRESS_UNIQUE; ?>";
				error = 1;
		  	}
		  }
		  if (entry_street_address == "" || entry_street_address.length < <?php echo ENTRY_STREET_ADDRESS_MIN_LENGTH; ?>) {
			error_message = error_message + "<?php echo JS_ADDRESS; ?>";
			error = 1;
		  }
		  if (entry_postcode == "" || entry_postcode.length < <?php echo ENTRY_POSTCODE_MIN_LENGTH; ?>) {
			error_message = error_message + "<?php echo JS_POST_CODE; ?>";
			error = 1;
		  }
		  if (entry_city == "" || entry_city.length < <?php echo ENTRY_CITY_MIN_LENGTH; ?>) {
			error_message = error_message + "<?php echo JS_CITY; ?>";
			error = 1;
		  }
		<?php
		  if (ACCOUNT_STATE == 'true') {
		?>
		  if (document.customers.elements['state'].style.display != "none") {

			if (document.customers.state.value == '' || document.customers.state.value.length < <?php echo ENTRY_STATE_MIN_LENGTH; ?> ) {
			   error_message = error_message + "<?php echo JS_STATE; ?>";
			   error = 1;
			}
		  }else if (document.customers.elements['state1'].style.display != "none") {
			if (document.customers.state1.value == '' || document.customers.state1.value.length < <?php echo ENTRY_STATE_MIN_LENGTH; ?> ) {
			   error_message = error_message + "<?php echo JS_STATE; ?>";
			   error = 1;
			}
		  }
		<?php
		  }
		?>
		  if (document.customers.elements['country'].type != "hidden") {
			if (document.customers.country.value == 0) {
			  error_message = error_message + "<?php echo JS_COUNTRY; ?>";
			  error = 1;
			}
		  }
		  if (customers_telephone == "" || customers_telephone.length < <?php echo ENTRY_TELEPHONE_MIN_LENGTH; ?>) {
			error_message = error_message + "<?php echo JS_TELEPHONE; ?>";
			error = 1;
		  }
		  if (document.customers.elements['mobile'].type != "hidden") {
			if (check_phone(document.customers.elements['mobile'].value)==false) {
			  error_message = error_message + "<?php echo JS_MOBILE; ?>";
			  error = 1;
			}
		  }
		  //if (submitProcessFlag){ 
				//alert("<?php echo addslashes(TEXT_FORM_SUBMITTED);?>");
				//return;
			//}
		  submitProcessFlag=true;
		  if (error == 1) {
			alert(error_message);
			submitProcessFlag=false;
			return false;
		  } else {
		  if(document.getElementById("button_confirm1"))
		    document.getElementById("button_confirm1").src="<?php echo DIR_WS_LANGUAGES . $language . '/images/buttons/button_process.gif';?>";
		  if((document.getElementById("img_process1") && document.getElementById("ajx_load_content_img")))	
			document.getElementById("img_process1").innerHTML=document.getElementById("ajx_load_content_img").innerHTML;
		    submitProcessFlag=true;
			return true;
		  }
		}
		
		function check_phone(value){
		var rc = new RegExp("[~`!@#$%^&*_=|\/><,?;:+-]","i")
		var rn = new RegExp("[A-Z]","i");
		var res;
			if (value=="") return true;
			res= rn.exec(value);
			if (isNaN(res))
				return false;
			else
			{
				res=rc.exec(value);
				if (res!=null) 
					return false;
			}
			return true;
		}
//--></script>
<!---step1_script_end-->
<!--Step2 script-->
<!---step2_script_end-->
<!--add product script-->
<script language="javascript">
var attrib=new Array();
 function load_stock(att_name,prd_id,cnt){
		att_id =att_name.value;
		combo_name = att_name.name;
		temp=document.new_product.attribute_val.value;
		attrib=temp.split('^');
		var pre_ids ="";
			  for(i=0;i<=cnt;i++){
			   	pre_id = document.getElementById("add_products_options[" + attrib[i] + "]").options[document.getElementById("add_products_options[" + attrib[i] + "]").selectedIndex].value;
			 	pre_ids+=pre_id+",";
			 }
			command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW);?>?command=fetch_attrib_val&sel_attrib="+att_id+"&product_id="+prd_id+"&combo_name="+combo_name+"&previous_id="+pre_ids+"&cnt="+cnt;
		do_get_command(command);
}
function  validateproductForm(){
	 var value_array = new Array();
	 var chk = 1;
	 prd_quantity = 0;
	 var error='';
	if (products.priceAttr.enabled){
		for(icnt=0,n=products.priceAttr.count;icnt<n;icnt++){
			if(document.getElementById("attrValues["+icnt+"]").selectedIndex<=0){
				error+="* <?php echo ERR_SELECT_ATTRIBUTES;?>";
				break;
			}
		}
	}
	
	if(document.getElementById('qty') && (isNaN(parseInt(document.getElementById('qty').value))) || parseInt(document.getElementById('qty').value) <= 0){
		error+="* <?php echo ERR_TEXT_QUANTITY;?>";
	}
	
	if (error!=""){
		alert(error);
		return;
	} 
	if (!products.valid) return;
	products={0:0};
	document.getElementById("save").style.display="none";
	document.getElementById("save1").style.display="none";
	do_page_fetch("product_submit");
}
function validateproductquantity(prd_quantity){
   var chk = 1;
   if (document.new_product.qty.value > parseInt(prd_quantity) ) {
	 alert ('Error : Product Quantity Out of Stock');
	 return false;
   }
   return true;	
} 


</script>
<script language="javascript">    
	function validate_subscription_form(){
		var error="";
		if(document.add_new_subscription.currend_date){
		var currend_date = document.add_new_subscription.currend_date.value;
		var start_date = document.add_new_subscription.start_date.value;
		var finish_date = document.add_new_subscription.finish_date.value;
		var latest_start_date = document.add_new_subscription.latest_start_date.value;
		
		var subscription_type = document.add_new_subscription.subscription_type.value;
		var subscription_period = document.add_new_subscription.subscription_period.value;
		var subscription_date_type = document.add_new_subscription.subscription_date_type.value;
		var deliveries_perday = document.add_new_subscription.deliveries_perday.value;
		var deliveries_perday_date = document.add_new_subscription.deliveries_perday_date.value;
		
		var display_start_date = document.add_new_subscription.display_start_date.value;
		var display_finish_date = document.add_new_subscription.display_finish_date.value;
		var display_latest_start_date = document.add_new_subscription.display_latest_start_date.value;
		var your_start_date = document.add_new_subscription.your_start_date.value;
		
		
		var your_start_date_count = '';
		if(your_start_date!=""){
			var date_error = true;
			if((your_start_date).indexOf("-")!=-1){
				date_error = isValidDate(date_format(your_start_date,'','Y-m-d'));
			} else {
				date_error = false;
			}
			if(!(date_error)){
				alert("* <?php echo ERR_START_DATE;?>");
				return;
			} else {
				your_start_date_count = date_format(your_start_date,'','',true).getTime();
			}
		}
		var start_date_count = 0;
		var finish_date_count = 0;
		var latest_start_date_count = 0;
		var deliveries_perday_date_count = 0;
		var currend_date_count = date_format(currend_date,'','',true).getTime();
		if(your_start_date_count=="")your_start_date_count = date_format(currend_date,'','',true).getTime();
		if(display_start_date!=0)start_date_count = date_format(start_date,'Y-m-d','',true).getTime();
		if(display_finish_date!=0){
			finish_date_count = date_format(finish_date,'Y-m-d','',true).getTime();
			deliveries_perday_date_count = date_format(deliveries_perday_date,'','',true).getTime();
		}
		if(display_latest_start_date!=0)latest_start_date_count = date_format(latest_start_date,'Y-m-d','',true).getTime();
		if(subscription_date_type == 'F' && subscription_type != 'C'){
			if(currend_date_count >= start_date_count){
				error = "<?php echo addslashes(TEXT_ERR_SUBSCRIBE_FIXED_NON_CASUAL);?>";
			}
		} else if(subscription_date_type == 'F' && subscription_type == 'C'){
			if(currend_date_count >= deliveries_perday_date_count){
				error = "<?php echo addslashes(TEXT_ERR_SUBSCRIBE_FIXED_CASUAL);?>";
			}
		} else if(subscription_date_type == 'L' && subscription_type != 'C'){
			if(currend_date_count >= latest_start_date_count){
				error = "<?php echo addslashes(TEXT_ERR_SUBSCRIBE_FLEXIBLE_NON_CASUAL);?>";
			}
		} else if(subscription_date_type == 'L' && subscription_type == 'C'){
			if(currend_date_count >= deliveries_perday_date_count){
				error = "<?php echo addslashes(TEXT_ERR_SUBSCRIBE_FLEXIBLE_CASUAL);?>";
			}
		} else if(subscription_date_type == 'P' && subscription_type != 'C'){
			if(your_start_date_count < start_date_count){
				error = "<?php echo addslashes(TEXT_ERR_SUBSCRIBE_PREDEFINED_START);?>";
			} else if(your_start_date_count > latest_start_date_count){
				error = "<?php echo addslashes(TEXT_ERR_SUBSCRIBE_PREDEFINED_NON_CASUAL);?>";
			}
		} else if(subscription_date_type == 'P' && subscription_type == 'C'){
			if(your_start_date_count < start_date_count){
				error = "<?php echo addslashes(TEXT_ERR_SUBSCRIBE_PREDEFINED_START);?>";
			} else if(your_start_date_count > deliveries_perday_date_count){
				error = "<?php echo addslashes(TEXT_ERR_SUBSCRIBE_PREDEFINED_CASUAL);?>";
			}
		}
		if (error!=""){
			alert(error);
			return;
		}
		}
		do_page_fetch("subscription_submit");
	}
		function check_date(){
	var your_choose_date = document.add_new_subscription.your_start_date.value;
	var forward_period = document.add_new_subscription.subscription_period.value;
		if(your_choose_date!=""){
			var date_error = true;
			if((your_choose_date).indexOf("-")!=-1){
				date_error = isValidDate(date_format(your_choose_date,'','Y-m-d'));
			} else {
				date_error = false;
			}
			if(!(date_error)){
				alert("* <?php echo ERR_START_DATE;?>");
				return false;
			} else {
				var check_date = new Date();
				var split_date = document.add_new_subscription.your_start_date.value.split("-");
				check_date.setDate(split_date[0]);check_date.setMonth(split_date[1]-1);check_date.setYear(split_date[2]);
				check_date.setMinutes(0);check_date.setSeconds(0);check_date.setHours(0);check_date.setMilliseconds(0);
				var to_forward_period = 1;
				if(forward_period != 0)to_forward_period = forward_period;
				var day = DateAdd('d',to_forward_period-1,check_date).getDate();
				var month = DateAdd('d',to_forward_period-1,check_date).getMonth();
				var year = DateAdd('d',to_forward_period-1,check_date).getYear();
				month +=1;
				//day -=1;if(day!=1)
				if(year<1000)year +=1900;
				if(day<10)day = 0+""+day;
				if(month<10)month = 0+""+month;
				document.add_new_subscription.to_date.value = date_format(day+"-"+month+"-"+year,'d-m-Y','');
			}
		}
	}
	function DateAdd(timeU,byMany,dateObj) {
		var millisecond=1;
		var second=millisecond*1000;
		var minute=second*60;
		var hour=minute*60;
		var day=hour*24;
		var year=day*365;
	
		var newDate;
		var dVal=dateObj.valueOf();
		switch(timeU) {
			case "ms": newDate=new Date(dVal+millisecond*byMany); break;
			case "s": newDate=new Date(dVal+second*byMany); break;
			case "mi": newDate=new Date(dVal+minute*byMany); break;
			case "h": newDate=new Date(dVal+hour*byMany); break;
			case "d": newDate=new Date(dVal+day*byMany); break;
			case "y": newDate=new Date(dVal+year*byMany); break;
		}
		return newDate;
	}

</script>
<!---event------->
<script language="JavaScript">
		var choiceAmount1;
		var choiceAmount2;
		var choiceDays1;
		var choiceDays2;
		var selectedSession=0;
		var validIndexes=Array();
		var auto_select=false;

		function displayCurrency(num){
			var commaDelimiter="<?php echo (DEFAULT_CURRENCY!=''?$currencies->currencies[DEFAULT_CURRENCY]['thousands_point']:',');?>";
			var symbolLeft="<?php echo (DEFAULT_CURRENCY!=''?$currencies->currencies[DEFAULT_CURRENCY]['symbol_left']:'$');?>";
			var symbolRight="<?php echo (DEFAULT_CURRENCY!=''?$currencies->currencies[DEFAULT_CURRENCY]['symbol_right']:',');?>";
			var output=FormatNumber(new String(num),2,commaDelimiter,".");
			return symbolLeft+output+symbolRight;
		}
		function displaySessionsCountFixed(sIndex){
			var row=document.getElementById("sessions_count_row");
			var select_count=parseInt(document.select_session.select_count.value);
			var select_interval=parseInt(document.select_session.select_interval.value);
			var session_style=document.select_session.session_style.value;
			//var session_type=document.select_session.session_type.value;
			var amount_r=0;
			var amount_w=0;
			var total_fee_r=0;
			var total_fee_w=0;
			var total_days_r=0;
			var total_days_w=0;
			var total_days=0;
			var option;
			//var choice=document.select_session.sessions_count;
			var currentIndex=1;
			var waitlist_amount=0;
			var event_type="";
			//clearChoice(choice);
			if (select_interval==0) select_interval=1;
		
			choiceDays1[choiceDays1.length]=total_days_r;
			choiceDays2[choiceDays2.length]=total_days_w;
			choiceAmount1[choiceAmount1.length]=total_fee_r;
			choiceAmount2[choiceAmount2.length]=total_fee_w;
			//choice.options[choice.options.length]=new Option("",0);
			for (icnt=sIndex;icnt<sessions.length;icnt++){
				amount_r=0;
				amount_w=0;
				if (sessions[icnt][1]=="R" || sessions[icnt][1]=="W") {
					if (sessions[icnt][1]=="R"){//reserve user
						amount_r=sessions[icnt][2];
						amount_w=0;
						total_days_r+=1;
					} else if (sessions[icnt][1]=="W") {
						amount_w=0;
						amount_r=0;
						if (session_style=='S' || event_type==''){
							amount_w=fees_vip;
							event_type='W';
						} else {
							amount_w=0;
						}
						total_days_w+=1;
					}
					total_fee_r+=amount_r;
					total_fee_w+=amount_w;
					if (currentIndex % select_interval==0){
						choiceDays1[choiceDays1.length]=total_days_r;
						choiceDays2[choiceDays2.length]=total_days_w;
						choiceAmount1[choiceAmount1.length]=total_fee_r;
						choiceAmount2[choiceAmount2.length]=total_fee_w;
						if (choiceAmount1.length>=select_count) break;
					}
					currentIndex+=1;
				}
			}
			total_days=total_days_r+total_days_w;
			if (total_days<select_interval && choiceAmount1.length==0){
				//choice.options[choice.options.length]=new Option(total_days+"<?php echo TEXT_FOR;?>"+displayCurrency(total_fee_r+total_fee_w),select_interval);
				choice.options[choice.options.length]=new Option(total_days,select_interval);
				if (selectedCount==select_interval)
					choice.options[choice.options.length-1].selected=true;
			}
			for (icnt=1;icnt<choiceAmount1.length;icnt++){
				currentIndex=choiceDays1[icnt]+choiceDays2[icnt];
				//choice.options[choice.options.length]=new Option(currentIndex+"<?php echo TEXT_FOR;?>"+displayCurrency(choiceAmount1[icnt]+choiceAmount2[icnt]),currentIndex);
				choice.options[choice.options.length]=new Option(currentIndex,currentIndex);
				if (selectedCount==currentIndex)
					choice.options[choice.options.length-1].selected=true;
		
			}
			if (!row) return;
			row.style.display="block";
			calculateSelectedDate(1);
		}
		function calculateSelectedDate(selectMode){
			var icnt=0;
			var jcnt=0;
			var checkbox_field;
			var event_type="";
			var amount_r=0;
			var amount_w=0;
			var total_fee_r=0;
			var total_fee_w=0;
			var total_days_r=0;
			var total_days_w=0;
			var total_fee=0;
			var total_days=0;
			var sIndex=0;
			var eIndex=sessions.length-1;
			//var length_field=document.select_session.sessions_count;
			var select_interval=parseInt(document.select_session.select_interval.value);
			var session_style=document.select_session.session_style.value;
			var session_type=document.select_session.session_type.value;
			var reserve_type=document.select_session.reserve_type.value;
			var length_index=0;
			var length_remind=0;
			var cnt=0;
			var slotNo=0;
			var checkFlag;
			var prevIndex=0;
			var session_map=Array();
			var current_interval=0;
			document.getElementById("amount_notify_r").style.visibility="hidden";
			document.getElementById("amount_notify_w").style.visibility="hidden";
			document.getElementById("amount_notify_t").style.visibility="hidden";
			if (session_type=='S') return;
			checkbox_field=document.select_session.elements['sessions_id[]'];
			if (sessions.length==1){
				if (checkbox_field.checked) {
					if (sessions[0][1]=="R") {
						$total_fee_r=sessions[icnt][2];
						total_days_r=1;
					} else if (sessions[0][1]=="W")  {
						$total_fee_w=fees_vip;
						total_days_w=1;
					}
				}
			}
			// session length is more than one
			if (sessions.length>1){
				reserve_type="R";
				//set the session map amount
				if (session_style!=''){
					jcnt=0;
					for (icnt=0;icnt<sessions.length;icnt++){
						if (checkbox_field[icnt].checked && sessions[icnt][1]!='E') {
							if (sessions[icnt][1]=="W") reserve_type="W";
							jcnt++;
							if (jcnt%select_interval==0) {
								session_map[current_interval]=reserve_type;
								current_interval++;
								reserve_type='R';
							}
						}
					}
					if (jcnt%select_interval!=0){
						session_map[current_interval]=reserve_type;
					}
				}
				cnt=0;
				current_interval=0;
				reserve_type="";
				for (icnt=sIndex;icnt<=eIndex;icnt++){
					amount_r=0;
					amount_w=0;
					if (checkbox_field[icnt] && sessions[icnt][1]!='E' && checkbox_field[icnt].checked) {
						if (session_style!='E'){
							if (sessions[icnt][1]=="R"){
								amount_r=sessions[icnt][2];
								total_days_r+=1;
							} else if (sessions[icnt][1]=="W") {
								amount_w=fees_vip;
								total_days_w+=1;
							}
						} else {
							if (session_map[current_interval]=='R'){
								amount_r=sessions[icnt][2];
								total_days_r+=1;
							} else {
								if (reserve_type=="") {
									amount_w=fees_vip;
									reserve_type="W";
								}
								total_days_w+=1;
							}
						}
						cnt++;
						if (session_style!=""){
							if (cnt%select_interval==0) {
								reserve_type="";
								current_interval++;
							}
						}
						total_fee_r+=parseFloat(amount_r);
						total_fee_w+=parseFloat(amount_w);
					}
				}
			}
			//alert(total_fee_r);
			total_days=total_days_r+total_days_w;
			if (total_fee_r>0){
				document.getElementById("amount_notify_r").innerHTML="<?php echo RESERVE_FEE;?>"+displayCurrency(total_fee_r)+" ("+total_days_r+" <?php echo TEXT_DAYS;?>"+")";
				document.getElementById("amount_notify_r").style.visibility="visible";
			}
			if (total_fee_w>0) {
				document.getElementById("amount_notify_w").innerHTML="<?php echo WAITLIST_FEE;?>"+displayCurrency(total_fee_w)+" ("+total_days_w+" <?php echo TEXT_DAYS;?>"+")";
				document.getElementById("amount_notify_w").style.visibility="visible";
			}
			total_fee=total_fee_r+total_fee_w;
			total_days=total_days_r+total_days_w;
			if (total_fee>0) {
				document.getElementById("amount_notify_t").innerHTML="<?php echo TOTAL_FEE;?>"+displayCurrency(total_fee)+" ("+total_days+" <?php echo TEXT_DAYS;?>"+")";
				document.getElementById("amount_notify_t").style.visibility="visible";
			}
			document.getElementById("no_sessions").innerHTML=total_days;
		}
		function selectValidDates(index){
			//alert(document.select_session.session_reduction.value);
			var select_interval=parseInt(document.select_session.select_interval.value);
			var session_style=document.select_session.session_style.value;
			var session_type=document.select_session.session_type.value;
			var session_gaps=document.select_session.session_gaps.value;
			var session_reduction=document.select_session.session_reduction.value;
			if(document.getElementById('interval')){
				if(document.getElementById('interval').innerHTML != select_interval) select_interval = parseInt(document.getElementById('interval').innerHTML);
			}
			var validIndexs=0;
			var validIndexe=0;
			var no_reserve=0;
			var no_waitlist=0;
			var checkbox_field;
			var selectSlotType=""; // check type category the selected group falls full reserve,waitlist,mixed;
			var error="";
			var no_sessions=0;
			var reserve_type="";
			var selection_mode='fixed' // 'fixed'=>fixed selection. 'reserve'=>select only reservation if possible if not change to fixed reservation
			// if single session or sessions.lengh <2 or  index is invalid exit
			
			//alert(select_interval);
			
			checkbox_field=document.select_session.elements['sessions_id[]'];
			if (session_type=='S' || sessions.length<2 || index<0 || index>=sessions.length){
				calculateSelectedDate(0);
				return;
			}
			// if auto select just select the sessions and exit
			if (auto_select){
				auto_select=false;
				if (sessions.length>1) checkbox_field[index].checked=true;
				else checkbox_field.checked=true;
			}
			//if select _interval is less than 2 exit
			if (select_interval<2 || sessions.length<2){
				calculateSelectedDate(0);
			} 
			// checkbox is being selected or unselected
			checkFlag=checkbox_field[index].checked;
			if (checkFlag){
				validIndexs=index;
				checkbox_field[index].checked=false;
				reserve_type='R';
				selectSlotType="";
				// if sessions gaps is allowed and selected is reserved just change selection mode reserve
				if (session_gaps=='Y' && sessions[index][1]=="R") selection_mode='reserve';
				// iterate first by taking "reserve mode" and then work for fixed
				for (var kcnt=1;kcnt<=2;kcnt++){
					jcnt=0;
					// if selected box is reserved
					if (selection_mode=='reserve'){
						// iterate upto the sessions count & automatically checke the sessions upto select "interval" count or until a session is selected
						for (icnt=index;icnt<sessions.length;icnt++){
							if (checkbox_field[icnt].checked) break;
							validIndexe=icnt;
							if (sessions[icnt][1]=='R') {
								jcnt++;
								if (jcnt>=select_interval) break;
							}
						}
					} else { // if selected is waitlist
						// iterate and select "interval" no of sessions if valid
						for (icnt=index;icnt<sessions.length;icnt++){
						
							if (checkbox_field[icnt].checked) break;
							// mark the slot type to waitlist or mixed or reserved
							if (sessions[icnt][1]!='E'){
								if (sessions[icnt][1]=='W' && selectSlotType!="W"){
									if (selectSlotType=="") selectSlotType="W";
									else selectSlotType="M";
								}
								if (sessions[icnt][1]=='R' && selectSlotType!="R"){
									if (selectSlotType=="") selectSlotType="R";
									else selectSlotType="M";
								}
							}
							// if there is a empty in slot and session_gaps is not allowed pop the error message
							if (sessions[icnt][1]=='E' && session_gaps!='Y'){
								error="<?php echo addslashes(stripslashes(ERR_SESSION_GAPS));?>";
								break;
							} 
							// store the last index 
							validIndexe=icnt;
							if (sessions[icnt][1]!='E') {
								jcnt++;
								if (jcnt>=select_interval) break;
							}
						}
					}
					// if selection mode is reserve and "no sessions" exceeds just exit
					if (selection_mode=="reserve"){
						if (jcnt>=select_interval) {
							selectSlotType="R";
							break;
						}
						selection_mode="fixed";
					}
				}
				// if selection mode is fixed and no sessions is less than expected interval and "session reduction" is off just error
				if (error=="" && selection_mode=="fixed"){ 
					if (jcnt<select_interval && sessions.length>select_interval && session_reduction!='Y'){
						error="<?php echo addslashes(stripslashes(ERR_SESSION_REDUCTIONS));?>";
					}
				}
				if (error!=""){
					alert(error);
					return;
				}
				// check above selected session to find any waitlist is present and slottype is other than waitlist
				for (icnt=0;icnt<validIndexs;icnt++){
					if (checkbox_field[icnt].checked){
						if (sessions[icnt][1]=='W' && selectSlotType!='W') {
							error="<?php echo addslashes(stripslashes(ERR_SESSION_WAITLIST_ABOVE));?>";
							break;
						}
					}
				}
				if (error!=""){
					alert(error);
					return;
				}
				jcnt=0;
				reserve_type='R';
				for (icnt=validIndexe+1;icnt<sessions.length;icnt++){
					if (checkbox_field[icnt].checked && sessions[icnt][1]!='E'){
						if (sessions[icnt][1]=='W') reserve_type='W';
						jcnt++;
						if (jcnt%select_interval==0){
							if (reserve_type=='R' && selectSlotType!='R') {
								error="<?php echo addslashes(stripslashes(ERR_SESSION_RESERVE_BELOW));?>";
								break;
							}
							reserve_type="R";
						}
					}
				}
				if (jcnt%select_interval!=0){
					if (reserve_type=='R' && selectSlotType!='R') {
						error="<?php echo addslashes(stripslashes(ERR_SESSION_RESERVE_BELOW));?>";
					}
				}
				if (error!=""){
					alert(error);
					return;
				}
				// if there is no error select the possible session dates
				for (icnt=validIndexs;icnt<=validIndexe;icnt++){
					if (sessions[icnt][1]!='E') {
						if ((selection_mode=="reserve" && sessions[icnt][1]=='R') || selection_mode!="reserve")
						checkbox_field[icnt].checked=true;
					}
				}
				if (session_reduction!='Y')
					validIndexes[validIndexes.length]=validIndexs+","+validIndexe;
			} else if (session_reduction!='Y') {
				var tempStr="";
				var delIndex=-1;
				for (icnt=0;icnt<validIndexes.length;icnt++){
					tempStr=validIndexes[icnt].split(",");
					validIndexs=parseInt(tempStr[0]);
					validIndexe=parseInt(tempStr[1]);
					if (index>=validIndexs && index<=validIndexe){
						validIndexes[icnt]="";
						delIndex=icnt;
						break;
					}
				}
				if (delIndex>=0) {
					for (icnt=validIndexs;icnt<=validIndexe;icnt++){
						if (sessions[icnt][1]!='E') {
							checkbox_field[icnt].checked=false;
						}
					}
					deleteStoredIndex(delIndex);
				}
			}
			calculateSelectedDate(0);
		}
		function deleteStoredIndex(delIndex){
			if (delIndex<0 || delIndex>=validIndexes.length) return;
			for (var jcnt=delIndex; jcnt<validIndexes.length-1; jcnt++)
				validIndexes[jcnt] = validIndexes[jcnt+1];
			validIndexes.length = validIndexes.length-1;
		}
		function clearChoice(choice){
			if (choice.options==null) return;
			while(choice.options.length>0){
				choice.options[0]=null;
			}
			choice.selectedIndex=-1;
			choiceAmount1=Array();
			choiceAmount2=Array();
			choiceDays1=Array();
			choiceDays2=Array();
		}
		function validateeventForm(frm){
			var error="";
			var icnt=0;
			var check_field=frm.elements["sessions_id[]"];
			var session_type=frm.session_type.value;
			var session_style=frm.session_style.value;
			var session_gaps=frm.session_gaps.value;
			var session_reduction=frm.session_reduction.value;
			if (session_type=='S') return true;
			
			if (sessions.length>1){ 
				error="<?php echo addslashes(stripslashes(ERR_SELECT_SESSION_DATE));?>";
				for (icnt=0;icnt<check_field.length;icnt++){ 
					if (check_field[icnt].checked) { 
						error="";
						break;
					}
				}
			} else {
				if (check_field.checked==false){
					error="<?php echo addslashes(stripslashes(ERR_SELECT_SESSION_DATE));?>";
				}
			}
			if (error=="" && frm.question_type){
				if (frm.question_type.value=="D"){
					if (isDate(frm.question_month.value+"/"+frm.question_day.value+"/"+frm.question_year.value)==false){
						error="<?php echo addslashes(stripslashes($question_result_error));?>";
					} else {
						frm.question_value_data.value=frm.question_year.value + "-" + frm.question_month.value + "-" + frm.question_day.value;
					}
				} else if (frm.question_type.value=="T" && frm.question_value_data.value==""){
						error="<?php echo addslashes(stripslashes($question_result_error));?>";
				} else if (frm.question_type.value=="N" && isNaN(parseInt(frm.question_value_data.value))){
						error="<?php echo addslashes(stripslashes($question_result_error));?>";
				}
			}
			if (error!=""){
				alert(error);
				return false;
			}
			if (sessions.length<=1 || session_style!='E' || session_type=='S') return true;
			// check for event based waiting lists that reservations exist before selected waitlist
			var no_reserve=0; // selected reserve count
			var no_waitlist=0;
			var gap_on=false;
			session_store_type="M";
			for (icnt=0;icnt<sessions.length;icnt++){
				if (sessions[icnt][1]=='W' && check_field[icnt].checked) {
					session_store_type='W';
				} 
				if (sessions[icnt][1]=='R' && check_field[icnt].checked) no_reserve+=1;
			}
			return true;
		}
		function isDate(dateStr) {
		
		  var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
		  var matchArray = dateStr.match(datePat); // is format OK?
		
		  if (matchArray == null) {
			return false;
		  }
		
		  // parse date into variables
		  month = matchArray[1];
		  day = matchArray[3];
		  year = matchArray[5];
		
		  if (month < 1 || month > 12) { // check month range
			return false;
		  }
		
		  if (day < 1 || day > 31) {
			return false;
		  }
		
		  if ((month==4 || month==6 || month==9 || month==11) && day==31) {
			return false;
		  }
		
		  if (month == 2) { // check for february 29th
			var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
			if (day > 29 || (day==29 && !isleap)) {
			  return false;
			}
		  }
		  return true;  // date is valid
}
</script>
<!--service-->
<script language="javascript">
			var max_bookings;
			var time_length;
			var book_type;
			var book_granular;
			var service_quantity;
			var start_time="00:00";
			var end_time="23:59";
			var span_days;
			var tempCheck=1;
			var cur_hour;
			var cur_date;
			var include_resource;
			var include_attributes;
			var multiple_purchase;			
			var st_time;
			var et_time;
			var sel_start_date="";
			var sel_start_time="";
			var select_edate="";
			if(!time_length) time_length=1;
			var book_buffer;
			var book_buffer_minute; 
 			 var attribute_array=Array();
		
				function ValidateserviceForm(){
					var frm = document.select_resource;
					var error_result="";
					if (book_type=="D"){
						if (frm && frm.start_times.value==""){
							error_result="<?php echo addslashes(ERR_SELECT_START_TIME);?>";
						} else if (frm && frm.end_times.value==""){
							error_result="<?php echo addslashes(ERR_SELECT_END_TIME);?>";
						}
					} else {
						if (frm && frm.start_date.value=="" || frm && frm.start_time.value==""){
							error_result="<?php echo addslashes(ERR_SELECT_START_TIME);?>";
						} else if (frm && frm.end_times.value==""){
							error_result="<?php echo addslashes(ERR_SELECT_END_TIME);?>";
						}
					}
					if(frm && include_resource=='N' &&  multiple_purchase=='Y')
					{
						if(frm.quantity.value=="" || isNaN(frm.ser_quantity.value))
							error_result='<?php echo ERR_EMPTY_HOW_MANY;?>';
					}
					if (error_result!=""){
						alert(error_result);
						return false;
					}
					var option_id="";
					if(frm && include_resource=='N' &&  multiple_purchase=='Y')	
						frm.ser_quantity.value=frm.quantity.value;
					else if(frm)
						frm.ser_quantity.value=1;
					var id="";
					if(frm){
						for(i=0;i<attribute_array.length;i++){
							id="id_attrib["+attribute_array[i]+"]";
							frm_option=document.getElementById(id);
							if(frm_option) option_id+=frm_option.options[frm_option.selectedIndex].value+",";
						}
					}
					if(document.select_resource.option_ids) document.select_resource.option_ids.value=option_id;  
					if(frm && book_type=='D' && frm.start_times)
						frm.start_times.value=frm.start_times.options[frm.start_times.selectedIndex].value;
					
					return true;
				} 

				function sel_services(boxname,id,index){ 
					var element=document.getElementById(boxname+id); 
					var field=document.select_resource.elements[boxname+"_index"];  
					field.value=index;
					field=document.select_resource.elements[boxname];
					if (field.value!=''){
						document.getElementById(boxname+field.value).style.backgroundColor="#FFFFFF"; 
					}
					field.value=id;  
					element.style.backgroundColor="#D8EDFB";
				}
				function get_diff_minutes(stime,etime){
					splt1=stime.split(":");
					splt2=etime.split(":");
					smin=parseInt(splt1[0],10)*60+parseInt(splt1[1],10);
					emin=parseInt(splt2[0],10)*60+parseInt(splt2[1],10); 
					return emin-smin;
				}				

				function add_options(textArr,valueArr,optionElement){
					// clear the previous details
					
					while(optionElement.options.length>0){
						optionElement.remove(optionElement.options.length - 1);
					}
					//create the new details
					for (icnt=0;icnt<textArr.length;icnt++){
						  var option = document.createElement('option');
						  option.text = textArr[icnt];
						  option.value = valueArr[icnt];
						  try {
							optionElement.add(option, null); // standards compliant; doesn't work in IE
						  }
						  catch(ex) {
							optionElement.add(option); // IE only
						  }
						  if (valueArr[icnt]==select_edate) optionElement.selectedIndex=optionElement.options.length-1;
					}
				}
				
			function add_start_times(){
				  	var select_cnt=0;
					var dis_time_format="";
					dis_time_format="<?php if(defined('TIME_FORMAT')) echo TIME_FORMAT; ?>";
					if((book_type=='H' || book_type=='M') && document.select_resource && document.select_resource.start_date){
						st_date=document.select_resource.start_date.value;
						var tempDate=convert_to_sdate(st_date);
					}
					var i=0;
					var hour;
					var sel_ecnt=0;
					var arr_text=Array();
					var arr_value=Array();
					splt_cur_hour=cur_hour.split(":");
					var cnt=0;
					if(tempDate==cur_date) i=(parseInt(splt_cur_hour[0])+1) * 60;
					var slot=parseInt(book_granular); //booking granular
					if(book_type=='H') slot=parseInt(slot*60);
					while(i<=1440){
						if(i>1440) break;						
					   // loop for no booking date and time 
					    for(j=0;j<nb_dates.length;j++){
							 n_dates=nb_dates[j].split("#");
							 n_sdate=n_dates[0];
							 nb_s_time=n_dates[1];
							 nb_e_time=n_dates[2];
							 splt_etime=nb_e_time.split(":");
							 splt_stime=nb_s_time.split(":");
							 splt_stime_mt=splt_stime[0] * 60;
							 splt_etime_mt=splt_etime[0] * 60;
							 if(n_sdate==tempDate){
							      if(splt_stime_mt<=i && i<=splt_etime_mt || splt_stime_mt==i) 	
							   	  	i=splt_etime_mt;
						     }	 
						}
						// loop for no booking date and time
						 buf_min=0;
						 if(i>=1440) break;
						 var mins=parseInt(time_length*60);
						 if(book_type=='M') mins=parseInt(time_length);
						 for(ict=0;ict<=59;ict+=slot){
					 	     var d_obj=new Date(1976,1,1,0,i,ict*60);
						  	 hr=((d_obj.getHours()==0)?00:d_obj.getHours());
							 hr=((hr<10)?"0"+hr:hr);
						     mt=((d_obj.getMinutes()<10)?"0"+d_obj.getMinutes():d_obj.getMinutes());
						     var tem_hr=hr;
						     if(dis_time_format=='24'){
						     	if(hr==12) tem_hr=12;
						     	//if(hr==00) tem_hr=24;
						     }else if(hr==12) tem_hr=24;
						     tem_hour=tem_hr +":"+mt;
						     hour=hr +":"+mt;
						     var n_obj=new Date(1976,1,1,hr,(mt+mins));
						     if(span_days=='N' && n_obj.getDate()=="2" && (n_obj.getMinutes()>0 || n_obj.getHours()>0)) hour="";
						     	if(hour!=""){
									var dis_time=convert_to_stime(tem_hour);
									if(dis_time_format!="" && dis_time_format=='24') dis_time=tem_hour;
							     		if(convert_to_stime(st_time)==convert_to_stime(hour)) select_cnt=cnt;
											arr_text[cnt]=dis_time;
											arr_value[cnt]=hour;
							     			cnt++;
						     	}
						  }
						  if(book_type=='H') i=parseInt(i+slot);
						  else i=parseInt(i+60);
						  if(i>1440) break;
					 }
					 if(arr_text.length<=0 && arr_value.length<=0 && (book_type=='H' || book_type=='M') && document.select_resource.start_time && document.select_resource.start_date){
					 	document.select_resource.start_date.remove(document.select_resource.start_date.options.selectedIndex);
					 	add_start_times();
					 }
					 if (arr_text.length>0 && arr_value.length>0 && (book_type=='H' || book_type=='M')){
					 	add_options(arr_text,arr_value,document.select_resource.start_time);
					 	add_end_times();
					 }			 										 
					return select_cnt;
				}

				function add_end_times(){
				var arr_text=Array();
				var sel_ecnt=0;
				var arr_value=Array();
				//check if booking is day based or hours based
				var dis_time_format="";
				dis_time_format="<?php if(defined('TIME_FORMAT')) echo TIME_FORMAT; ?>";
				var end_time='23:59:00';
				var send_time=convert_to_stime('00:00:00');
				if(dis_time_format!="") if(dis_time_format=='24') send_time='00:00';													
				if (book_type=="D"){
						if(document.select_resource && document.select_resource.start_times) var tempDate=getDatePart(document.select_resource.start_times.value,"D");
						jcnt=0;
						if (!tempDate) return;
						for (icnt=time_length;icnt<=max_bookings;icnt=icnt+time_length){
						    start_time_split=start_time.split(":");
						    hour=start_time_split[0];
						  if(hour==00){
								if(jcnt>=1)
								  	tempDate=dateAdd("d",time_length,tempDate);
								else 
									tempDate=dateAdd("d",time_length-1,tempDate);
					      }else tempDate=dateAdd("d",time_length,tempDate);						   
						 	if(et_time==tempDate+" "+end_time)sel_ecnt=jcnt;
						 	tempDate_ed=dateAdd("d",1,tempDate);
							arr_value[jcnt]=tempDate+" "+end_time;
							arr_text[jcnt]=date_format(tempDate_ed,'Y-m-d','')+" "+send_time;
							jcnt++;
						}
				} else {
						var tempTime_s='0:0';
						var tempDate='1-1';
						if(document.select_resource){
							tempTime_s=document.select_resource.start_time.value;
							tempDate=document.select_resource.start_date.value;
							var check_date=tempDate;
							var tempDateS=document.select_resource.start_date.value;
						}
						var check_date=tempDateS;
						if (!tempTime_s && document.select_resource) {
							document.select_resource.start_time.remove(document.select_resource.start_time.options.selectedIndex)
							if(document.select_resource.start_time.options.length<0) document.select_resource.start_date.remove(document.select_resource.start_date.options.selectedIndex)
						}
						if (book_granular<=0) book_granular=1;
						slot=book_granular;
						jcnt=0;
						elapsed=1;
						tempCheck=0;
						hour=0;
						var display_hour = 0;
						var display_minute = 0;
						var mins=time_length*60;
						var maxs=max_bookings*60;						
						if(book_type=='M'){
							mins=time_length;
							maxs=max_bookings;
						}
						while(true){		
								tempTime_splt=tempTime_s.split(":");
								tempdate_splt=tempDate.split("-");
								hour=parseInt(tempTime_splt[0],10);
								if(tempTime_s=="24:00"){
							    	hour=11+parseInt(time_length);
								    display_hour=11+parseInt(time_length);  //Display Hour
								}
								//else if(hour==23 && book_type=='H') mins-=1;
								else if(tempTime_splt[0]=="24"){
								  hour=12+parseInt(time_length);
								  display_hour=12+parseInt(time_length);  //Display Hour
								}
							hour=((hour<10)?"0"+hour:hour);
							minute=parseInt(tempTime_splt[1],10)+mins;
							minute=((minute<10)?"0"+minute:minute);
							var dt=new Date(tempdate_splt[0],parseInt(tempdate_splt[1])-1,tempdate_splt[2],hour,minute,0);							
							getday=dt.getDate();
							getmonth=dt.getMonth()+1;
							getyear=dt.getFullYear();
							set_getday=getday;
							set_getmonth=getmonth
							set_getyear=getyear;
							if(tempdate_splt[2]<getday && dt.getHours()==0 && dt.getMinutes()==0){
								set_getday=tempdate_splt[2];
								set_getmonth=tempdate_splt[1];
								set_getyear=tempdate_splt[0];
							}
							if(set_getday<10)   set_getday="0"+set_getday; 								
							if(set_getmonth<10) set_getmonth="0"+set_getmonth;
							tempDate=tempDateS=(dt.getFullYear()+"-"+getmonth+"-"+getday);
							set_tempDate=(set_getyear+"-"+set_getmonth+"-"+set_getday);
							tempTime_s=((dt.getHours()<10)?"0"+dt.getHours():dt.getHours()) + ":"+ dt.getMinutes();
							var display_dt=new Date(tempdate_splt[0],tempdate_splt[1]-1,tempdate_splt[2],hour,minute,(minute=="59")?60:1);							
							display_tempDate=(display_dt.getFullYear()+"-"+(display_dt.getMonth()+1)+"-"+display_dt.getDate());
							display_tempTime_s=((display_dt.getHours()<10)?"0"+display_dt.getHours():display_dt.getHours())+ ":" + ((display_dt.getMinutes()<10)?"0"+display_dt.getMinutes():display_dt.getMinutes());
							var dis_time=convert_to_stime(display_tempTime_s);
							if(dis_time_format!="" && dis_time_format=='24')  dis_time=display_tempTime_s;
							check_date_obj=date_format(check_date,'Y-m-d','Y-m-d',true);
							tempDate_obj=date_format(tempDate,'Y-m-d','Y-m-d',true);
							if (tempTime_s>end_time || (span_days=='N' && check_date_obj<tempDate_obj && (dt.getMinutes()>0 || dt.getHours()>0))) break;
								if(et_time==tempDate+" "+tempTime_s) sel_ecnt=jcnt;
								arr_text[jcnt]=date_format(display_tempDate,'Y-m-d','')+" "+dis_time;
								arr_value[jcnt]=set_tempDate+" "+tempTime_s;
								elapsed+=mins;							
							if (elapsed>maxs) break;
							jcnt++;	
					 } 
				 }
				  if(arr_text.length>0 && document.select_resource) {
					document.select_resource.end_times.style.display='';
					add_options(arr_text,arr_value,document.select_resource.end_times);	
				  }
				  return sel_ecnt;
				}
				function getDatePart(source,type){
					var result="";
					if (source!=""){
						splt=source.split(" ");
						if (type=="D")
							result=splt[0];
						else
							result=splt[1];
					}

					return result;
				}
				function convert_to_sdate(sdate){
					format="<?php echo EVENTS_DATE_FORMAT;?>";
					splt=sdate.split("-");
					switch(format){
						case "d-m-Y":
							rdate=splt[2]+"-"+splt[1]+"-"+splt[0];
							break;
						case "m-d-Y":
							rdate=splt[1]+"-"+splt[2]+"-"+splt[0];
							break;
						case "Y-m-d":
							rdate=sdate;
							break;
					}
					return rdate;
				}
				
				function convert_to_stime(stime){
					splt=stime.split(":");
					hour=parseInt(splt[0],10);
					minutes=parseInt(splt[1],10);
					if (hour>12 || hour==12){
						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;
				}
			
			
   function dateAdd(p_Interval, p_Number, p_Date,ret_type){	
				if(isNaN(p_Number)){return false;}
				//convert date elements
				if(!ret_type) ret_type=false;
				if (book_type=="H"){ 
					splt=new Array(1967,1,1);
					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_times=new Array(0,0,0);
					splt_hours=getDatePart(p_Date,'D');
					if(getDatePart(p_Date,'H')) splt_times=getDatePart(p_Date,'H').split(":");
					splt=getDatePart(p_Date,'D').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 + "'";
					}
				}
			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;
			var ret="";	
			if (book_type=="H") {
				if(ret_type) ret=dt.getFullYear()+"-"+month+"-"+day+" "+hour+":"+minute;
				else ret=hour+":"+minute;
			}else {
				if(ret_type) ret=dt.getFullYear()+"-"+month+"-"+day+" "+hour+":"+minute;
				else ret=dt.getFullYear()+"-"+month+"-"+day;	
			}	
			  return ret;
			}
   
	function get_diff_minutes(stime,etime){
		splt1=stime.split(":");
		splt2=etime.split(":");
		smin=parseInt(splt1[0],10)*60+parseInt(splt1[1],10);
		emin=parseInt(splt2[0],10)*60+parseInt(splt2[1],10);
		return emin-smin;
	}
</script>

<!---add product_script_end-->
<script language="JavaScript">
		function resize(){
			document.getElementById('customer_list').style.visibility="hidden";
			document.select_customer.customer_text.blur();
		}
		var iex=(document.all);//ie
		var na6=(window.sidebar);//netscape 6.2
		var lastposition=0;
		var currentField="";
		var intervalId;
			function checkdropDown(){
				if (currentField==""){
					clearInterval(intervalId);
					hideList();
					intervalId="";
				}
			}
			function toggleText(mode){
				if (mode==1) {
					currentField="Text";
					showList();
					if (intervalId) clearInterval(intervalId);
					intervalId=setInterval("checkdropDown()",300);
				} else {
					currentField="";
				}
			}
			function toggleList(mode){
				if (mode==1){
					currentField="drop";
				} else {
					currentField="";
				}
			}
			function showList(){
				var listbox=document.getElementById("customer_list");
				var textbox=document.select_customer.customer_text;
				listbox.style.visibility="visible";
				listbox.style.display="";
				var left = getPageOffsetLeft(textbox);
				var top =getPageOffsetTop(textbox);

				if(window.scrollMaxX >0)listbox.style.left=left;
				else listbox.style.left=left;
				listbox.style.top=top+17;
								
			}
			function hideList(){
				var listbox=document.getElementById("customer_list");
				var textbox=document.select_customer.customer_text;
				setListboxText(1);
				listbox.style.display="none";
			}
			function scrollList(e){
				var listbox=document.select_customer.customers_id;

				if (iex) keyCode=window.event.keyCode;
				if (na6) keyCode=e.which;

				if (keyCode==40 || keyCode==38){
					if (keyCode==40 && listbox.selectedIndex>=0 && listbox.selectedIndex<listbox.options.length-1){
						listbox.selectedIndex+=1;
					} else if (keyCode==38 && listbox.selectedIndex>0 && listbox.selectedIndex<=listbox.options.length-1){
						listbox.selectedIndex-=1;
					}

					setListboxText(0);
					if (iex) window.event.returnValue=0;
					if (na6) e.returnValue=0;
					return;

				}
			}

			function selectList(e){
				var listbox=document.select_customer.customers_id;
				var search_word=document.select_customer.customer_text.value;
				var text_length;
				var found=-1;
				var listbox_word;
				var eventObject;
				var keyCode=0;
				var fromPos=0;
				var toPos=0;
	
				if (!listbox.options || listbox.options.length<=0) return;

				if (search_word!="") {
					search_word=search_word.toLowerCase();
					found=binaryFind(listbox,search_word,0,listbox.options.length-1);
					if (found>=0)
						listbox.selectedIndex=found;
				}

			}
			function setListboxText(mode){
				var listbox=document.select_customer.customers_id;
				if (!listbox.options || listbox.options.length<=0 || listbox.selectedIndex<=-1) return;
				var textbox_name=document.select_customer.customer_text;
				if (textbox_name.value=="" && mode==1) return "";
				textbox_name.value=listbox.options[listbox.selectedIndex].innerHTML;
				//merge
			    if((document.getElementById("img_process1") && document.getElementById("ajx_load_content_img")))	
					document.getElementById("img_process1").innerHTML=document.getElementById("ajx_load_content_img").innerHTML;
				//merge	
				command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'command=show_customer_details');?>&cID="+listbox.options[listbox.selectedIndex].value;
				do_get_command(command);	
			}
			function binaryFind(listBox,fWord,sPos,ePos){
				var listElement;
				var tWord;
				var mPos;
				if (sPos>ePos) return -1;
				mPos=sPos+Math.ceil((ePos-sPos)/2);
				
				if (mPos<0 || mPos>=listBox.options.length) return -1;
				listElement=listBox.options[mPos].innerHTML.toLowerCase();
				tWord=listElement.substr(0,fWord.length);

				if (tWord==fWord) return mPos;
				if (mPos<=0 || mPos>=listBox.options.length) return -1;
				
				if (fWord<tWord) return binaryFind(listBox,fWord,mPos+1,ePos);
				else return binaryFind(listBox,fWord,sPos,mPos-1);
			}
function check_input(field_name, pos,field_size) {
  var form=document.select_session;
  if (pos>=0){
	  var control=form.elements[field_name][pos];
  } else {
	  var control=form.elements[field_name];
  }
  var field_value = control.value;
  if (field_value == '' || field_value.length < field_size) {
    return true;
  }
} 
function check_select(field_name, pos,field_default) {
  var form=document.select_session;
  if (pos>=0){
	  var control=form.elements[field_name][pos];
  } else {
	  var control=form.elements[field_name];
  }
  var field_value = control.value;

   if (field_value == field_default) {
     return true;
   }
}
function dofill(){
	var frm=document.select_session;
	frm_customers=frm.elements["attendee[]"];
	for (icnt=1;icnt<frm.elements["city[]"].length;icnt++)
	{
	 if(frm_customers && frm_customers[icnt].checked) return;	
	 frm.elements["city[]"][icnt].value=frm.elements["city[]"][0].value;
	 frm.elements["state1[]"][icnt].style.display='';
	 frm.elements["state[]"][icnt].style.display="none";
	 if(frm.elements["state[]"][0].style.display!='none') 	
	 	state=frm.elements["state[]"][0].value;
	 else if(frm.elements["state1[]"][0].style.display!='none')
	 	state=frm.elements["state1[]"][0].value;
		 			 	
	 frm.elements["state1[]"][icnt].value=state;		
	 frm.elements["country[]"][icnt].value=frm.elements["country[]"][0].value;
	 frm.elements["postcode[]"][icnt].value=frm.elements["postcode[]"][0].value;
	 frm.elements["street_address[]"][icnt].value=frm.elements["street_address[]"][0].value;
	 frm.elements["email_address[]"][icnt].value=frm.elements["email_address[]"][0].value;
	}
}
function clear_error(pos){
	error_control=document.getElementById("error_box_"+pos);
	error_control.innerHTML="";
	error_control.style.display="none";
}
function show_errors(count){
	for (icnt=0;icnt<count;icnt++){
		error_control=document.getElementById("error_box_"+icnt);
		error_control.style.display="";
	}
}
function check_customer(pos){
	var error_att="";
		if (check_input("first_name[]",pos,"<?php echo ENTRY_FIRST_NAME_MIN_LENGTH;?>")){
			error_att+="<?php echo FIRST_NAME_ERROR;?><br>";
		}
		if (check_input("last_name[]",pos,"<?php echo ENTRY_LAST_NAME_MIN_LENGTH;?>")){
			error_att+="<?php echo LAST_NAME_ERROR;?><br>";
		}
		if (check_input("email_address[]",pos,"<?php echo ENTRY_EMAIL_ADDRESS_MIN_LENGTH;?>")){
			error_att+="<?php echo EMAIL_ADDRESS_ERROR;?><br>";
		}
		if (check_input("street_address[]",pos,"<?php echo ENTRY_STREET_ADDRESS_MIN_LENGTH;;?>")){
			error_att+="<?php echo STREET_ADDRESS_ERROR;?><br>";
		}
		if (check_input("city[]",pos,"<?php echo ENTRY_CITY_MIN_LENGTH;?>")){
			error_att+="<?php echo CITY_ERROR;?><br>";
		}
		if (check_input("postcode[]",pos,"<?php echo ENTRY_POSTCODE_MIN_LENGTH;?>")){
			error_att+="<?php echo POSTCODE_ERROR;?><br>";
		}
		if(document.select_session.elements["state[]"].size!=0){
			if (document.select_session.elements["state[]"][pos].style.display!='none' && check_input("state[]",pos,"<?php echo ENTRY_STATE_MIN_LENGTH;?>")){
				error_att+="<?php echo STATE_ERROR;?><br>";
			}else if(document.select_session.elements["state1[]"][pos].style.display!='none' && check_input("state1[]",pos,"<?php echo ENTRY_STATE_MIN_LENGTH;?>")){
				error_att+="<?php echo STATE_ERROR;?><br>";
			}
		}else if(document.select_session.elements["state[]"].size==0) {
			if (document.select_session.elements["state[]"].style.display!='none' && check_input("state[]",pos,"<?php echo ENTRY_STATE_MIN_LENGTH;?>")){
				error_att+="<?php echo STATE_ERROR;?><br>";
			}else if(document.select_session.elements["state1[]"].style.display!='none' && check_input("state1[]",pos,"<?php echo ENTRY_STATE_MIN_LENGTH;?>")){
				error_att+="<?php echo STATE_ERROR;?><br>";
			}
		}	
		if (check_select("country[]",pos,"")){
			error_att+="<?php echo COUNTRY_ERROR;?><br>";
		}
		if (pos>0){
			var controls=document.select_session.elements["email_address[]"];
			var attendees=document.select_session.elements["attendee[]"];
			for (jcnt=pos-1;jcnt>=0;jcnt--){
				if (controls[pos].value==controls[jcnt].value){
					if(attendees && attendees[pos].checked)
						error_att="<?php echo ERR_ATTENDEES_MUST_UNIQUE;?>";
					else if(attendees && !attendees[pos].checked)
						error_att="<?php echo EMAIL_UNIQUE_ERROR;?>";	
				}
				if(controls[jcnt].value.indexOf('@')<=0 || controls[jcnt].value.indexOf('.')<=0){
					error_att="<?php echo ADDRESS_CHECK_ERROR;?>";
				}
			}
		}
	return error_att;
}
function check_attendee_form(form_name) {
	var error=false;
	var frm=document.select_session;
	if(frm.elements["country[]"].size!=0){
		for(i=0;i<frm.elements["country[]"].length;i++){
			if(frm.elements["state[]"][i].style.display!='none')
				frm.elements["state[]"][i].disabled=false;
				frm.elements["country[]"][i].disabled=false; 
		}
	}else if(frm.elements["country[]"].size==0){
			if(frm.elements["state[]"].style.display!='none')
				frm.elements["state[]"].disabled=false;
			frm.elements["country[]"].disabled=false;  	
	}
	var controls=frm.elements["first_name[]"];
	set_state();
	if (controls.length){
		for (icnt=0;icnt<controls.length;icnt++){
			error_att=check_customer(icnt);
			if (error_att!="") {
				error=true;
				error_control=document.getElementById("error_box_"+icnt);
				error_control.innerHTML=error_att;
				error_control.style.display="";
			}
		}
	} else {
		error_att=check_customer(-1);
		if (error_att!="") {
			error=true;
			error_control=document.getElementById("error_box_0");
			error_control.innerHTML=error_att;
			error_control.style.display="";
		}
	}
	if (error == true) {
		return false;
	} else {
		submitted = true;
		return true;
	}
}

 function hide_customerlistbox(i){
	 var frm=document.select_session;
	 var val=new Array('','','','','','','','');
	 var frm_customer=frm.elements["attendee[]"];
	 var check=false;
	 	 if(frm_customer.length>0){
				if(frm_customer) check=frm_customer[i].checked;
				if(check){
					frm.customer_text[i].style.display="";
					fill_details(i);
				}else if(!check) { 
					frm.customer_text[i].style.display="none";
					fetch_details(val,i);
				}			
				frm.elements["first_name[]"][i].readOnly=frm.elements["last_name[]"][i].readOnly=frm.elements["email_address[]"][i].readOnly=frm.elements["street_address[]"][i].readOnly=frm.elements["city[]"][i].readOnly=frm.elements["postcode[]"][i].readOnly=check;
				frm.elements["country[]"][i].disabled=check;
				frm.elements["state[]"][i].style.display='none';
				frm.elements["state1[]"][i].style.display='';
				if(frm.elements["state1[]"][i])
					frm.elements["state1[]"][i].readOnly=check;
				 
		}else {
			if(frm.elements["attendee[]"]) check=frm.elements["attendee[]"].checked;	
			if(check){
				frm.customer_text.style.display="";
				fill_details(0);
			}else if(!check) {	
				frm.customer_text.style.display="none";
				fetch_details(val,0);
			}
			frm.elements["first_name[]"].readOnly=frm.elements["last_name[]"].readOnly=frm.elements["email_address[]"].readOnly=frm.elements["street_address[]"].readOnly=frm.elements["city[]"].readOnly=frm.elements["postcode[]"].readOnly=check;
			frm.elements["country[]"].disabled=check;
			if(frm.elements["state[]"].style.display!='none')
				frm.elements["state[]"].disabled=check;
			else if(frm.elements["state1[]"])
				frm.elements["state1[]"].readOnly=check;
		}
	}
  function fill_details(cnt){
  	id=0;
  	var frm=document.select_session.elements["customer_text"];
  	if(frm.size!=0)
  		id=frm[cnt].options[frm[cnt].selectedIndex].value; 
	else 
		id=frm.options[frm.selectedIndex].value;
		command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'command=fetch_customers_details','NONSSL',true,false);?>&cust_id="+id+"&cnt="+cnt; 
   	do_get_command(command);
  } 
	function set_state(){
		var frm=document.select_session;
			if(frm.elements["country[]"].size!=0){
				for(i=0;i<frm.elements["country[]"].length;i++){
					if(frm.elements["state[]"][i].style.display!='none'){
						frm.elements["customer_state[]"][i].value=frm.elements["state[]"][i].value;
					}
					else	
						frm.elements["customer_state[]"][i].value=frm.elements["state1[]"][i].value;
				}
			}else if(frm.elements["country[]"].size==0){
					if(frm.elements["state[]"].style.display!='none'){
						frm.elements["customer_state[]"].value=frm.elements["state[]"].value;
					}
					else 
						frm.elements["customer_state[]"].value=frm.elements["state1[]"].value;
			}
					  
	}
  
  function fetch_details(val,i){ 
  	var frm=document.select_session;
  	if(!frm.elements["first_name[]"].length){
  		frm.elements["first_name[]"].value=val[0];  
		frm.elements["last_name[]"].value=val[1];
		frm.elements["email_address[]"].value=val[2];
		frm.elements["street_address[]"].value=val[3];
		frm.elements["city[]"].value=val[4];  
		frm.elements["postcode[]"].value=val[5]; 
		if(frm.elements["state[]"].style.display!='none') 
			frm.elements["state[]"].value=val[6];
		else if(frm.elements["state1[]"])
			frm.elements["state1[]"].value=val[6];
		frm.elements["country[]"].value=val[7];
	}else if(frm.elements["first_name[]"][i]){
		frm.elements["first_name[]"][i].value=val[0];  
		frm.elements["last_name[]"][i].value=val[1];
		frm.elements["email_address[]"][i].value=val[2]; 
		frm.elements["street_address[]"][i].value=val[3];
		frm.elements["city[]"][i].value=val[4];  
		frm.elements["postcode[]"][i].value=val[5]; 
		if(frm.elements["state[]"][i].style.display!='none')
			frm.elements["state[]"][i].value=val[6];
		else if(frm.elements["state1[]"][i]){ 
			frm.elements["state1[]"][i].value=val[6];
		}
		frm.elements["country[]"][i].value=val[7];	
	}
  }
  
  function show_attendee_state(cnt){ 
  		var this_=document.select_session.elements["country[]"];
  		if(this_[cnt].size==0)
  			id=this_[cnt].options[this_[cnt].selectedIndex].value;
  		else
  			id=this_.options[this_.selectedIndex].value;
		if(id){
		  command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'command=show_state','NONSSL',true,false);?>&country_id="+id+"&cnt="+cnt;
		  do_get_command(command);	
		}
  }   
		</script>
		<tr>
		<td valign="top">
			<div id="step2_show" style="display:none"></div>
			<div id="step3_show" style="display:none"></div>
			<div id="step4_show" style="display:none"></div>
			<div id="step5_show" style="display:none">
			<?php 
			if($HTTP_GET_VARS['payment_error_flag']=="yes")
			{
				require(FILENAME_CHECKOUT_PAYMENT_NEW);
			 }?>
			</div>
			<div id="step6_show" style="display:none"></div>
			<div id="step1_show"><?php out_create_order_step1($customers_id);?></div>
		</td>
		</tr>
	</table>
	</td></tr>
</table>
</td></tr></table>
<?php if($HTTP_GET_VARS['payment_error_flag']=="yes")
{?>
<script>
	document.getElementById("step5_show").style.display="";
	document.getElementById("step1_show").style.display="none";
</script>
<?php }?>
<!-- body_eof //-->
<!-- footer //-->
<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
<!-- footer_eof //-->
<div id="ajx_load_content_img" style="display:none"><img src="images/24-1.gif"></div>
</body>
</html>
<?php 
require(DIR_WS_INCLUDES . 'application_bottom.php'); 
}
function tep_update_customers($customers_id)
{
	global $HTTP_POST_VARS,$customer_default_address_id,$customer_id,$server_date,$order_id,$customer_country_id,$customer_zone_id;
		  $firstname = tep_db_prepare_input($HTTP_POST_VARS['firstname']);
		  $lastname = tep_db_prepare_input($HTTP_POST_VARS['lastname']);

		  $email_address = tep_db_prepare_input($HTTP_POST_VARS['email_address']);
		  $confirm_email_address = tep_db_prepare_input($HTTP_POST_VARS['confirm_email_address']);
		  
		  $second_email_address = tep_db_prepare_input($HTTP_POST_VARS['second_email_address']);
		  if($second_email_address!='')
		  	$second_confirm_email_address = tep_db_prepare_input($HTTP_POST_VARS['second_email_address']);
		  	
		  $telephone = tep_db_prepare_input($HTTP_POST_VARS['telephone']);
		  $second_telephone = tep_db_prepare_input($HTTP_POST_VARS['second_telephone']);
		  $mobile = tep_db_prepare_input($HTTP_POST_VARS['mobile']);

		  $street_address = tep_db_prepare_input($HTTP_POST_VARS['street_address']);
		  $company = tep_db_prepare_input($HTTP_POST_VARS['company']);
		  $suburb = tep_db_prepare_input($HTTP_POST_VARS['suburb']);
		  $postcode = tep_db_prepare_input($HTTP_POST_VARS['postcode']);
		  $city = tep_db_prepare_input($HTTP_POST_VARS['city']);
		  $zone_id = tep_db_prepare_input($HTTP_POST_VARS['zone_id']);
		  //$state = isset($HTTP_POST_VARS['state'])?tep_db_prepare_input($HTTP_POST_VARS['state']):$HTTP_POST_VARS['state1'];
		  $state = tep_db_prepare_input($HTTP_POST_VARS['state']);
        if($state=='' || $HTTP_POST_VARS['state1'])$state=tep_db_prepare_input($HTTP_POST_VARS['state1']);
        $country = tep_db_prepare_input($HTTP_POST_VARS['country']);
			$default_address_id=tep_db_prepare_input($HTTP_POST_VARS['default_address_id']);
		
		  $error = false; // reset error flag
		
		  if (strlen($firstname) < ENTRY_FIRST_NAME_MIN_LENGTH) {
			$error = true;
			$entry_firstname_error = true;
		  } else {
			$entry_firstname_error = false;
		  }
		
		  if (strlen($lastname) < ENTRY_LAST_NAME_MIN_LENGTH) {
			$error = true;
			$entry_lastname_error = true;
		  } else {
			$entry_lastname_error = false;
		  }
		
		  if (strlen($email_address) < ENTRY_EMAIL_ADDRESS_MIN_LENGTH) {
			$error = true;
			$entry_email_address_error = true;
		  } else {
			$entry_email_address_error = false;
		  }
		
		 if (!tep_validate_email($email_address)) {
				$error = true;
				$entry_email_address_check_error = true;
		  } else {
				$entry_email_address_check_error = false;
		  }
				 	
		 if ($second_email_address !='' && !tep_validate_email($second_email_address)) {
				$error = true;
				$entry_second_email_address_check_error = true;
		  }else {
				$entry_second_email_address_check_error = false;
		  }
		  
		  if (strlen($street_address) < ENTRY_STREET_ADDRESS_MIN_LENGTH) {
			$error = true;
			$entry_street_address_error = true;
		  } else {
			$entry_street_address_error = false;
		  }
		
		  if (strlen($postcode) < ENTRY_POSTCODE_MIN_LENGTH) {
			$error = true;
			$entry_post_code_error = true;
		  } else {
			$entry_post_code_error = false;
		  }
		
		  if (strlen($city) < ENTRY_CITY_MIN_LENGTH) {
			$error = true;
			$entry_city_error = true;
		  } else {
			$entry_city_error = false;
		  }
		
		  if (!$country) {
			$error = true;
			$entry_country_error = true;
		  } else {
			$entry_country_error = false;
		  }
		
		  if (ACCOUNT_STATE == 'true') {
			if ($entry_country_error) {
			  $entry_state_error = true;
			} else {
			  $zone_id = 0;
			  $entry_state_error = false;
			  $check_query = tep_db_query("select count(*) as total from " . TABLE_ZONES . " where zone_country_id = '" . tep_db_input($country) . "'");
			  $check_value = tep_db_fetch_array($check_query);
			  $entry_state_has_zones = ($check_value['total'] > 0);
			  if ($entry_state_has_zones) {
				$zone_query = tep_db_query("select zone_id from " . TABLE_ZONES . " where zone_country_id = '" . tep_db_input($country) . "' and zone_name = '" . tep_db_input($state) . "'");
				if (tep_db_num_rows($zone_query) == 1) {
				  $zone_values = tep_db_fetch_array($zone_query);
				  $zone_id = $zone_values['zone_id'];
				} else {
				  $zone_query = tep_db_query("select zone_id from " . TABLE_ZONES . " where zone_country_id = '" . tep_db_input($country) . "' and zone_code = '" . tep_db_input($state) . "'");
				  if (tep_db_num_rows($zone_query) == 1) {
					$zone_values = tep_db_fetch_array($zone_query);
					$zone_id = $zone_values['zone_id'];
				  } else {
					$error = true;
					$entry_state_error = true;
				  }
				}
			  } else {
				if (!$state) {
				  $error = true;
				  $entry_state_error = true;
				}
			  }
			}
		  }
		 if (ACCOUNT_TELEPHONE == 'true') {
		  if (strlen($telephone) < ENTRY_TELEPHONE_MIN_LENGTH) {
			$error = true;
			$entry_telephone_error = true;
		  } else {
			$entry_telephone_error = false;
		  }
		}
		  if (strpos($mobile,"+")!==FALSE) {
			$error = true;
			$entry_mobile_error = true;
		  } else {
		    $entry_mobile_error = false;
		  }

		$check_email = tep_db_query("select customers_email_address from " . TABLE_CUSTOMERS . " where customers_email_address = '" . tep_db_input($email_address) . "' and customers_id <> '" . tep_db_input($customers_id) . "'");
		if (tep_db_num_rows($check_email)) {
			$error = true;
			$entry_email_address_exists = true;
		} else {
			$entry_email_address_exists = false;
		}
		
		if ($error == false) {

        $sql_data_array = array('customers_firstname' => $firstname,
                                'customers_lastname' => $lastname,
                                'customers_email_address' => $email_address,
                                'customers_telephone' => $telephone,
                                'customers_fax' => $mobile);


		if (ACCOUNT_SECOND_PHONE=='true') $sql_data_array['customers_second_telephone']=$second_telephone;

		if (ACCOUNT_SECOND_EMAIL=='true') $sql_data_array['customers_second_email_address']=$second_email_address;
	

        tep_db_perform(TABLE_CUSTOMERS, $sql_data_array, 'update', "customers_id = '" . (int)$customers_id . "'");

        tep_db_query("update " . TABLE_CUSTOMERS_INFO . " set customers_info_date_account_last_modified ='" . $server_date . "' where customers_info_id = '" . (int)$customers_id . "'");

        if ($entry_zone_id > 0) $entry_state = '';

        $sql_data_array = array('entry_firstname' => $firstname,
                                'entry_lastname' => $lastname,
                                'entry_street_address' => $street_address,
                                'entry_postcode' => $postcode,
                                'entry_city' => $city,
                                'entry_country_id' => $country);

        if (ACCOUNT_COMPANY == 'true') $sql_data_array['entry_company'] = $company;
        if (ACCOUNT_SUBURB == 'true') $sql_data_array['entry_suburb'] = $suburb;

        if (ACCOUNT_STATE == 'true') {
          if ($zone_id > 0) {
            $sql_data_array['entry_zone_id'] = $zone_id;
            $sql_data_array['entry_state'] = '';
          } else {
            $sql_data_array['entry_zone_id'] = '0';
            $sql_data_array['entry_state'] = $state;
          }
        }
		$add_option="";
		/*if (isset($HTTP_POST_VARS["param_event"]) && isset($HTTP_POST_VARS["param_session"])){
			$add_option.="&param_1=" . $HTTP_POST_VARS["param_event"];
			$add_option.="&param_2=" . $HTTP_POST_VARS["param_session"];
		}*/
        tep_db_perform(TABLE_ADDRESS_BOOK, $sql_data_array, 'update', "customers_id = '" . (int)$customers_id . "' and address_book_id = '" . (int)$default_address_id . "'");
		//if(tep_session_is_registered('customer_id'))
		$check_sql = tep_db_query("select customers_default_address_id from " . TABLE_CUSTOMERS . " where customers_id = '" . (int)$customers_id . "'");
		$check_adr=tep_db_fetch_array($check_sql);
		tep_session_register('customer_id');
        tep_session_register('customer_default_address_id');
        tep_session_register('customer_zone_id');
		tep_session_register('customer_country_id');
		$customer_id=$customers_id;
		$customer_zone_id=$zone_id;
		$customer_default_address_id=$check_adr['customers_default_address_id'];
		$select_country_query= tep_db_query("select entry_country_id from " . TABLE_ADDRESS_BOOK . " where customers_id = " .(int)$customer_id);
		if(tep_db_num_rows($select_country_query)){
			while($customer_country_array = tep_db_fetch_array($select_country_query))
				  $customer_country_id = $customer_country_array['entry_country_id'];
		}

		//--------saving address in a temporary table-----------------
		if(tep_session_is_registered('order_id'))
		{
			tep_db_query("delete from " . TABLE_CUSTOMERS_BASKET_ADDRESS . " where customers_id='" . (int)$customer_id . "' and orders_id='" . (int)$order_id . "'");
			$address_query = tep_db_query("select * from " . TABLE_ORDERS . " where orders_id='" . (int)$order_id . "'");
			$address = tep_db_fetch_array($address_query);
			$sql_data_array = array('customers_id' => $customer_id,
									 'orders_id' => $order_id,
									'billing_name' => tep_db_input(stripslashes($address['billing_name'])),
									'billing_company' =>tep_db_input(stripslashes($address['billing_company'])) ,
									'billing_street_address' => tep_db_input(stripslashes($address['billing_street_address'])),
									'billing_suburb' =>tep_db_input(stripslashes($address['billing_suburb'])),
									'billing_city' =>tep_db_input(stripslashes( $address['billing_city'])),
									'billing_state' =>$address['billing_state'],
									'billing_postcode' =>tep_db_input(stripslashes($address['billing_postcode'])),
									'billing_country' =>tep_db_input(stripslashes($address['billing_country'])),
									'billing_address_format_id'=>tep_db_input(stripslashes( $address['billing_address_format_id'])),
									'delivery_name' => tep_db_input(stripslashes($address['delivery_name'] )),
									'delivery_company' =>tep_db_input(stripslashes($address['delivery_company'])),
									'delivery_street_address' =>tep_db_input(stripslashes($address['delivery_street_address'])),
									'delivery_suburb' =>tep_db_input(stripslashes( $address['delivery_suburb'])),
									'delivery_city' => tep_db_input(stripslashes($address['delivery_city'])),
									'delivery_state' =>$address['delivery_state'],
									'delivery_postcode' =>tep_db_input(stripslashes($address['delivery_postcode'])),
									'delivery_country' =>tep_db_input(stripslashes($address['delivery_country'])),
									'delivery_address_format_id'=>tep_db_input(stripslashes($address['delivery_address_format_id'])),
									'customers_telephone' =>tep_db_input(stripslashes($address['customers_telephone'])),
									'customers_second_telephone' =>tep_db_input(stripslashes($address['customers_second_telephone'])),
									'customers_fax' =>tep_db_input(stripslashes($address['customers_fax'])),
									'customers_second_email_address' =>tep_db_input(stripslashes($address['customers_second_email_address'])),
									'customers_email_address' =>tep_db_input(stripslashes($address['customers_email_address'])));
			tep_db_perform(TABLE_CUSTOMERS_BASKET_ADDRESS, $sql_data_array);
		}
		else
		{
			tep_db_query("delete from " . TABLE_CUSTOMERS_BASKET_ADDRESS . " where customers_id='" . (int)$customer_id . "' and orders_id=0");
			$shipping_address_query = tep_db_query("select ab.entry_firstname, ab.entry_lastname, ab.entry_company, ab.entry_street_address, ab.entry_suburb, ab.entry_postcode, ab.entry_city, ab.entry_zone_id, z.zone_name, ab.entry_country_id, c.countries_id, c.countries_name, c.countries_iso_code_2, c.countries_iso_code_3, c.address_format_id, ab.entry_state from " . TABLE_ADDRESS_BOOK . " ab left join " . TABLE_ZONES . " z on (ab.entry_zone_id = z.zone_id) left join " . TABLE_COUNTRIES . " c on (ab.entry_country_id = c.countries_id) where ab.customers_id = '" . (int)$customer_id . "' and ab.address_book_id = '" . (int)$customer_default_address_id . "'");
			$shipping_address = tep_db_fetch_array($shipping_address_query);
		
			$billing_address_query = tep_db_query("select ab.entry_firstname, ab.entry_lastname, ab.entry_company, ab.entry_street_address, ab.entry_suburb, ab.entry_postcode, ab.entry_city, ab.entry_zone_id, z.zone_name, ab.entry_country_id, c.countries_id, c.countries_name, c.countries_iso_code_2, c.countries_iso_code_3, c.address_format_id, ab.entry_state from " . TABLE_ADDRESS_BOOK . " ab left join " . TABLE_ZONES . " z on (ab.entry_zone_id = z.zone_id) left join " . TABLE_COUNTRIES . " c on (ab.entry_country_id = c.countries_id) where ab.customers_id = '" . (int)$customer_id . "' and ab.address_book_id = '" . (int)$customer_default_address_id . "'");
			$billing_address = tep_db_fetch_array($billing_address_query);
	
			 $sql_data_array = array('customers_id' => $customer_id,
									 'orders_id' => 0,
									'billing_name' => tep_db_input(stripslashes($billing_address['entry_firstname'] . ' ' . $billing_address['entry_lastname'])),
									'billing_company' =>tep_db_input(stripslashes($billing_address['entry_company'])) ,
									'billing_street_address' => tep_db_input(stripslashes($billing_address['entry_street_address'])),
									'billing_suburb' =>tep_db_input(stripslashes($billing_address['entry_suburb'])),
									'billing_city' =>tep_db_input(stripslashes( $billing_address['entry_city'])),
									'billing_state' =>((tep_not_null($billing_address['entry_state'])) ? $billing_address['entry_state'] : $billing_address['zone_name']),
									'billing_postcode' =>tep_db_input(stripslashes($billing_address['entry_postcode'])),
									'billing_country' =>tep_db_input(stripslashes($billing_address['countries_name'])),
									'billing_address_format_id'=>tep_db_input(stripslashes( $billing_address['address_format_id'])),
									'delivery_name' => tep_db_input(stripslashes($shipping_address['entry_firstname'] . ' ' . $shipping_address['entry_lastname'])),
									'delivery_company' =>tep_db_input(stripslashes($shipping_address['entry_company'])),
									'delivery_street_address' =>tep_db_input(stripslashes($shipping_address['entry_street_address'])),
									'delivery_suburb' =>tep_db_input(stripslashes( $shipping_address['entry_suburb'])),
									'delivery_city' => tep_db_input(stripslashes($shipping_address['entry_city'])),
									'delivery_state' =>((tep_not_null($shipping_address['entry_state'])) ? $shipping_address['entry_state'] : $shipping_address['zone_name']),
									'delivery_postcode' =>tep_db_input(stripslashes($shipping_address['entry_postcode'])),
									'delivery_country' =>tep_db_input(stripslashes($shipping_address['countries_name'])),
									'delivery_address_format_id'=>tep_db_input(stripslashes($shipping_address['address_format_id'])),
									'customers_telephone' =>tep_db_input(stripslashes($telephone)),
									'customers_second_telephone' =>tep_db_input(stripslashes($second_telephone)),
									'customers_fax' =>tep_db_input(stripslashes($mobile)),
									'customers_second_email_address' =>tep_db_input(stripslashes($second_email_address)),
									'customers_email_address' =>tep_db_input(stripslashes($email_address)));
			tep_db_perform(TABLE_CUSTOMERS_BASKET_ADDRESS, $sql_data_array);
		}


		echo "step2||";
		out_shopping_cart_details();
      } else if ($error == true) {
		   $account = $HTTP_POST_VARS;
		   echo "create_order_details||";
           require(DIR_WS_MODULES . 'create_order_details.php');
      }
}
function out_shopping_cart_details()
{
global $cart,$order_id,$customer_default_address_id,$customer_id,$currencies,$languages_id,$language,$order,$store_member,$HTTP_GET_VARS,$customer_country_id,$customer_zone_id;
require(FILENAME_SHOPPING_CART);
echo '||' . $cart->get_max_attendees().'||'.$content;
}
function out_create_order_step1($customers_id)
{	
	global $HTTP_POST_VARS;
	$query = tep_db_query("select customers_id, customers_firstname, customers_lastname,customers_email_address from " . TABLE_CUSTOMERS . " ORDER BY customers_lastname desc");
	$result = $query;
	$selected_name="";	
	if (tep_db_num_rows($result) > 0)
	{
		// Query Successful
		$SelectCustomerBox = "<select name='customers_id' size=10 onClick=\"javascript:setListboxText(0);toggleList(0);\" onFocus=\"javascript:toggleList(1);\" onBlur=\"javascript:toggleList(0);\" class='customerSelect'>\n";
		while($db_Row = tep_db_fetch_array($result)){ 
			$SelectCustomerBox .= "<option value='" . $db_Row["customers_id"] . "'";
			if($db_Row["customers_id"]==$customers_id){
				$SelectCustomerBox .= " SELECTED ";
				$selected_name=$db_Row["customers_lastname"] . ' ' . $db_Row["customers_firstname"] . ", " . $db_Row["customers_email_address"];
			}
			$SelectCustomerBox .= ">" . $db_Row["customers_lastname"] . ' ' .  $db_Row["customers_firstname"] . ", " . $db_Row["customers_email_address"] . " (" . $db_Row["customers_id"]. ") </option>\n";
		}
		$SelectCustomerBox .= "</select>\n";
	}
	
	?>
			<table border='0' cellpadding='0' width="100%"><tr><td class="main" valign="top">
				<tr>
					<td><?php echo tep_draw_separator('pixel_trans.gif', '100%', '5'); ?></td>
				</tr>
				<?php echo tep_draw_form('select_customer',FILENAME_CREATE_ORDER_NEW,'','post'); 
						/*if (isset($HTTP_POST_VARS["param_event"]) && isset($HTTP_POST_VARS["param_session"])){
							echo '<input type="hidden" name="param_event" value="' . $HTTP_POST_VARS["param_event"] .'">';
							echo '<input type="hidden" name="param_session" value="' . $HTTP_POST_VARS["param_session"] .'">';
						}*/
				?>
				<tr>
        			<td>
					<table border='0' cellpadding="4" cellspacing="0"  width="100%">
						<div id="customer_list" style="position:absolute;display:none;width:400px">
							<?php echo $SelectCustomerBox;?>
						</div>
						<tr> <?php echo tep_draw_separator('pixel_trans.gif', '100%', '5','1'); ?> </tr>
						<tr>
							<td class="main" width="100" align="right"><font color="#003366"><b><?php echo TEXT_NAME;?></b></font></td>
							<td class="main"><?php echo tep_draw_input_field('customer_text',$selected_name,'onFocus="javascript:toggleText(1);" onBlur="javascript:toggleText(0);" style="width:400px"',false,'text',false) . '&nbsp;<span id="img_process1"></span>';?></td>
					</table>
					</td>
				</tr>
				<tr height="3"></tr>
				</form>
				<script language="JavaScript">
					if(na6) document.select_customer.customer_text.addEventListener("keyup",selectList,true);
					if(iex) document.select_customer.customer_text.onkeyup=selectList;
					if(na6) document.select_customer.customer_text.addEventListener("keydown",scrollList,true);
					if(iex) document.select_customer.customer_text.onkeydown=scrollList;
				</script>
				<tr>
		 		<td class=infoBoxHeading><?php echo tep_draw_separator('pixel_trans.gif', '1', '3'); ?></td> 
        		</tr>
				<tr><td id="customer_details">
					<?php out_customer_details($customers_id);?>
				</td></tr>
			</table>
<?php }

function out_customer_details($customers_id)
{
	global $language,$HTTP_SESSION_VARS,$cart,$languages_id;
	$error = false;
	
	if($customers_id!='')
	{
		if(isset($HTTP_SESSION_VARS['param_event'])){
		$events_query = tep_db_query("select ed.events_name,e.sessions_select_interval from ".TABLE_EVENTS." e, ".TABLE_EVENTS_DESCRIPTION." ed where e.events_id=ed.events_id and ed.events_id='{$HTTP_SESSION_VARS['param_event']}' and ed.language_id='$languages_id'");
		$events_array = tep_db_fetch_array($events_query);
		
		$sessions_query = tep_db_query("select start_date,sessions_type from ".TABLE_EVENTS_SESSIONS." where sessions_id='{$HTTP_SESSION_VARS['param_session']}'");	
		$sessions_array = tep_db_fetch_array($sessions_query);
		
		if($events_array['sessions_select_interval']>1){
		
		$multiple_sessions_query = tep_db_query("select sessions_id,start_date,sessions_type from ".TABLE_EVENTS_SESSIONS." where start_date >= '{$sessions_array['start_date']}' limit {$events_array['sessions_select_interval']}");
			while($multiple_sessions_array = tep_db_fetch_array($multiple_sessions_query)){
				$sessions[$multiple_sessions_array['sessions_id']] = array("type"=>$multiple_sessions_array['sessions_type'],
						  "date"=>$multiple_sessions_array['start_date'],
						  "fees"=>0,
						  "group"=>'R');
			}
		
		} else {
		$sessions[$HTTP_SESSION_VARS['param_session']] = array("type"=>$sessions_array['sessions_type'],
						  "date"=>$sessions_array['start_date'],
						  "fees"=>0,
						  "group"=>'R');
		}
		
		$old_orders_id = 0;				  
		$question_type = '';				  
		$question_value = '';
		$no_attendees = 1;
		$cart->add_cart_event($HTTP_SESSION_VARS['param_event'],$sessions,$old_orders_id,$question_type,$question_value,$no_attendees);
		unset($HTTP_SESSION_VARS['param_event']);
		unset($HTTP_SESSION_VARS['param_session']);
		}

	
		$admin_group_sql = "select c.customers_id,c.is_blocked from " . TABLE_CUSTOMERS . " c where c.customers_id = '" . (int)$customers_id . "'";
		$admin_group_query = tep_db_query($admin_group_sql);
		$admin_group = tep_db_fetch_array($admin_group_query);
		$is_blocked = $admin_group['is_blocked'];
		$suspended = '';
		$group_sql = "select customers_id from " . TABLE_CUSTOMERS . " c where customers_id=" . (int)$customers_id . 
					" and ((suspend_from!='0000-00-00' and suspend_from<=curdate() and (resume_from='0000-00-00' or resume_from>curdate()))
					or (resume_from!='0000-00-00' && resume_from>curdate()))";
		$group_query = tep_db_query($group_sql);
		$is_data = tep_db_fetch_array($group_query);
		if($is_data['customers_id'] != ''){
			$error = true;
			$err_message = SUSPENDED_USER_ERROR;
		}
	   if($is_blocked=="Y"){
    		$error=true;
    		$err_message=BLOCKED_USER_ERROR;
	   }
		$account_query = tep_db_query("select c.customers_id, c.customers_gender, c.customers_firstname, c.customers_lastname, c.customers_dob, c.customers_email_address, c.customers_second_email_address, c.customers_type,c.customers_telephone, c.customers_second_telephone,c.customers_fax, c.customers_newsletter, c.customers_reserve_newsletter,c.customers_default_address_id from " . TABLE_CUSTOMERS . " c where c.customers_id = '" . (int)$customers_id . "'");
		$account = tep_db_fetch_array($account_query);
		$customer = $account['customers_id'];
		$address_query = tep_db_query("select a.entry_company, a.entry_street_address, a.entry_suburb, a.entry_postcode, a.entry_city, a.entry_state,a.entry_zone_id, a.entry_country_id from " . TABLE_ADDRESS_BOOK . " a where a.address_book_id = '" . $account['customers_default_address_id'] . "'");
		$address = tep_db_fetch_array($address_query);
		$account=array_merge($account,$address);
	}?>
		<?php echo tep_draw_form('customers', FILENAME_CREATE_ORDER_NEW, 'action=update', 'post', 'onSubmit="return check_form();"');
			/*if (isset($HTTP_POST_VARS["param_event"]) && isset($HTTP_POST_VARS["param_session"])){
				echo '<input type="hidden" name="param_event" value="' . $HTTP_POST_VARS["param_event"] .'">';
				echo '<input type="hidden" name="param_session" value="' . $HTTP_POST_VARS["param_session"] .'">';
			}*/
			if ($error) 
				echo '<input type="hidden" name="default_address_id" value="' . $account["default_address_id"] . '">';
			else
				echo '<input type="hidden" name="default_address_id" value="' . $account["customers_default_address_id"] . '">';
		?>
		<table width="100%" cellpadding="5" border="0">
			<tr>
				<td class="errortext"><?php echo $err_message; ?></td>
			</tr>
			<tr>
				<td><?php echo tep_draw_separator('pixel_trans.gif', '100%', '5'); ?></td>
			</tr>
  			 <tr>
     			<td valign=top >
					<div id="create_order_details_show">
					<?php  require(DIR_WS_MODULES . 'create_order_details.php');?>
					</div>
     			</td>
		   </tr>
		   <tr>
				 <td class=contenttitle><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
		  </tr>
		  <tr><td>&nbsp;</td></tr>
		   <tr>
			 <td align="right" nowrap>
			 	 <?php 
					if($error)
						echo '<a href="' . tep_href_link(FILENAME_CUSTOMERS, 'page='. (int)$HTTP_GET_VARS['page'] . '&cID=' . (int)$HTTP_GET_VARS['cID'] , 'SSL') . '">' . tep_image_button('button_cancel.gif',IMAGE_CANCEL) . '</a>';
					else
						echo '<a href="javascript:do_page_fetch(\'update_customer\');">' .  tep_image_button('button_continue.gif', IMAGE_CONTINUE,'name="button_confirm1" id="button_confirm1"') . '</a>'; 
					 ?>
				</td>
		    </tr>
		  </table></form>
<?php } ?>
<?php 
function out_product_details($add_product_products_id)
{
global $currencies,$JS_DETAILS;

			// changes from(N)
			print "<table width='100%' border='0'><tr><td width=145></td><td>";
			$pro_query=tep_db_query("select products_price,products_tax_class_id,products_quantity,is_attributes,product_type,products_price_break from " . TABLE_PRODUCTS . " where products_id='" . (int)$add_product_products_id . "'");
			$product=tep_db_fetch_array($pro_query);
			$tax_rate=tep_get_tax_rate($product["products_tax_class_id"]);
			$quantity_is_combobox = false;
			if ($new_price = tep_get_products_spl_price($add_product_products_id)) {
			  $products_dprice = '<s>' . $currencies->display_price($product['products_price'], $tax_rate,'1',true) . '</s> <font color="red">' . $currencies->format(tep_add_tax($new_price, $tax_rate)) . '</font>';
			  $pro_total=tep_add_tax($new_price, $tax_rate);
			  $products_original_price=$new_price;
			  $products_total_price=$currencies->format(tep_add_tax($new_price, $tax_rate));
			} else {
			  $products_dprice = $currencies->display_price($product["products_price"], $tax_rate,'1',true);
			  $pro_total=tep_add_tax(tep_get_plain_products_price($product["products_price"]), $tax_rate);
			  $products_original_price=$product["products_price"];
			  $products_total_price=$currencies->format(tep_add_tax($product["products_price"], $tax_rate));
			}

    $product_to_categories_query = tep_db_query("select categories_id from " . TABLE_PRODUCTS_TO_CATEGORIES . " where products_id = '" . $add_product_products_id . "'");
    $product_to_categories = tep_db_fetch_array($product_to_categories_query);
    $category_id = $product_to_categories['categories_id'];

			$special_price=$new_price;
			print "<table width=100% cellpadding=1>";

			if ($product["products_price_break"]!="Y"){
				$products_price_break_sql = "select * from " . TABLE_PRODUCTS_PRICE_BREAK . " ppb where products_id = '" . (int)$add_product_products_id . "'";
				$products_price_break_query = tep_db_query($products_price_break_sql);
				if(tep_db_num_rows($products_price_break_query) > 0){
					$quantity_is_combobox = true;
					$pro_total=tep_add_tax($product["products_price"], $tax_rate);
					$products_dprice=$currencies->format($pro_total);
				}
			    print "<tr ><td align='left' class='dataTableContent'><b>Price:</b></td><td align='left' class='smalltext' colspan='2'>&nbsp;" . $products_dprice;
				print "</td></tr>";
			}	  
			/*if(tep_db_num_rows($products_price_break_query) > 0){
			print "<table width=100% cellpadding=1>";
				 $pro_total=tep_add_tax($product['products_price'],$tax_rate);
				$quantity_is_combobox = true;
			}else if($tax_rate!=0 && $add_product_products_id!="" && $add_product_products_id > 0){
				print "<table width=100% cellpadding=1>";
				$discount_price=tep_get_products_discount_price($product["products_price"],$order_result['customers_id']);
				$special_price=tep_get_products_special_price($add_product_products_id,$order_result['customers_id']);
				if ($special_price){
				  $pro_total=tep_add_tax($discount_price,$tax_rate);
				  print "<tr ><td align='left' class='dataTableContent'><b>Price:</b></td><td align='left' class='smalltext' colspan='2'>&nbsp;<s>" . $currencies->format(tep_add_tax($discount_price,$tax_rate)) . "</s>&nbsp;&nbsp;<font color='red'>" . $currencies->format(tep_add_tax($special_price,$tax_rate)) . "</font>";
				  print "</td></tr>";
				} else {
					 $pro_total=tep_add_tax($discount_price,$tax_rate);
				//  print "<table width=100% cellpadding=1>";  
				  print "<tr ><td align='left' class='dataTableContent'><b>Price:</b></td><td align='left' class='smalltext' colspan='2'>&nbsp;" . $currencies->format(tep_add_tax($discount_price,$tax_rate));
				  print "</td></tr>";
				}
			}else if($add_product_products_id!="" && $add_product_products_id > 0) {
				print "<table width=100% cellpadding=1>";
				$pro_query=tep_db_query("select products_price,products_tax_class_id from " . TABLE_PRODUCTS . " where products_id='" . (int)$add_product_products_id . "'");
				$res_query=tep_db_fetch_array($pro_query);
				$discount_price=tep_discount_price($add_product_products_id,$res_query['products_price'],tep_get_tax_rate($res_query['products_tax_class_id']),$order_result['customers_id']);
				if($discount_price['text']==0){
				 $pro_total=abs($res_query['products_price']);
				  print "<tr ><td align='left' class='dataTableContent'><b>Price:</b></td><td align='left' class='smalltext' colspan='2'>&nbsp;" . $currencies->format(abs($res_query['products_price']));
				  print "</td></tr>";
				}else if($discount_price['id']=='GD'){
				 $pro_total=$discount_price['text'];
				  print "<tr ><td align='left' class='dataTableContent'><b>Price:</b></td><td align='left' class='smalltext' colspan='2'>&nbsp;" . $currencies->format($discount_price['text']);
				  print "</td></tr>";
				}else if($discount_price['text']>0 && $discount_price['id']=='SP') {
				 $pro_total=abs($res_query['products_price']);
				  print "<tr ><td align='left' class='dataTableContent'><b>Price:</b></td><td align='left' class='smalltext' colspan='2'>&nbsp;<s>" . $currencies->format(abs($res_query['products_price'])) . "</s>&nbsp;&nbsp;<font color='red'>" . $currencies->format($discount_price['text']) . "</font>";
				  print "</td></tr>";
				}
			}	*/
			
			print "<input type='hidden' id='txt_price' name='txt_price' value='" .$products_original_price . "'>"; 
			print "<input type='hidden' id='txt_tax' name='txt_tax' value='" .$product["products_tax_class_id"] . "'>"; 
			print "<input type='hidden' id='product_stock' name='product_stock' value='" .tep_get_products_stock($add_product_products_id) . "'>"; 
			//PSP
			if($product['product_type']=='S') {
				print "<tr><td colspan='3'>" . tep_draw_separator('pixel_trans.gif','5','5') . "</td></tr>\n";
				print "<tr><td colspan='3'>" . tep_show_support_packs($add_product_products_id) . "</td></tr>";
			}
			print "<tr><td colspan='3'>" . tep_draw_separator('pixel_trans.gif','5','5') . "</td></tr>\n";
			print "<tr><td class='dataTableContent' align='right' valign=top width=1% nowrap>
			<table width='100%' border='0'>
				<tr><td class='dataTableContent' align='left' valign=top nowrap>
				<b>STEP 2:</b>
				</td></tr>
			</table></td><td colspan='2'><table cellpadding='2' cellspacing='2' borer='0' width='100%'>";
			
			if($quantity_is_combobox){
				$out_of_stock=tep_check_stock($add_product_products_id, 0);
				if($out_of_stock==""){
					//if(tep_db_num_rows($result) > 0)print "</td><td height='20'></td></tr></table>";
					print "<tr><td colspan='3'><br>";
					print "<div style='border:1px solid #93AAEE;align:left;width:150px;height:100px;overflow:auto;'>";
					print "<table width='100%' cellpadding='1' cellspacing='1'  id='tablePriceBreaks'>";
					print  product_prices($add_product_products_id);
					print "</table></div></td></tr>";
				}
				print "<input type='hidden' id='qty' name='qty' value=''>";
			}else{ $qty=1;
				print "<tr >";
				print "<td class='dataTableContent' align='' width=10%><b>Quantity</b></td>";
				print "<td class='' valign='top' colspan='2'>";
				print "<input name='qty' size='2' id='qty' value='" . $qty . "' class='inputnormal' onkeyup='quanAutoCheck();' onblur=\"javascript:checkStock('');\" onKeyDown=\"javascript:return numericOnly(event);\"> </td>";
				print "</tr>";
			}
			$JS_DETAILS['SALEMAKER_DATAS']='{enabled:false}';
				if ($product["products_price_break"]!="Y"){
					$has_option="";
					if ($special_price) $has_option=" and sale_specials_condition!=1";
					$sDate=getServerDate(true);
					//check for product_discount price
					$sale_query = tep_db_query("select sale_id,sale_specials_condition, sale_deduction_value, sale_deduction_type,choice_text,choice_warning from " . TABLE_SALEMAKER_SALES . " where sale_discount_type='C' " . $has_option . " and ((sale_categories_all='' and sale_products_selected='') or sale_categories_all like '%," . tep_db_input($category_id) . ",%' or sale_products_selected like '%," . tep_db_input($add_product_products_id) .",%') and sale_status = '1' and (sale_date_start <='" . $sDate . "' or sale_date_start = '0000-00-00') and (sale_date_end >= '" . $sDate . "' or sale_date_end = '0000-00-00') and (sale_pricerange_from <= " . $product['products_price'] . " or sale_pricerange_from = '0') and (sale_pricerange_to >= " . $product['products_price'] . " or sale_pricerange_to = '0') order by sale_deduction_value");
					if (tep_db_num_rows($sale_query)>0){
		
						echo '<tr><td class="main" colspan="3"><b>' . TEXT_SELECT_SALEMAKER_DISCOUNT . '<b></td></tr>';
						echo '<tr><td colspan="3"><table border="0" cellpadding="1" cellspacing="0">';
						$JS_DETAILS['SALEMAKER_DATAS']='{enabled:true,sales:{';
						
						echo '<tr><td class="main"  width="30">' . tep_draw_radio_field('salemaker_id',-1,true,'','id="salemaker_id" onClick="javascript:selectDiscount(0);"') . '</td><Td class="main">' . TEXT_NO_DISCOUNT . '</td></tr>';
						while($sale=tep_db_fetch_array($sale_query)){
							$JS_DETAILS['SALEMAKER_DATAS'].=$sale["sale_id"] . ":{price:";
							switch($sale['sale_deduction_type']){
								case 1:
									$choice_text=$sale["choice_text"] . " (" . number_format($sale["sale_deduction_value"],2). "%)";
									break;
								case 2:
									$choice_text=$sale["choice_text"] . " (<s><font color='red'>" . $currencies->format(tep_add_tax($products_original_price, $tax_rate)) . "</font></s>&nbsp;" . $currencies->format($sale["sale_deduction_value"], $tax_rate) . ")";
									break;
								default:
									$choice_text=$sale["choice_text"] . " (" . $currencies->format($sale["sale_deduction_value"],$tax_rate). ")";
									break;
								
							}
							//$pro_total=tep_add_tax(tep_get_salemaker_price($special_price,$products_original_price,$sale),$tax_rate);
							$JS_DETAILS['SALEMAKER_DATAS'].=tep_add_tax(tep_get_salemaker_price($special_price,$product["products_price"],$sale),$tax_rate) . ",warning:'" .htmlspecialchars($sale["choice_warning"]) . "'},";
							echo '<tr><td class="main">' .  tep_draw_radio_field('salemaker_id',$sale["sale_id"],false,'',' onClick="javascript:selectDiscount(' . $sale["sale_id"] . ');"')  . '</td><Td class="main">' . $choice_text  . '</td></tr>';
						}
						$JS_DETAILS['SALEMAKER_DATAS']=substr($JS_DETAILS['SALEMAKER_DATAS'],0,-1) . "}}";
					}
					echo '</table><td></tr><tr>
						<td class="main" colspan="3">
							<div  style="display:none;background:#E84A92;color:#FFFFFF;padding:1px 5px 1px 5px" id="salemaker_info">
							</div>	
						</td>
					</tr>';
					print "<input type='hidden' id='price_breaks' name='price_breaks' value='0'>"; 
				}
				else print "<input type='hidden' id='price_breaks' name='pricebreaks' value='1'>"; 
			print "<input type='hidden' id='product_price' name='product_price' value='" . $pro_total . "'>"; 
			print '<tr><td class="main" colspan="3"><span id="stockProductQuan" style="display:none"><b>Checking Stock...</b></span></td></tr>';
			if($product['is_attributes']=='Y') {
				$pattributes='';
				$pattr_array=tep_get_products_attributes($add_product_products_id);
				
				print '<tr><td colspan="3"><table cellpadding="2" cellspacing="2" border="0" width="100%">';
				for($acnt=0,$an=count($pattr_array);$acnt<$an;$acnt++){
					$arr_element=$pattr_array[$acnt];
					print '<tr><td class="dataTableContent" width="150"><b>' . $arr_element['name'] . '</b></td><td class="dataTableContent" width="200">' . $arr_element['value'] . '</td><td class="dataTableContent"><b>' . $arr_element['price'] . '</b></td></tr>';
				}
				print '</table></td></tr>';
				print '<tr><td class="main" colspan="3"><span id="stockAttrQuan" style="display:none"><b>Checking Stock...</b></span></td></tr>';
			}	
			print '<tr><td class="main" colspan="3"><span id="outstock" style="display:none;color:#ff0000" >The product is not currently in Stock.</span></td></tr>';
			print "<tr><td colspan='3'>&nbsp;</td></tr>\n";
			print "<tr><td class='dataTableContent' align='center' colspan='3'><b>Total Price: " .'<span id="totalProductsPrice">' . $products_dprice ."</span></td></tr>";
			print "</table></td></tr>";
			print "</table></td></tr>\n";
			print "</table>\n";
}
?>
<?php
  function tep_get_country_id($country_name) {
    $country_id_query = tep_db_query("select * from " . TABLE_COUNTRIES . " where countries_name = '" . tep_db_input($country_name) . "'");
    if (!tep_db_num_rows($country_id_query)) {
      return 0;
    }
    else {
      $country_id_row = tep_db_fetch_array($country_id_query);
      return $country_id_row['countries_id'];
    }
  }
  function tep_get_zone_id($country_id, $zone_name) {
    $zone_id_query = tep_db_query("select * from " . TABLE_ZONES . " where zone_country_id = '" . (int)$country_id . "' and zone_name = '" . tep_db_input($zone_name) . "'");
    if (!tep_db_num_rows($zone_id_query)) {
      return 0;
    }
    else {
      $zone_id_row = tep_db_fetch_array($zone_id_query);
      return $zone_id_row['zone_id'];
    }
  }
  function tep_html_quotes($string) {
    return str_replace("'", "&#39;", $string);
  }
  
  function out_subscription_details($post_subscription_id)
  {
  	global $languages_id,$currencies;
	  //subscription type
	  $type_array=array('B'=>TEXT_SUBSCRIPTION_BASIC,
					'C'=>TEXT_SUBSCRIPTION_CASUAL,
					'S'=>TEXT_SUBSCRIPTION_SEASONAL
					);
		  	$split_date_format = split("-",EVENTS_DATE_FORMAT);
			$database_date_format = '';
			for($i=0;$i<sizeof($split_date_format);$i++){
				$database_date_format .= "%" . $split_date_format[$i];
				if($i!=(sizeof($split_date_format)-1))
					$database_date_format .= "-";
			}
			if($database_date_format=='')$database_date_format='%d-%m-%Y';
			if($post_subscription_id==0){
				print "<tr><td class='dataTableContent'>" . TEXT_ERR_SUBSCRIPTION_GET . "</td></tr>";
			} else if($post_subscription_id!=0){
				$att_period_query = tep_db_query("select subscription_period,deliveries_perday from " . TABLE_SUBSCRIPTIONS . " where subscription_id = '" . (int)$post_subscription_id . "'");
				$att_period_result = tep_db_fetch_array($att_period_query);
				$period_value = $att_period_result['subscription_period'];
				$deliveries_perday = $att_period_result['deliveries_perday'];
				if($att_period_result['subscription_period'] > 0)
				$period_value -= 1;
				if($att_period_result['deliveries_perday'] > 0)
				$deliveries_perday -= 1;
				print "<table width=100% cellpadding=5><tr >\n";
				// get the costs and type for selected option from list
				$cos_and_type_sql = "select su.subscription_id,su.deliveries,su.deliveries_name, sud.subscription_name, sud.subscription_description, su.subscription_image, sud.subscription_url, su.subscription_costs, su.subscription_tax_class_id, su.subscription_date_added, su.subscription_date_available, " .
											" su.subscription_free_trial,su.subscription_free_days,su.deliveries_perday, " .
											" date_format(date_sub(date_format(su.subscription_finish_date,'%Y-%m-%d'),INTERVAL " . $deliveries_perday . " DAY),'" . $database_date_format . "') as deliveries_perday_date, " .
											"su.subscription_type,su.subscription_conditions,su.subscription_start_date,date_format(su.subscription_start_date,'" . $database_date_format . "') as display_start_date, " .
											" date_format(su.subscription_finish_date,'" . $database_date_format . "') as display_finish_date, " . 
											" subscription_finish_date,su.subscription_period,su.subscription_date_type,su.subscription_latest_start_date, " .
											" date_format(su.subscription_latest_start_date,'" . $database_date_format . "') as display_latest_start_date " .
											" from " . TABLE_SUBSCRIPTIONS . " su, " . TABLE_SUBSCRIPTIONS_DESCRIPTION . " sud where su.subscription_status = '1' and su.subscription_id = '" . (int)$post_subscription_id . "' and sud.subscription_id = su.subscription_id and sud.language_id = '" . (int)$languages_id . "'";
				//echo $cos_and_type_sql;
				$cos_and_type=tep_db_query($cos_and_type_sql);
				//$cos_and_type=tep_db_query("select * from " . TABLE_SUBSCRIPTIONS . " su," . TABLE_SUBSCRIPTIONS_DESCRIPTION . " sud where su.subscription_id=sud.subscription_id and su.subscription_status='1' and su.subscription_id='" .$subscriptions_id . "'");
				$cos_and_type_value=tep_db_fetch_array($cos_and_type);
				if(isset($cos_and_type_value['subscription_type']) && tep_not_null($cos_and_type_value['subscription_type']) && isset($cos_and_type_value['subscription_costs']) && $cos_and_type_value['subscription_costs']!=''){
					if($cos_and_type_value['subscription_type'])
						$type=$type_array[$cos_and_type_value['subscription_type']];
					if($cos_and_type_value['subscription_type']=='C' || $cos_and_type_value['subscription_type']=='S'){
						$deliveries=$cos_and_type_value['deliveries'];
						$deliveries_name=$cos_and_type_value['deliveries_name'];
					}
					if($cos_and_type_value['subscription_type']=='C')
						$deliveries_perday=$cos_and_type_value['deliveries_perday'];	

					if($cos_and_type_value['subscription_type']=='C' && $deliveries && $deliveries_perday && $cos_and_type_value['subscription_date_type'] == 'F')
						 $subscription_details=sprintf(TEXT_SUBSCRIPTION_CASUAL_PER_FIXED,$deliveries,$deliveries_name,int_to_words($deliveries_perday),$cos_and_type_value['display_start_date'],$cos_and_type_value['display_finish_date']);
					else if($cos_and_type_value['subscription_type']=='C' && $deliveries && $deliveries_perday && $cos_and_type_value['subscription_date_type'] == 'L')
						 $subscription_details=sprintf(TEXT_SUBSCRIPTION_CASUAL_PER_FLEXIBLE,$deliveries,$deliveries_name,int_to_words($deliveries_perday),$cos_and_type_value['subscription_period'],$cos_and_type_value['display_start_date'],$cos_and_type_value['display_finish_date']);
					else if($cos_and_type_value['subscription_type']=='C' && $deliveries && $deliveries_perday && $cos_and_type_value['subscription_date_type'] == 'P')
						 $subscription_details=sprintf(TEXT_SUBSCRIPTION_CASUAL_PER_PREDEFINED,$deliveries,$deliveries_name,int_to_words($deliveries_perday),$cos_and_type_value['subscription_period'],$cos_and_type_value['display_start_date'],$cos_and_type_value['display_finish_date']);
				
					else if($cos_and_type_value['subscription_type']=='S' && $deliveries && $cos_and_type_value['subscription_date_type'] == 'F') 
						$subscription_details=sprintf(TEXT_SUBSCRIPTION_SEASON_DELIVERIES_FIXED,$deliveries,$deliveries_name,$cos_and_type_value['display_start_date'],$cos_and_type_value['display_finish_date']);
					else if($cos_and_type_value['subscription_type']=='S' && $deliveries && $cos_and_type_value['subscription_date_type'] == 'L') 
						$subscription_details=sprintf(TEXT_SUBSCRIPTION_SEASON_DELIVERIES_FLEXIBLE,$deliveries,$deliveries_name,$cos_and_type_value['subscription_period'],$cos_and_type_value['display_start_date'],$cos_and_type_value['display_finish_date']);
					else if($cos_and_type_value['subscription_type']=='S' && $deliveries && $cos_and_type_value['subscription_date_type'] == 'P') 
						$subscription_details=sprintf(TEXT_SUBSCRIPTION_SEASON_DELIVERIES_PREDEFINED,$deliveries,$deliveries_name,$cos_and_type_value['subscription_period'],$cos_and_type_value['display_start_date'],$cos_and_type_value['display_finish_date']);
				
					else if($cos_and_type_value['subscription_type']=='B' && $cos_and_type_value['subscription_date_type'] == 'F') 
						$subscription_details=sprintf(TEXT_SUBSCRIPTION_BASIC_DELIVERIES_FIXED,$cos_and_type_value['display_start_date'],$cos_and_type_value['display_finish_date']);
					else if($cos_and_type_value['subscription_type']=='B' && $cos_and_type_value['subscription_date_type'] == 'L') 
						$subscription_details=sprintf(TEXT_SUBSCRIPTION_BASIC_DELIVERIES_FLEXIBLE,$cos_and_type_value['subscription_period'],$cos_and_type_value['display_start_date'],$cos_and_type_value['display_finish_date']);
					else if($cos_and_type_value['subscription_type']=='B' && $cos_and_type_value['subscription_date_type'] == 'P') 
						$subscription_details=sprintf(TEXT_SUBSCRIPTION_BASIC_DELIVERIES_PREDEFINED,$cos_and_type_value['subscription_period'],$cos_and_type_value['display_start_date'],$cos_and_type_value['display_finish_date']);
					if($cos_and_type_value['subscription_costs']){
						$costs=$cos_and_type_value['subscription_costs']; 
					}
				}
				if($cos_and_type_value['subscription_costs']>0){
					echo '<input type="hidden" name="start_date" id="start_date" value="' . $cos_and_type_value['subscription_start_date'] . '">';
					echo '<input type="hidden" name="display_start_date" id="display_start_date" value="' . $cos_and_type_value['display_start_date'] . '">';
					
					echo '<input type="hidden" name="finish_date" id="finish_date" value="' . $cos_and_type_value['subscription_finish_date'] . '">';
					echo '<input type="hidden" name="display_finish_date" id="display_finish_date" value="' . $cos_and_type_value['display_finish_date'] . '">';
					
					echo '<input type="hidden" name="latest_start_date" id="latest_start_date" value="' . $cos_and_type_value['subscription_latest_start_date'] . '">';
					echo '<input type="hidden" name="display_latest_start_date" id="display_latest_start_date" value="' . $cos_and_type_value['display_latest_start_date'] . '">';
						
					echo '<input type="hidden" name="subscription_date_type" id="subscription_date_type" value="' . $cos_and_type_value['subscription_date_type'] . '">';
					echo '<input type="hidden" name="subscription_period" id="subscription_period" value="' . $cos_and_type_value['subscription_period'] . '">';
					echo '<input type="hidden" name="subscription_type" id="subscription_type" value="' . $cos_and_type_value['subscription_type'] . '">';
					echo '<input type="hidden" name="deliveries_perday" id="deliveries_perday" value="' . $cos_and_type_value['deliveries_perday'] . '">';
					echo '<input type="hidden" name="deliveries_perday_date" id="deliveries_perday_date" value="' . $cos_and_type_value['deliveries_perday_date'] . '">';
					
					echo '<input type="hidden" name="currend_date" id="currend_date" value="' . date(EVENTS_DATE_FORMAT) . '">';
					
					print "<td class='dataTableContent' align='left' width=5% nowrap>";
					//print "<table><tr><td class='dataTableContent' align='left'>";
					print "<b>" . TEXT_SUBSCRIPTION_COSTS . "</b></td>";
					print "<td class='dataTableContent' align='left'>";
					print $currencies->format($costs);
					print "</td></tr>";
					print "<tr ><td class='dataTableContent' align='left'>";
					print "<b>" . TEXT_SUBSCRIPTION_TYPE . "</b></td>";
					print "<td class='dataTableContent' align='left'>";
					print $type . "</td></tr>";
					if(($cos_and_type_value['subscription_type']=='S' && $cos_and_type_value['subscription_date_type']!='F') || $cos_and_type_value['subscription_type']=='B'){
					?>
					  <tr >
						<td class="smallText" valign="top" nowrap>
								<?php echo '<b>' . TEXT_SUBSCRIPTION_PERIOD . '</b>';?>
						</td>
						<td class="smallText" valign="top">
							<?php echo $cos_and_type_value['subscription_period'] . '&nbsp;' . TEXT_DAYS;?>
						</td>
					  </tr>
					  <?php
							}
					 ?>
					  <tr >
						<td class="smallText" valign="top" colspan="2" nowrap><?php echo $subscription_details;?></td>
					  </tr>
					  <?php  if($cos_and_type_value['subscription_date_type']=='P'){?>
					  <tr >
						<td valign="top" colspan="2">
						<table width="100%" cellpadding="0" cellspacing="0" border="0">
							<tr>
							<td valign="top" class="smallText">
							<?php 
								$_array=array('d','m','Y');  $replace_array=array('DD','MM','YYYY'); 	
								$date_format=str_replace($_array,$replace_array,EVENTS_DATE_FORMAT);
								echo TEXT_ENTER_YOUR_SUBSCRIBE_DATE . '&nbsp;';
								echo tep_draw_input_field("your_start_date",date(EVENTS_DATE_FORMAT)," size=10 id='your_start_date' onblur='check_date()'",false,'text',false);
							?>
							<a href="javascript:show_calendar('add_new_subscription.your_start_date',null,null,'<?php echo $date_format;?>');"
							   onmouseover="window.status='Date Picker';return true;"
							   onmouseout="window.status='';return true;" onBlur="check_date()"><img border="none" src="images/icon_calendar.gif"/>  
							</a>
							<?php echo '<input type="hidden" name="to_date" id="to_date" value="" size="10" align="left" disabled="true">';?>
							</td>
						</tr>
						</table>
					  </tr>
						<?php 
							} else{
								echo '<input type="hidden" name="your_start_date" id="your_start_date" value="' . date(EVENTS_DATE_FORMAT) . '">';
							}
						?>
					  <tr>
						<td colspan="2"><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
					  </tr>
					 <?php 
				}
		}
	print "</table>\n";
  }
  function out_event_details($events_id,$show_period,$override,$overbook,$no_attendees)
  { 
  	global $languages_id,$currencies,$events_result,$customer_id,$cart;
	$multiple_attendees=false;
	if ($events_id>0){
		$events_sql="select events_id,sessions_select_count,sessions_select_interval,sessions_date_count,events_forward_period,events_forward_length,events_max_reserve,events_overbook_reserve,waitsize_vip,waitsize_firstcome,
										waitsize_custom,priority_question,events_tax_class_id,session_style,events_fees,waitfee_vip,waitfee_firstcome,waitfee_custom,events_pending_period,session_style,session_reduction,session_gaps,events_wait_list,events_renewal_start,events_renewal_end,events_group_bookings,events_group_min,events_group_max from " . TABLE_EVENTS . " where events_id='" . (int)$events_id . "'";
		//echo $events_sql;
		$events_query = tep_db_query($events_sql);
		$events_result=tep_db_fetch_array($events_query);
		//print_r($events_result);
		//echo $events_result['events_overbook_reserve'];
		//multiple attendees
		if($events_result['events_group_bookings'] =='Y')
			$multiple_attendees=true;
		}
	?>
<Table width=100%>
 <tr>
	<td colspan="2"><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
  </tr>
<?php 
	if($multiple_attendees){
		$attendees_array = array();
		if($events_result['events_group_min']!=1 && $events_result['events_group_min']>0) $attendees_array[]= array('id'=>1,'text'=>1);
		for($icnt=$events_result['events_group_min'];$icnt<=$events_result['events_group_max'];$icnt++)
		  if($icnt) $attendees_array[]=array('id' =>$icnt,'text' =>$icnt);
	?>
	<tr valign="middle">
		<td class="dataTableContent" align=left height="20"><b><?php echo EVENT_STEP2; ?></b></td>
	</tr>
	  <tr>
		<td colspan="2"><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
	  </tr>
	<tr>
		<td>
		<table border="0" cellpadding="0" cellspacing="0">
		<tr >
			<td valign="middle" class="main">
				<?php 
					echo TEXT_MULTIPLE_ATTENDEES . '&nbsp;&nbsp;' . tep_draw_pull_down_menu('no_attendees',$attendees_array) .'&nbsp;';
				?>
			</td>
			<td class="main" valign="middle">
				<?php
					echo '<a href="javascript:do_page_fetch(\'new_event_step3\');">' . tep_image_button("button_select.gif",IMAGE_SELECT_EVENT,'valign="middle"') . "</a>";
				?>
				<span id="event_process_show2" style="display:none"><?php echo tep_image(DIR_WS_IMAGES . '24-1.gif');?></span>
			</td>
		</tr>
		  <tr>
			<td colspan="2"><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
		  </tr>
		</table>
		</td>
	</tr>
<?php 	
	}
	else
		$show_period=true;
	if($show_period)
	{
	$cnt=0;
	$no_attendees=$no_attendees;
	// fetch event details
		// fetch question details for the current event if present
		$question_query=tep_db_query("SELECT q.question_title,q.question_description,q.answer_type,q.question_id from " . TABLE_EVENTS . " e, " . TABLE_POP_QUESTIONS .  " q where e.events_id='" . (int)$events_id . "' and q.question_id=e.priority_question");
		$question_count=tep_db_num_rows($question_query);
		$question_confirm="";
		if ($question_count>0){
			$question_result=tep_db_fetch_array($question_query);
			$question_result_error=sprintf(ERR_INVALID_ANSWER,$question_result["question_title"]);
			

			// found already this user had answered the question
			$answer_query=tep_db_query("SELECT oa.answer_value,oa.answer_type from " . TABLE_EVENTS . " e," . TABLE_ORDERS_EVENTS_ANSWERS . " oa " . 
										" where oa.orders_id='" . (int)$oId . "' and oa.events_id=e.events_id and e.priority_question='" . (int)$question_result["question_id"] .
										"' limit 1"
										);
										
			if (tep_db_num_rows($answer_query)>0){
				$answer_result=tep_db_fetch_array($answer_query);
				if ($answer_result["answer_type"]=="D") {
					$question_confirm=date("F|d|Y",strtotime($answer_result["answer_value"]));
				} else {
					$question_confirm=$answer_result["answer_value"];
				}
			}
		}
	
	// get session details
	$session_type=tep_get_session_type((int)$events_id);
	$session_array = array();
		
	$add_option="";
	if ($events_result['events_forward_period']=='Y'){
		$check_date=date('Y-m-d',tep_dateadd(time(),'day',(int)$events_result['events_forward_length']));
		$add_option=" and start_date<='" . $check_date . "' ";
	}
	// check for overbook function 
	$lock_date=false;
	$dates_array=array();
	// get the previous two day results
	if ($session_type=='S') {
		$start_option=" and start_date>curdate() ";
	} else {
		$start_option=" and start_date>curdate() ";
		$two_dates_query=tep_db_query("SELECT start_date,sessions_id,recursive_sessions_id from " . TABLE_EVENTS_SESSIONS . " where events_id='" . (int)$events_id . "' and start_date<=curdate() and sessions_type!='' order by start_date desc limit 2");

		$icnt=tep_db_num_rows($two_dates_query)-1;
		while($two_dates_result=tep_db_fetch_array($two_dates_query)){
			// if the mode is "edit" check for placing the already added date
			if ($edit_mode && isset($edit_dates[$two_dates_result["sessions_id"]])){
				$selected_mode=true;
				$temp_date=$edit_dates[$two_dates_result["sessions_id"]];
				$status=$temp_date["type"];
				$group=$temp_date["waitlist_type"];
			} else {
				$selected_mode=false;
				$status='E';
				if ($status=='E' && tep_check_session_free($two_dates_result,$events_result,'R',$customer_id,$override,$overbook,$no_attendees)) {
					$status='R';
				}
				$group=tep_find_waitlist_group($events_id,$two_dates_result['sessions_id'],$customer_id,$events_result,$no_attendees);
				if ($group=='E') $group="";
				else if ($status=='E') $status="W";
			}	
			//echo $status.'<br>';								
				$dates_array[$icnt] = array(	'id' => $two_dates_result['sessions_id'],
												'date'=> $two_dates_result['start_date'],
												'group'=>$group,
												'locked'=>$lock_date,
												'bgcolor'=>0,
												'selected'=>$selected_mode,
												'recursive_id'=>$two_dates_result['recursive_sessions_id'],
												'type'=> $status);
			$icnt--;
		}
	}
	
	$tax_rate=tep_get_tax_rate($events_result['events_tax_class_id']);
	// get other dates
		$date_query=tep_db_query("SELECT start_date,sessions_id,recursive_sessions_id from " . TABLE_EVENTS_SESSIONS  .  " where events_id='" . (int)$events_id . "'" . $start_option . $add_option . " and sessions_type!='' order by start_date");
		
		while($date_result = tep_db_fetch_array($date_query))
		{
			$status='E';
			$group='';
			if ($edit_mode && isset($edit_dates[$date_result["sessions_id"]])){
				$selected_mode=1;
				$temp_date=$edit_dates[$date_result["sessions_id"]];
				$status=$temp_date["type"];
				$group=$temp_date["waitlist_type"];
			} else {
				$selected_mode=0;
				//check for reservation seats
				//$seats_available = tep_check_session_free($date_result,$events_result,'R',$customer_id,$override,$overbook,$no_attendees);
				/*if(substr($seats_available,0,6)=='A_full') {
					echo "<td class='main'>". TEXT_NO_ADDITIONAL_SEATS ."</td>";
					return; 
				}
				if(substr($seats_available,0,6)=='P_full'){ 
					echo "<td class='main'>".TEXT_PARTLY_FULL . '&nbsp;&nbsp;'." Avilable Attendees <b>" . substr($seats_available,6) ."</b> only </td>" ;
					return;
				}*/
				if ($status=='E' && tep_check_session_free($date_result,$events_result,'R',$customer_id,$override,$overbook,$no_attendees)) {
					$status='R';
				}
				// check for waitlist seats
				$group=tep_find_waitlist_group($events_id,$date_result['sessions_id'],$customer_id,$events_result,$no_attendees);
				if ($group=='E') $group="";
				else if ($status=='E') $status="W";	
				
				if ($status!='E' && $sessions_id==0) $sessions_id=$date_result['sessions_id'];
			}
		
			$dates_array[] = array(	'id' => $date_result['sessions_id'],
									'date'=> $date_result['start_date'],
									'recursive_id'=>$date_result['recursive_sessions_id'],
									'locked'=>$lock_date,
									'selected'=>$selected_mode,
									'bgcolor'=>1,
									'type'=> $status,
									'group'=>$group);
		}
		
		// get the recursive ids
		$cnt=0;
		$recursive_array=array();
		$prev_recursive=0; 
		for ($icnt=0;$icnt<sizeof($dates_array);$icnt++){
			$color="#FF0000";
			if ($dates_array[$icnt]['locked']) $color="#668DE3";
			else if ($dates_array[$icnt]['type']=='R') $color="#000000";
			else if ($dates_array[$icnt]['type']=='W') $color="FFA715";
			$session_array[] = array('id' => $dates_array[$icnt]['id'],
									'date'=> $dates_array[$icnt]['date'],
									'type'=> $dates_array[$icnt]['type'],
									'group'=> $dates_array[$icnt]['group'],
									'selected'=>$dates_array[$icnt]['selected'],
									'bgcolor'=>$dates_array[$icnt]['bgcolor'],
									'text' => sprintf("<font color=\"%s\">%s</font>",$color,format_date($dates_array[$icnt]['date']))
									);
			$cnt++;
			if ($session_type=='R' && $prev_recursive!=$dates_array[$icnt]['recursive_id']){
				$prev_recursive=$dates_array[$icnt]['recursive_id'];
				$recursive_array[]=$prev_recursive;
			}
		}
	if($sessions_id > 0){
		$session_query=tep_db_query("SELECT start_date FROM " . TABLE_EVENTS_SESSIONS . " where sessions_id='" . tep_db_input($sessions_id) . "'");
		$session_result = tep_db_fetch_array($session_query);
		$start_date=$session_result['start_date'];
		$events_result['start_date']=$start_date;
	}
	// get the gap dates
	if ($session_type=='R' && sizeof($recursive_array)>0){
			$result_array=get_gap_dates_array($recursive_array);
			if (sizeof($result_array)>0){
				for ($icnt=0;$icnt<sizeof($result_array);$icnt++){
					$session_array[]=array('date'=>$result_array[$icnt],'selected'=>0,'type'=>'H','group'=>'','text'=>sprintf("<font color=\"%s\">%s</font>","#000000",format_date($result_array[$icnt]) . '&nbsp;&nbsp;' . TEXT_NOTIFY_HOLIDAY));
				}
				usort($session_array,"user_compare");
			}
		
	}
	$sessions_count=isset($HTTP_POST_VARS["sessions_count"])?(int)$HTTP_POST_VARS["sessions_count"]:0;
	
//	$sessions_count=(isset($HTTP_POST_VARS['products_qty'])?(int)$HTTP_POST_VARS['products_qty']:0);
	
	//$total_reservations = tep_get_check_free_sessions($sessions_id,1,'R',$no_attendees);
	$total_reservations = tep_get_check_free_sessions($sessions_id,1,'R',$no_attendees);

		
	//draw the script elements to form
//	print_r($dates_array);
	?>
	<tr  valign=middle height="20">
		<td class="dataTableContent" align=left><b><?php 
		if($multiple_attendees)
			 echo EVENT_STEP3;
		else 
			echo EVENT_STEP2;
	?></b></td>
	</tr>
	<tr>
		<td colspan="2" id="partly_full"></td>
	</tr>
	  <tr>
		<td colspan="2"><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
	  </tr>
	<?php if ($cnt >0) {?>
		<tr>
			<td>
			<table border="0" cellpadding="2" cellspacing="0">
				<tr valign=middle>
					<td class="dataTableContent" width="100" valign="top"><?php echo TEXT_START_DATE;?></td>
					<td class="dataTableContent" align="left" width="320"><?php echo customSessionListBox('sessions_id',$session_array,$sessions_id,"100%","220px"); ?></td>
					<td class="dataTableContent" align="left">
						<table border="0" cellpadding="3" cellspacing="0">
							<tr  id="sessions_count_row" valign="middle">
								<td class="dataTableContent" width="100"><?php echo TEXT_NO_OF_SESSIONS;?></td>
								<td class="dataTableContent" align="left" width="50"><span id="no_sessions">&nbsp;</span></td>
								<td class="dataTableContent" align="left"><?php if($no_attendees>1)  echo '<a href="javascript:do_page_fetch(\'show_attendees\');">' . tep_image_button("button_select.gif",IMAGE_SELECT_SESSION) . '</a>';
																				else echo '<a href="javascript:do_page_fetch(\'event_submit\');">' . tep_image_button("button_select.gif",IMAGE_SELECT_SESSION) . '</a>'; 
																				if($no_attendees<=1){
																				?>
																				<span id="event_process_show3" style="display:none"><?php echo tep_image(DIR_WS_IMAGES . '24-1.gif');?></span>
																				<?php } ?>
																				</td>
																			
							</tr>
							<tr>
								<td colspan="3" class="dataTableContent" align="left">
									<div id="amount_notify_r" style="visibility:hidden;"><?php echo RESERVE_FEE;?></div>
									<div id="amount_notify_w" style="visibility:hidden"><?php echo WAITLIST_FEE;?></div><p>
									<div id="amount_notify_t" style="visibility:hidden"><?php echo TOTAL_FEE;?></div>
								</td>
							</tr>
						</table>
					</td>
				</tr>
			</table>
			<?php 
					for ($icnt=0;$icnt<sizeof($session_array);$icnt++){
						if ($session_array[$icnt]['type']=='W' || $session_array[$icnt]['type']=='R'){
							echo '<input type=hidden name="select_dates[' . $session_array[$icnt]['id'] . '][type]" value="' . $session_array[$icnt]['type'] . '">';
							echo '<input type=hidden name="select_dates[' . $session_array[$icnt]['id'] . '][date]" value="' . $session_array[$icnt]['date'] . '">'; 
							echo '<input type=hidden name="select_dates[' . $session_array[$icnt]['id'] . '][group]" value="' . $session_array[$icnt]['group'] . '">';
						}
					}
					if (!$multiple_attendees){
						echo '<input type="hidden" name="no_attendees" value="1">';
					}
			?>
			<input type='hidden' name="session_type" value="<?php echo $session_type;?>">
			<input type='hidden' name="reserve_type" value="M">
			<input type="hidden" name="events_id" value="<?php echo $events_id ?>"
			<?php if ($session_type=='R') {  ?>
				<input type="hidden" name="select_interval" id="select_interval" value="<?php echo $events_result['sessions_select_interval'];?>">
				<input type="hidden" name="select_count" value="<?php echo $events_result['sessions_select_count'];?>">
				<input type="hidden" name="session_style" value="<?php echo $events_result['session_style'];?>">
				<span id="interval" style="display:none"><?php echo $events_result['sessions_select_interval'];?></span>
			<?php } else { ?>
				<input type="hidden" name="select_interval" id="select_interval" value="1">
				<input type="hidden" name="select_count" value="1">
				<input type="hidden" name="session_style" value="S">
			<?php }?>
				<input type="hidden" name="session_gaps" value="<?php echo $events_result['session_gaps'];?>">
				<input type="hidden" name="session_reduction" value="<?php echo $events_result['session_reduction'];?>">
			</td>
		</tr>
		<tr><td>&nbsp;</td></tr>
		<?php 
			$subs_query=tep_db_query("select s.subscription_id as id from " .TABLE_SUBSCRIPTIONS ." s," . TABLE_SUBSCRIPTION_TO_SUBSCRIPTION_CATEGORIES . " sc where s.subscription_id=sc.subscription_id and  s.subscription_type='M' and s.subscription_status=1");
			$subs_result=tep_db_fetch_array($subs_query);
						 if(tep_db_num_rows($subs_query)>0) {

			$order_query=tep_db_query("select o.orders_id from " .TABLE_ORDERS_PRODUCTS ." op," . TABLE_ORDERS . " o where op.orders_id=o.orders_id and o.customers_id='" . tep_db_input($customer_id) . "' and  op.products_id='" . tep_db_input($subs_result['id']) ."' and op.products_type='S'");
			$order_result=tep_db_fetch_array($order_query);
			$item_exists=false;
			$check_subs=false;
			 
			 if(tep_db_num_rows($order_query)<=0) {
				$check_subs=true;
			}	else  {
				
				if(tep_session_is_registered('order_id') ) {
					$check_subs=true;
				}
			}
			
				if($check_subs) {
				while (list($products_id, ) = each($cart->contents)) {
					if($cart->contents[$products_id]['element_type']=='S' && $products_id=$subs_result['id'])
						$item_exists=true;
				}
				if(!$item_exists) {
					//add store membership checkbox if exist
					?>
					<tr>
					<td class="main"><?php echo tep_draw_checkbox_field('store_membership_option','Y','','',' id="store_membership_option" ').' '. 'Add StoreMembership';?>
					</td>
					</tr>
					<?php
					}			
				}	
				
				
				
				}?>
		
		<?php if ($question_count>0) { // output question area 
				echo '<input type="hidden" name="question_type" value="' . $question_result["answer_type"] . '">';
		?>
					<tr valign=middle height="20">
						<td class="dataTableContent" align=left><b><?php echo $question_result["question_title"];?></b></td>
					</tr>
					<tr class="attributes-even" valign="middle">
						<td>
						<table border="0" cellpadding="2" cellspacing="0" >
							<tr valign=middle>
								<td class="main" valign="center">
								<?php echo $question_result["question_description"];?>
								</td>
								<?php echo tep_get_question_input_table($question_result["answer_type"]);?>
							</tr>
							<?php if ($question_confirm!="") { ?>
							<tr valign=middle>
								<td class="smallText" valign="center"><?php echo TEXT_ANSWER_INFO;?></td>
								<?php 
									if ($question_result["answer_type"]=="D") {
										$answer_splt=split("\|",$question_confirm);
										for ($icnt=0;$icnt<sizeof($answer_splt);$icnt++){
											echo '<td class="smallText" valign="top">' . $answer_splt[$icnt] . '</td>';
										}
									} else {
										echo  '<td class="smallText" valign="top">' . $question_confirm . '</td>';
									}
								?>
							</tr>
							<?php }?>
						</table>
						</td>
					</tr>
		
		<?php  } // question_count
				if (isset($HTTP_GET_VARS["check"])) { 
		?>
			<script language="JavaScript">
				auto_select=true; 
				selectValidDates(selectedSession)
			</script>
		<?php }
	 } else {	?>
		<tr "attributes-even" valign=middle>
			<td class="dataTableContent" height="20" align="center"><?php echo TEXT_NO_SESSIONS; ?></td>
		</tr>
	<?php  } ?>
  <tr>
	<td colspan="2"><?php echo tep_draw_separator('pixel_trans.gif', '100%', '10'); ?></td>
  </tr>
<tr class="attributes-odd">
	<td>&nbsp;</td>
</tr>
<?php } ?>
</table>
<?php 
	echo "{}selectedCount||" . $sessions_count;
	echo "{}fees_reserve||" . tep_add_tax($events_result["events_fees"],$tax_rate);
	echo "{}fees_vip||" . tep_add_tax($events_result["waitfee_vip"],$tax_rate);
	echo "{}fees_firstcome||" . tep_add_tax($events_result["waitfee_firstcome"],$tax_rate);
	echo "{}fees_custom||" . tep_add_tax($events_result["waitfee_custom"],$tax_rate);
	$jcnt=0;
	echo "{}dates_array||";
	$d_text='';
	for ($icnt=0;$icnt<sizeof($dates_array);$icnt++) { 
		$d_text.=isset($dates_array[$icnt]['id'])?$dates_array[$icnt]['id']:0;
		$d_text.='?' . $dates_array[$icnt]['type'];
		$d_text.='?' . tep_get_events_price($events_result,$dates_array[$icnt]['type'],'',$dates_array[$icnt]['date'],true);
		$d_text.='?' . $dates_array[$icnt]['bgcolor'] . "^";
	}
	echo $d_text;
  unset($session_array); 
}
function check_dates($event_id,$no_of_attendees,$type,$sessions){
	$sessions_split_array=split(",",$sessions);
	$session=array();
	$events=array();
	$events_query=tep_db_query("SELECT * FROM " . TABLE_EVENTS . " where events_id='" .(int)$event_id . "'");
 	if(tep_db_num_rows($events_query)>0) $events=tep_db_fetch_array($events_query);				
	$error="";	
	while(list(,$val)=each($sessions_split_array)){
	  if($val>0){	  	
		if ($type=='R')
			$reserve_count=tep_reserve_count($val,$events);
		else
			$reserve_count=tep_waitlist_count($val,$events,$customer_id);		
		$reserve_count+=tep_count_cart($val,$type);
		//to check reserved sessions
		if ($type=='R'){
			//$reserve_count+=tep_get_renewal_users_count($events['events_id'],$events['events_renewal_end'],$customer_id,$session['start_date']);
			$lock_date=false;
			$total_seats=$events["events_max_reserve"];
			$renewal_count=0;
			if (!$override)	$renewal_count=tep_get_renewal_users_count($events,$customer_id,tep_get_session_date($val));
			if ($overbook) $total_seats+=$events["events_overbook_reserve"];
			$seats_avail = $total_seats - $reserve_count;
			if($seats_avail==0 || $seats_avail<0) $error= TEXT_NO_ADDITIONAL_SEATS;
			if($seats_avail>0 && $seats_avail<$no_of_attendees) $error=sprintf(TEXT_PARTLY_FULL,$seats_avail);
		}
	  }
	}     
	echo $error;    
	echo '{}';
	return;
}
function customSessionListBox($name,&$list,$selected,$width,$height){
	global $session_type;
	$selIndex=0;
	$bgcolor="#FFFFFF";
	$jcnt=0;
	echo '<div id="' . $name . '_box" style="border-color: #7b9ebd; border-style: solid; border-width: 1px;overflow:auto;width:' . $width . ';height:' . $height . '">' . "\n";
	echo '<table border="0" cellspacing="0" cellpadding="1" width="100%" valign="middle" align="center" class="BoxTable">' . "\n";
	for ($icnt=0;$icnt<sizeof($list);$icnt++){
		echo '<tr class="attributes-even" height=20><td class="main" width=50>';
		if ($list[$icnt]['type']=='R' || $list[$icnt]['type']=='W'){
			if ($list[$icnt]['bgcolor']==0) $bgcolor="#F5F5F5";
			else $bgcolor="#FFFFFF";
			if ($selected=="" || $selected==0) $selected=$list[$icnt]['id'];
			if ($selected==$list[$icnt]['id']) $selIndex=$jcnt;
			if ($session_type!='S')
				echo tep_draw_checkbox_field($name . "[]",$list[$icnt]['id'],$list[$icnt]['selected'],'','onClick="javascript:selectValidDates('. $jcnt . ');"');
				echo '</td><td bgcolor="' . ($selected==$list[$icnt]['id']?"#D8EDFB":$bgcolor) . '" valign="middle" width="100%" id="' . $name . $list[$icnt]['id'] . '" onClick="javascript:selectSessionItem(\'' . $name . '\',\'' . $list[$icnt]['id'] .  '\',' . $jcnt .')" class="BoxTd">';
		} else {
			if ($list[$icnt]['type']=='E') echo tep_draw_checkbox_field($name . "[]",$list[$icnt]['id'],false,'','style="visibility:hidden"');
			echo '</td><td bgcolor="#FFFFFF" valign="middle" width="100%" class="BoxTd">';
		}
		if ($list[$icnt]['type']!='H') $jcnt++;
		echo $list[$icnt]['text'] .'</td></tr>';
	}
	echo '</table></div>' . "\n";
	if ($session_type=="S")
		echo '<input type="hidden" name="' . $name . '[]" value="' . $selected . '">';
	else
		echo '<input type="hidden" name="' . $name . '_field" value="' . $selected . '">';
	echo '<input type="hidden" name="' . $name . '_index" value="' . $selIndex . '">';
}
function out_service_details($service_id)
{
global $languages_id,$currencies,$no_booking_sdate,$no_booking_edate,$no_booking_dates,$no_booking_stime,$no_booking_etime,$service_start_time,$service_week,$time_length,$block_dates,$no_booking_sdate_array,$granular;
			 	$current_date=getServerDate(true);
				$current_time=strtotime(getServerDate(true));
				$combo_end_date=date('Y-m-d',tep_dateadd($current_time,"day",60));
				$service_info_query=tep_db_query( "select se.service_id,se.multiple_purchase,se.service_total_time,se.booking_granular,se.booking_type,se.quantity,".
							  				   "se.service_location, sed.service_name, sed.service_description, se.service_image, sed.service_url, se.service_costs, se.service_tax_class_id, se.service_date_added, se.service_date_available, se.pending_period, " .
											    "se.service_total_time,se.max_bookings," . 
											    "se.span_days,include_resource from " . TABLE_SERVICES . " se, " . TABLE_SERVICES_DESCRIPTION . " sed  where se.service_status = '1' and se.service_id = '" . 
											     (int)$service_id . "' and sed.service_id = se.service_id and sed.language_id = '" . (int)$languages_id . "'");
														
				$service_info = get_services_info($service_id,$languages_id);
				$service=new objectInfo($service_info);
				$booking_type=$service->booking_type;
				$time_length=$service->service_total_time;
				$max_bookings=$service->max_bookings;
				$service_week=$service->service_week;
				$recurring_details=$service->recurring_details;
				if ($time_length==0) $time_length=1;
				if ($max_bookings==0) $max_bookings=1;
				$service_costs = $currencies->display_price($service->service_costs, tep_get_tax_rate($service->service_tax_class_id));
				$granular=(int)$service->booking_granular;
				if ($granular==0) $granular=1;
				$slot=60/$granular;
				$select_edate="";
				$combo_start_date=date('Y-m-d',strtotime($current_date));
				/*Month */
				$current_month=date("n",$current_time);
				$current_year=date("Y",$current_time);
				$year=date("Y",$current_time);
				$month=date("n",$current_time);
				$month_start_time=mktime(0,0,0,$month,1,$year);
				$week_day=date("w",$month_start_time);
				$total_days=date("t",$month_start_time);
				$month_end_time=mktime(0,0,0,$month,$total_days,$year);
				$month_end_date=date('Y-m-d',$month_end_time);
				$service_start_time="00:00:00";
				if ($booking_type=='H' || $booking_type=='M'){
				$shour=0;
				$ehour=24;
				$no_booking_sdate='';
				$no_booking_edate='';
				$cur_time=date("H",$current_time) .':00:00';
				$span_days=$service->span_days;
				$service_end_time="24:00:00";
				//$bk_query="select recurring_type,recurring_details,no_booking_start_date,no_booking_end_date,no_booking_start_time,no_booking_end_time,recurring_type,recurring_details from ".TABLE_SERVICES_NO_BOOKING_DAYS ." snd where snd.service_id='". $service_id . "' order by recurring_type,no_booking_end_date";
				$bk_query="select no_booking_start_date,no_booking_end_date,no_booking_start_time,no_booking_end_time,recurring_type,recurring_details from ".TABLE_SERVICES_NO_BOOKING_DAYS ." snd where snd.service_id='".(int)$service_id."' and (('$combo_start_date'>=no_booking_start_date and '$combo_start_date'<=no_booking_start_date) OR  ('$combo_end_date'>=no_booking_start_date and '$combo_end_date'<=no_booking_end_date) OR ('$combo_start_date'<=no_booking_start_date and '$combo_end_date'>=no_booking_end_date)) order by no_booking_start_date,no_booking_end_date,no_booking_start_time,no_booking_end_time";
				$bk=tep_db_query($bk_query);
				$dates=array();
				$n_dates=array();
				//echo $combo_start_date.'-'.$combo_end_date;
				while($nbk=tep_db_fetch_array($bk)){					
				$recurring_type=$nbk['recurring_type'];				
				$sInfo=$nbk;													
				if($recurring_type!='DD'){ 
					$nb_dates=get_dates_array($sInfo,$recurring_type);					
					$start_date=$combo_start_date;
					$end_date=$combo_end_date;
					$nbd_array[]=formated_type_dates('dates');
					$nb_dates_array[]=formated_type_dates('n_dates');
				}else if($recurring_type=='DD'){
					 $tep_start_date=$combo_start_date;
					 $tep_end_date=$combo_end_date;
					 while($tep_start_date<=$tep_end_date){					    
					    if($nbk['no_booking_start_date']<=$tep_start_date && $nbk['no_booking_end_date']>=$tep_start_date){
					 		$no_b_stime=$nbk['no_booking_start_time'];
							$no_b_etime=$nbk['no_booking_end_time'];
							$no_b_sdate=$no_b_edate=$tep_start_date;
					 		if($no_b_etime<=$no_b_stime && $span_days=='Y') 
								$no_b_edate=date("Y-m-d",tep_dateadd(@strtotime($tep_start_date),"day",1));
							else if($no_b_etime<=$no_b_stime && $span_days=='N')
								$no_b_etime="24:00:00";
							if($tep_start_date<=$no_b_sdate && $tep_end_date>=$no_b_sdate){								
								$booking_total[]=array('start_date'=>$no_b_sdate,'end_date'=>$no_b_edate,'start_time'=>$no_b_stime,'end_time'=>$no_b_etime);								
								//$nbd_array[][]=array('type'=>$recurring_type,'n_s_date'=>$no_b_sdate,'n_e_date'=>$no_b_edate,'n_s_time'=>$no_b_stime,'n_e_time'=>$no_b_etime);
							$nb_split=split(':',$no_b_stime);
							//echo date("d",mktime(($nb_split[0]+$time_length),$mt,0,1,1,1987)).'-'.$nb_split[0].'-'.$time_length.'-'.$mt.'<br>';  														 
							if($no_b_stime=='00:00:00' && ($no_b_etime>=(24-$time_length).':05:00' && $no_b_etime<='24:00:00') || (($booking_type=='H' || $booking_type=='M') && $time_length!=''  && date("d",mktime(($nb_split[0]+$time_length),$mt,0,1,1,1987))=="02"))
								$nb_dates_array[][format_date($no_b_sdate)]='full';
							if($no_b_stime<=$cur_time && ($no_b_etime>=(24-$time_length).':05:00' && $no_b_etime<='24:00:00') && $no_b_sdate<=$combo_start_date && $no_b_edate>=$combo_start_date)
								$nb_dates_array[][format_date($no_b_sdate)]='full';
						  }  	
					 	}					 	
					   if($tep_start_date) $tep_start_date=date('Y-m-d',tep_dateadd(@strtotime($tep_start_date),"day",1));
					 }
				}								
		  }
		$block_dates=$nb_dates_array;				
		$dates_array=tep_get_service_dates_array($combo_start_date,$combo_end_date,$booking_type);
		$select_sdate=$start_date;
		$select_stime=$start_time;
		$select_edate=$end_date . " " . $end_time;
		} else {
				$shour=0;
				$ehour=24;
				$no_booking_sdate='';
				$no_booking_edate='';
				$cur_time=date("H",$current_time) .':00:00';
				$span_days=$service->span_days;
				$service_end_time="24:00:00";
				//$bk_query="select recurring_type,recurring_details,no_booking_start_date,no_booking_end_date,no_booking_start_time,no_booking_end_time,recurring_type,recurring_details from ".TABLE_SERVICES_NO_BOOKING_DAYS ." snd where snd.service_id='". $service_id . "' order by recurring_type,no_booking_end_date";
				$bk_query="select no_booking_start_date,no_booking_end_date,no_booking_start_time,no_booking_end_time,recurring_type,recurring_details from ".TABLE_SERVICES_NO_BOOKING_DAYS ." snd where snd.service_id='".(int)$service_id."' and (('$current_date'>=no_booking_start_date and '$current_date'<=no_booking_start_date) OR  ('$combo_end_date'>=no_booking_start_date and '$combo_end_date'<=no_booking_end_date) OR ('$current_date'<=no_booking_start_date and '$combo_end_date'>=no_booking_end_date)) order by no_booking_start_date,no_booking_end_date,no_booking_start_time,no_booking_end_time";
				$bk=tep_db_query($bk_query);
				$dates=array();
				$n_dates=array();
				$sel_ssplit=split(" ",$current_date);
				$select_sdate=$sel_ssplit[0];
				while($nbk=tep_db_fetch_array($bk)){
					$recurring_type=$nbk['recurring_type'];					
					if($recurring_type!='DD'){ 
						$nb_dates=service_get_dates_array($sInfo,$recurring_type);					
						$start_date=$select_sdate;
						$end_date=$combo_end_date;					
						$nbd_array[]=formated_type_dates('dates');
						$nb_dates_array[]=formated_type_dates('n_dates');
					}else if($recurring_type=='DD'){					 					 					 	
					 	if($booking_type=='D') $no_booking_sdate_array[]=array('start_date'=>$nbk['no_booking_start_date'],'end_date'=>$nbk['no_booking_end_date']);					 						
					 	$tep_start_date=$select_sdate;											
					 	$tep_end_date=$combo_end_date;					 
					 	while($tep_start_date<=$tep_end_date){					   					    
						    if($nbk['no_booking_start_date']<=$tep_start_date && $nbk['no_booking_end_date']>=$tep_start_date){					 		
					 		$no_b_stime=$nbk['no_booking_start_time'];
							$no_b_etime=$nbk['no_booking_end_time'];													
							$no_b_sdate=$no_b_edate=$tep_start_date;
							if($booking_type=='D'){
								$no_b_stime="00:00:00";
								$no_b_etime="24:00:00";
								$nb_dates_array[][format_date($no_b_sdate)]='full';
							}
							//echo $tep_start_date.'-'.$no_b_sdate.'-'.$tep_end_date.'-'.$no_b_sdate.'<br>';								
					 		if($no_b_etime<=$no_b_stime && $span_days=='Y') 
								$no_b_edate=date("Y-m-d",tep_dateadd(@strtotime($tep_start_date),"day",1));
							else if($no_b_etime<=$no_b_stime && $span_days=='N')
								$no_b_etime="24:00:00";
							if($tep_start_date<=$no_b_sdate && $tep_end_date>=$no_b_sdate){								
								$booking_total[]=array('start_date'=>$no_b_sdate,'end_date'=>$no_b_edate,'start_time'=>$no_b_stime,'end_time'=>$no_b_etime);
								//$nbd_array[][]=array('type'=>$recurring_type,'n_s_date'=>$no_b_sdate,'n_e_date'=>$no_b_edate,'n_s_time'=>$no_b_stime,'n_e_time'=>$no_b_etime);
							$nb_split=split(':',$no_b_etime); 														 
							if($no_b_stime=='00:00:00' && ($no_b_etime>=(24-$time_length).':05:00' && $no_b_etime<='24:00:00') || (($booking_type=='H' || $booking_type=='M') && $time_length!='' && date("d",mktime(($nb_split[0]+$time_length),$mt,0,1,1,1987))=="02")){
								$nb_dates_array[][format_date($no_b_sdate)]='full';
							}		
							if($no_b_stime<=$cur_time && ($no_b_etime>=(24-$time_length).':05:00' && $no_b_etime<='24:00:00') && $no_b_sdate<=$combo_start_date && $no_b_edate>=$combo_start_date){
								$nb_dates_array[][format_date($no_b_sdate)]='full';
							}
						  }  	
					 	} 
					   if($tep_start_date) $tep_start_date=date('Y-m-d',tep_dateadd(@strtotime($tep_start_date),"day",1));
					 }
				}
			 }							
			$block_dates=$nb_dates_array;
			$dates_array=tep_get_service_dates_array($current_date,$combo_end_date,$booking_type);
			$select_sdate=$start_date . ' ' . $start_time;
			$select_edate=$end_date . ' ' . $end_time;
		}
		if ($mode=="edit" && $start_date=="" && $end_date==""){
			// fetch the old details for current service booking
			$info_query=tep_db_query("SELECT oep.products_quantity,oes.products_id,oes.start_date,oes.end_date,time_format(oes.start_time,'%H:%i') as start_time,time_format(oes.end_time,'%H:%i') as end_time from " . TABLE_ORDERS_EDIT_SERVICES . " oes, " . TABLE_ORDERS_EDIT_PRODUCTS . 
									" oep where oep.orders_id='" . (int)$oID ."' and oep.products_id='" . (int)$service_id . "' and oep.products_id=oes.products_id and oep.orders_id=oes.orders_id and oes.start_date='".$start_date."' and oes.end_date='".$end_date."' and oes.start_time='".$start_time."' and oes.end_time='".$end_time."' group by oep.products_id");
			$info_result=tep_db_fetch_array($info_query);
			if ($service_id==$info_result["products_id"]){
				$start_date=$info_result["start_date"];
				$end_date=$info_result["end_date"];						
				$start_time=$info_result["start_time"];
				$end_time=$info_result["end_time"];
				$quantity=$info_result["products_quantity"];
				$start_times=$info_result["start_date"].' '.$info_result["start_time"];
			}
		}
		// check for the service already reserved
		if ($step>3 ){
			$curDate=date('Y-m-d',$current_time);
		}
?>
		<Table width="100%">
				<tr>
					<td><?php echo tep_draw_separator('pixel_trans.gif', '1', '10'); ?></td>
				</tr>
				<tr><td id="service_error"></td></tr>
				<tr>
					<td>
					<table cellpadding="2" cellspacing="0" width="100%" border="0">
						<tr  valign=middle height="20">
							<td class="dataTableContent" align=left><b><?php echo SERVICE_STEP2; ?></b></td>
						</tr>
						<tr>
							<td>
							<table cellpadding="2" cellspacing="0" border="0">
								<tr>
									<td class="dataTableContent"> <?php echo  TEXT_START_TIME;?></td>
									<td class="dataTableContent"  valign="middle"  align="left">
										<?php 
										if ($service->booking_type=="H" || $service->booking_type=='M'){
											echo  tep_draw_pull_down_menu('start_date',$dates_array,tep_db_prepare_input($HTTP_POST_VARS['start_date']),'onChange="javascript:add_start_times();"'.',size=10'); 
											echo '&nbsp;' . tep_draw_pull_down_menu('start_time',$times_array,tep_db_prepare_input($HTTP_POST_VARS['start_time']),'onChange="javascript:add_end_times();"');
										} else {
											echo tep_draw_pull_down_menu('start_times',$dates_array,tep_db_prepare_input($HTTP_POST_VARS['start_times']), 'onChange="javascript:add_end_times();"'.',size=10'); 
											echo tep_draw_hidden_field('start_date_combo','');   
											echo tep_draw_hidden_field('start_time_combo','');  
										}?>
										</td> 
									</tr>
									<tr><td colspan="2"><?php echo tep_draw_separator('pixel_trans.gif', '10', ''); ?></td></tr>
									<tr>
										<td class="dataTableContent"><?php echo  TEXT_END_TIME ; ?></td>
										<td>
										<?php 
										echo tep_draw_pull_down_menu('end_times',array(),'','class="inputnormal"'); 
										echo tep_draw_hidden_field('end_date_combo','');
										echo tep_draw_hidden_field('end_time_combo','');
										?> 
									</td>
								</tr>
								<tr><td colspan="2"><?php echo tep_draw_separator('pixel_trans.gif', '10', ''); ?></td></tr>
								<?php if($service->multiple_purchase=='Y' && $service->include_resource=='N') {?>
										<tr>
											<td  class="dataTableContent" valign="middle"><?php echo TEXT_HOW_MANY; ?></td>
											<td class="dataTableContent" valign="middle"><?php echo tep_draw_input_field('quantity',$sel_quantity,'size=10 maxlength=6'); ?></td>
										</tr>													
								<?php }	?>	
								<tr>
									<td colspan="2" width="750" class="dataTableContent" align="right"></td> 
								</tr> 
							</table>
						</td>
					</tr>
					<Tr><td colspan="2" id="show_select_step3">	
						<table border="0" cellspacing="0" cellpadding="0" width="100%">
							<tr><td width="16%" id="div_dates"></td><td width="10%" align="left"><?php echo '<a href="javascript:do_page_fetch(\'new_service_step3\');">' . tep_image_button('button_select.gif',IMAGE_BUTTON_SELECT) . '</a>';?></td></tr>
						</table>
					</td></Tr>	
				</table>
				</td>
			</tr>
		</Table>
	<input type="hidden" name="ser_quantity" value="1">
<?php
echo "{}max_bookings||" .  (int)$service->max_bookings;
echo "{}time_length||" . (int)$service->service_total_time;
echo "{}book_type||" .$service->booking_type;
echo "{}book_granular||" .(int)$service->booking_granular;
echo "{}service_quantity||" .(int)$service->quantity;
echo "{}span_days||" .$service->span_days;
echo "{}cur_hour||" .date("H",strtotime(getServerDate(true))).':00';
echo "{}cur_date||" .format_date(getServerDate(true));
$result = tep_db_query("SELECT * FROM " . TABLE_SERVICES_ATTRIBUTES . " sa LEFT JOIN " . TABLE_SERVICES_OPTIONS . " so ON so.services_options_id=sa.options_id LEFT JOIN " . TABLE_SERVICES_OPTIONS_VALUES . " sov ON sov.services_options_values_id=sa.options_values_id WHERE sa.service_id='" . (int)$service_id . "' and so.language_id='" . (int)$languages_id . "' and sov.language_id='" . (int)$languages_id . "' order by services_options_id");
$rows=tep_db_num_rows($result); 
if($rows){
echo "{}include_attributes||true";
}
echo "{}include_resource||" .$service->include_resource;
echo "{}multiple_purchase||" . $service->multiple_purchase;
echo "{}st_time||" .$start_time;
echo "{}et_time||" .$end_times;
$booking_buffer=$service->booking_buffer;
$booking_buffer_split=split(",",$booking_buffer);
$book_buffer='N';
$book_buffer_minute=0;
if($booking_buffer!='' && $booking_buffer_split[1]){
	echo "{}book_buffer||" .$booking_buffer_split[0]; 
	echo "{}book_buffer_minute||" .$booking_buffer_split[1];
}
	$details="{}nb_dates||";
	for($bk=0;$bk<sizeof($booking_total);$bk++){ 
		 $nbstime=$booking_total[$bk]['start_time'];
		 $nbetime=$booking_total[$bk]['end_time'];
		 $nb_sdate=$booking_total[$bk]['start_date'];
		 $nb_edate=$booking_total[$bk]['end_date'];
		if($nbstime=="12:00:00"){ $nbstime="00:00:00"; } 
		if($nb_sdate!=$nb_edate || $nbstime>$nbetime){
				$details.=format_date($nb_sdate).'#'.$nbstime.'#'.'24:00:00' . "?";
				$details.=format_date($nb_sdate).'#'.'00:00:00'.'#'.$nbetime . "?";	
	   }else {
				$details.=format_date($nb_sdate).'#'.$nbstime.'#'.$nbetime . "?";
	   }
	}
echo $details;
echo "{}call_functions||add_start_times();add_end_times();";
}

function out_service_details_step3($service_id)
{
global $currencies,$HTTP_POST_VARS,$languages_id,$customer_id,$cart;
	$start_date=isset($HTTP_POST_VARS['start_date'])?tep_db_prepare_input($HTTP_POST_VARS['start_date']):'0000-00-00';
	$start_time=isset($HTTP_POST_VARS['start_time'])?tep_db_prepare_input($HTTP_POST_VARS['start_time']):'0000-00-00';
	$start_times=isset($HTTP_POST_VARS['start_times'])?tep_db_prepare_input($HTTP_POST_VARS['start_times']):'00:00:00';
	$end_times=isset($HTTP_POST_VARS['end_times'])?tep_db_prepare_input($HTTP_POST_VARS['end_times']):'00:00:00';
	$splt_date=split(" ",$end_times);
	$end_date=$splt_date[0];
	$end_time=$splt_date[1];
	$service=get_services_info((int)$service_id,(int)$languages_id);
	$booking_type=$service['booking_type'];
	if($booking_type=='D'){
		$splt_stime=split(" ",$start_times);
		$start_date=$splt_stime[0];
		$start_time=$splt_stime[1];
	}
	//check service found
	  $error="";
	  $service_quantity=(($service['include_resource']=='Y')?1:$service['quantity']);
   	  if($booking_type=='H' || $booking_type=='M'){
		$diff=tep_time_diff($start_date.' '.$start_time,$end_date.' '.$end_time);		
		if($booking_type=='M') $service_quantity=round(($diff['minutes']/$service['service_total_time']) * $service_quantity);
 		else $service_quantity=round((24/$service['service_total_time']) * $service_quantity);
 	  }
	  $str_start_time=number_format($start_time, 2, ':', ' ');
	  $str_end_time=number_format($end_time, 2, ':', ' ');
 	  $reserved_quantity=get_orders_products_quantity($service_id,$start_date,$end_date,$str_start_time,$str_end_time,$booking_type,0,$cart);
 	  if($reserved_quantity>=$service_quantity) $error=ERR_TIME_ALREADY_RESERVED;
	//check service found
	$resource_id=isset($HTTP_POST_VARS['resource_ids'])?tep_db_prepare_input($HTTP_POST_VARS['resource_ids']):"0";	
	$splt=split("-",$resource_id);	
	if($splt[0]) $resource_id=$splt[0];
	$resource_costs=isset($HTTP_POST_VARS['resource_costs'])?tep_db_prepare_input($HTTP_POST_VARS['resource_costs']):0;;
	$include_resource=isset($HTTP_POST_VARS['include_resource'])?tep_db_prepare_input($HTTP_POST_VARS['include_resource']):'N';
	$sel_quantity=isset($HTTP_POST_VARS['ser_quantity'])?(int)$HTTP_POST_VARS['ser_quantity']:1;
	$quantity=(int)$sel_quantity;
	if($start_time=='24:00') $start_time="12:00";
	$attribute_array=array();
	$edit_mode=false;
	// get service details  
	$booking_type=$service['booking_type'];
	$include_resource_price=$service['include_resource_price'];
	$service_quantity=(int)(($service['include_resource']=='Y')?1:$service['quantity']);
	$resource_query="";
	if($service['include_resource']=='Y') {
		$reserved_resource_id="";
		if($service_id){ 
		//get resource details
		    $start_time_split=split(":",$start_time);
			$start_time=sprintf("%02d:%02d",$start_time_split[0],$start_time_split[1]);
	   //get resource details	
			 $res_num_rows=0;
			 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_RESOURCES . " re, " . TABLE_RESOURCES_DESCRIPTION . " red," .  TABLE_SERVICES_TO_SERVICES_RESOURCES . " seTre where seTre.service_id='" . (int)$service_id . "' and re.resource_id not in(".$reserved_resource_id.")  and red.language_id='".(int)$languages_id."' and seTre.service_resource_id=re.resource_id and re.resource_id=red.resource_id order by red.resource_name");			 
			 $res_num_rows=tep_db_num_rows($resource_query);
		 //if(!$res_num_rows)$error=ERR_TIME_ALREADY_RESERVED;
		  }
		  $quantity=1;
		}	 
		$products_id=get_details('resource_id','orders_edit_services',"start_date='".$start_date."' and end_date='".$end_date."' and start_time='".$start_time."' and end_time='".$end_time."' and products_id='".(int)$service_id."' and resource_id='".(int)$resource_id."'",$list=true);
		if($products_id && $mode!='edit'){
			while(list($key,$value)=each($products_id)){
		  	  if($products_id[$key] && $service['include_resource']=='Y') $mode="";
		  	}
		}
	$no_resource_display="false";
	$no_attributes_display="false";
	$result_attributes = tep_db_query("SELECT * FROM " . TABLE_SERVICES_ATTRIBUTES . " sa LEFT JOIN " . TABLE_SERVICES_OPTIONS . " so ON so.services_options_id=sa.options_id LEFT JOIN " . TABLE_SERVICES_OPTIONS_VALUES . " sov ON sov.services_options_values_id=sa.options_values_id WHERE sa.service_id='" . (int)$service_id . "' and so.language_id='" . (int)$languages_id . "' and sov.language_id='" . (int)$languages_id . "' group by services_options_id");
	$rows=tep_db_num_rows($result_attributes);
	if(!$rows && $service_id && $start_date && $error=='')$no_attributes_display="true";
	if(!$res_num_rows && $service_id && $start_date && $error=='')$no_resource_display="true";
?>
	<table width=100%>
			<tr><td class="errorText" align="center"><?php echo $error;?></td></tr>
			<tr  valign=middle height="20">
				<td class="dataTableContent" align=left><b><?php echo SERVICE_STEP3; ?></b></td>
			</tr>
			<tr id="div_resource">
   				<td width="70%" align="left">
					<table border="0" align="left" cellspacing="0" cellpadding="0" width="65%">
					<?php if($error=="" && $no_resource_display=="false"){ ?>
					<tr>
						<td colspan="4" class="pageHeading" nowrap="true"><?php echo HEADING_RESOURCE;?></td>
					</tr>
					<tr style="height:20" valign="bottom"><td></td></tr>
					<?PHP 
					   $cou=0;
					   if($resource_query!='' && tep_db_num_rows($resource_query)>0){
					   $no_resource=false;?>
					<tr class='pageheading'> 
						<td width="5%"></td>
						<td class="main" align="left" width="40%"><?php echo TEXT_NAME;?></td>
						<td class="main" align="left" width="10%"><?php echo TEXT_COSTS;?></td>
					</tr>
			<?php $bk_cnt=0;
			  while($resource=tep_db_fetch_array($resource_query)){	
				$reserved_resource="";
				$time_booking=tep_time_diff($start_date.' ' .$start_time,$end_date.' ' . $end_time);
			    $bookings=$time_booking['hours'];
			    $booking_type=$service->booking_type;
			    if($booking_type=='D'){
					$splt_stime=split(" ",$start_times);
					$start_date=$splt_stime[0];
					$start_time=$splt_stime[1];
					$splt_etime=split(" ",$end_times);
					$end_date=$splt_etime[0];
					$end_time=$splt_etime[1];
				}
				$reserved_resource=get_resource_ids((int)$service_id,$start_date,$end_date,$start_time,$end_time,$booking_type);
				$bookings=$time_booking['days'];
				$resource_id=$resource['resource_id']; 
				//check booking buffer
				$tep_date_time=strtotime($start_date.' '.$start_time);
				$buffer_string='#'.$start_date.' '.$start_time.'#'.$end_date.' '.$end_time;
				if($booking_buffer!='' && $booking_buffer_split[1]){ 
					$temp_date=date('Y-m-d',strtotime($start_date.' '.$start_time)-60);
					$temp_time=date('H:i',strtotime($start_date.' '.$start_time)-60);
					$booked_resource_ids=get_resource_ids($service_id,$temp_date,$temp_date,$temp_time,$temp_time,$booking_type,'dates',$resource_id);
					$res_ids="";
					$raw_date="";
					$sorted_date="";
					$raw_date=$booked_resource_ids;
					$sorted_date=rsort($raw_date);
					$temp_date_time=$start_date.' '.$start_time;
				if($raw_date[0]) {
					$buffer_string="";
					$tep_end_time_check=strtotime($raw_date[0])+60+($booking_buffer_split[1] * 60);
					if($tep_end_time_check) $ret=tep_time_diff($start_date.' '.$start_time,date('Y-m-d H:i:s',$tep_end_time_check));					
					if($ret['minutes']>0 && $ret['minutes']<=($booking_buffer_split[1] * 4)) $tep_date_time=$tep_end_time_check;
					if($bookings && $tep_date_time) {
						$tep_end_string=tep_dateadd($tep_date_time-60,'hr',$bookings);
						if($booking_type=='D') $tep_end_string=tep_dateadd($tep_date_time-60,'day',$bookings);
					} 	
					$buffer_string='#'.date('Y-m-d H:i',$tep_date_time).'#'.date('Y-m-d',$tep_end_string).' '.date('H:i',$tep_end_string);
					$reserved_resource=get_resource_ids($service_id,date('Y-m-d',$tep_date_time),date('Y-m-d',$tep_end_string),date('H:i',$tep_date_time),date('H:i',$tep_end_string),$booking_type,'',$resource_id);
							
				} 
			  }		
			 $resource_ids_found=false;
			 if($reserved_resource){
			  while(list($key,$value)=each($reserved_resource)){ 
				if($value==$resource['resource_id'])	$resource_ids_found=true;
			  }
			 }
			 if(!$resource_ids_found){
			  ?>
					 	<tr style="cursor:pointer;cursor:hand" class="RowEven" onMouseOver="rowOverEffect(this);" onMouseOut="rowOutEffect(this)" onClick="on_select(<?php echo $cou;?>);">
							<td class="main" align="left"><?php echo tep_draw_radio_field('resource[]',$resource['resource_id'].'-'.$resource['resource_costs'].$buffer_string);?></td>
							<td class="main" align="left"><?php echo $resource['resource_name'];?></td>
							<td class="main" align="left"><?php echo $currencies->display_price($resource['resource_costs'], tep_get_tax_rate($resource['resource_tax_class_id']));?></td>
						</tr>
						<tr>
							<td></td>
							<td class="main" align="left"><?php echo $resource["resource_description"];?></td>
							<td class="main"></td> 
						</tr>	
			<?php $bk_cnt+=1;
				} 
				 $cou++;
				}
				if(!$bk_cnt) {
				  echo '<script language=javascript>
				          if(document.getElementById("div_resource")) document.getElementById("div_resource").innerHTML="<br><span class=main>'.TEXT_RES_SKIPPED.'</span>";  
				       </script>';
				   $no_resource=true;	
				}
			  }else   $no_resource=true;
			 }else {?>
					<tr style="10"><td>&nbsp;</td></tr>
					<tr style="20%" >
						<td valign="bottom" class="smalltext"><?php echo TEXT_SKIPPED;?></td>
					</tr>				
					<tr style="10"><td>&nbsp;</td></tr>
		 <?php }
				?>
				 </table>
				</td>
			</tr>
			<tr class="attributes-odd" valign=middle height="20">
				<td class="dataTableContent" align=left><b><?php echo SERVICE_STEP4; ?></b></td>
			</tr>
			<tr> 
				<td colspan="3" align="left"> 
					<table border="0" cellpadding="0" cellspacing="0" width="89%">
					<?php if($error=="" && $no_attributes_display=="false"){?>
						<tr>
							<td colspan="3" class="pageHeading" align="left"><?php echo TEXT_HEADING_ATTRIBUTE;?></td>
						</tr>
						<tr style="height:20" valign="bottom"><td></td></tr>
						<?php 
							if($rows>0){ ?> 
						<tr>
							<td class="main" align="left" width="20%"><?php echo TEXT_ATTRIBUTE_NAME;?></td>
							<td class="main" align="left" width="70%"><?php echo TEXT_ATTRIBUTE_VALUE;?></td>
						</tr>
				<?php while ($services_options_name_values = tep_db_fetch_array($result_attributes)) {
						$selected = 0;
						$services_options_array = array();?> 
					   <tr style="height:40" valign="middle">
								<td class="main" nowrap="nowrap"><?php echo $services_options_name_values['services_options_name'];?>: </td>
								<?php 
							 		$services_options = tep_db_query("select sa.services_options_sort_order, sov.services_options_values_id, sov.services_options_values_name, sa.options_values_price, sa.price_prefix,sa.options_values_id from " . TABLE_SERVICES_ATTRIBUTES . " sa, " . TABLE_SERVICES_OPTIONS_VALUES . " sov where sa.service_id = '" . (int)$service_id . "' and sa.options_id = '" . (int)$services_options_name_values['services_options_id'] . "' and sa.options_values_id = sov.services_options_values_id and sov.language_id = '" . (int)$languages_id . "'" . " order by sa.services_options_sort_order, sa.options_values_price");
							 		$services_options_array[0]['text'] = TEXT_SERVICE_NOT_REQUIRED;
									while ($services_options_values = tep_db_fetch_array($services_options)) {
										$services_options_array[] = array('id' => $services_options_name_values['services_options_id'] .'-'.$services_options_values['services_options_values_id'], 'text' => $services_options_values['services_options_values_name']);
										if ($services_options_values['options_values_price'] != '0') {
											$services_options_array[sizeof($services_options_array)-1]['text'] .= ' (' . $services_options_values['price_prefix'] . $currencies->display_price($services_options_values['options_values_price'], tep_get_tax_rate($service_info["service_tax_class_id"]),'1',true) .') ';
										}
									} // while option values 
									$id.= $services_options_name_values['services_options_id'].'-';
									$id1='id_attrib[' . $services_options_name_values['services_options_id'] . ']';
									?> 
						<td>
								<?php echo tep_draw_pull_down_menu($id1, $services_options_array, (($option_id>0)?$option_id:$cart->contents[$service_id]['attributes'][$services_options_name_values['services_options_id']])) ;?>
						</td>		
				<?php  	} 
					  }
				}else { ?>
					<tr style="10"><td>&nbsp;</td></tr>
					<tr style="20%" >
						<td valign="bottom" class="smalltext"><?php echo TEXT_SKIPPED;?></td>
					</tr>				
					<tr style="10"><td>&nbsp;</td></tr>
			<?php } ?>
				<input type="hidden" name="resource_ids">
				<input type="hidden" name="resource_costs"> 
				<input type="hidden" name="option_ids"> 
				<?php  
					$start_date=isset($HTTP_POST_VARS['start_date'])?tep_db_prepare_input($HTTP_POST_VARS['start_date']):''; 
					$start_time=isset($HTTP_POST_VARS['start_time'])?tep_db_prepare_input($HTTP_POST_VARS['start_time']):'';
					$start_times=isset($HTTP_POST_VARS['start_times'])?tep_db_prepare_input($HTTP_POST_VARS['start_times']):'';
					$end_times=isset($HTTP_POST_VARS['end_times'])?tep_db_prepare_input($HTTP_POST_VARS['end_times']):'';
					$splt_date=split(" ",$end_times);
					$end_date=$splt_date[0];
					$end_time=$splt_date[1]; 
					$service=get_services_info((int)$service_id,(int)$languages_id);
					if($service['booking_type']=='D'){
						$splt_stime=split(" ",$start_times);
						$start_date=$splt_stime[0];
						$start_time=$splt_stime[1];
					}
				?>
				  </table>
				</td>
			</tr>
			
			<!-- store membership option -->	
			<tr><td>&nbsp;</td></tr>
		<?php 
			$subs_query=tep_db_query("select s.subscription_id as id from " .TABLE_SUBSCRIPTIONS ." s," . TABLE_SUBSCRIPTION_TO_SUBSCRIPTION_CATEGORIES . " sc where s.subscription_id=sc.subscription_id and  s.subscription_type='M' and s.subscription_status=1");
			$subs_result=tep_db_fetch_array($subs_query);
			if(tep_db_num_rows($subs_query)>0) {
			$order_query=tep_db_query("select o.orders_id from " .TABLE_ORDERS_PRODUCTS ." op," . TABLE_ORDERS . " o where op.orders_id=o.orders_id and o.customers_id='" . $customer_id . "' and  op.products_id='" . $subs_result['id']."' and op.products_type='S'");
			//echo "select o.orders_id from " .TABLE_ORDERS_PRODUCTS ." op," . TABLE_ORDERS . " o where op.orders_id=o.orders_id and o.customers_id='" . $customer_id . "' and  op.products_id='" . $subs_result['id']."' and op.products_type='S'";
			$order_result=tep_db_fetch_array($order_query);
			$item_exists=false;
			$check_subs=false;
			 
			 if(tep_db_num_rows($order_query)<=0) {
				$check_subs=true;
			}	else  {
				
				if(tep_session_is_registered('order_id') ) {
					$check_subs=true;
				}
			}
			
			if($check_subs) {
				while (list($products_id, ) = each($cart->contents)) {
					if($cart->contents[$products_id]['element_type']=='S' && $products_id=$subs_result['id'])
						$item_exists=true;
				}
				if(!$item_exists) {
					//add store membership checkbox if exist
					?>
					<tr>
					<td class="main"><?php echo tep_draw_checkbox_field('store_membership_option','Y','','',' id="store_membership_option" ').' '. 'Add StoreMembership';?>
					</td>
					</tr>
					<?php
					}			
				}
			}		?>	
       </table>
<?php
echo "{}attributes_array||";
$cou=0;
 $pre_id=""; 	
  $result = tep_db_query("SELECT * FROM " . TABLE_SERVICES_ATTRIBUTES . " sa LEFT JOIN " . TABLE_SERVICES_OPTIONS . " so ON so.services_options_id=sa.options_id LEFT JOIN " . TABLE_SERVICES_OPTIONS_VALUES . " sov ON sov.services_options_values_id=sa.options_values_id WHERE sa.service_id='" . (int)$service_id . "' and so.language_id='" . (int)$languages_id . "' and sov.language_id='" . (int)$languages_id . "' order by services_options_id");
  $rows=tep_db_num_rows($result); 
  if($rows){
	   while($attribute=tep_db_fetch_array($result)){
			    if($pre_id!=$attribute['services_options_id']){
					 echo $attribute['services_options_id'] . "?";
					$pre_id=$attribute['services_options_id'];
					$cou++;
				 }
			} 
   }
   echo "{}error||".$error;
}
if($HTTP_GET_VARS['action'] && $HTTP_GET_VARS['cID']){ ?>
<script language="javascript">
command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'command=show_customer_details');?>&cID="+ "<?php echo (int)$HTTP_GET_VARS['cID']; ?>";
</script>
<?php  } ?>

<?php if($HTTP_GET_VARS['return'] && $HTTP_GET_VARS['cID'] && $HTTP_GET_VARS['oID']){?>
<script language="javascript">
command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'command=update_customer');?>&oID="+ "<?php echo (int)$HTTP_GET_VARS['oID']; ?>" + "&cID="+ "<?php echo (int)$HTTP_GET_VARS['cID']; ?>" + "&return="+ "<?php echo tep_db_prepare_input($HTTP_GET_VARS['return']); ?>";
do_page_fetch('update_customer');
</script>
<?php }?>

<?php
function out_attendees_details($no_attendees)
{
  global $customer_id;
		//$customer_list=array();	
		$cus=0;
		$customer_query=tep_db_query("select distinct c.customers_id,c.customers_firstname,c.customers_lastname,c.customers_email_address,a.entry_postcode,a.entry_city,a.entry_state,a.entry_country_id from ".TABLE_CUSTOMERS_TO_CUSTOMERS ." c2c LEFT JOIN ".TABLE_CUSTOMERS ." c on(c2c.customer_id=c.customers_id) LEFT JOIN ".TABLE_ADDRESS_BOOK ." a ON(c.customers_id=a.customers_id) where group_customer_id!=c.customers_id and group_customer_id='$customer_id' order by c.customers_lastname,c.customers_firstname");
		if(tep_db_num_rows($customer_query)){
			while($customer=tep_db_fetch_array($customer_query)){
				if($customer['customers_id']) $customer_list[]=array('id'=>$customer['customers_id'],'text'=>$customer['customers_lastname'].' '.$customer['customers_firstname'].','.$customer['customers_email_address'].',('.$customer['customers_id'].')');
				$cus++; 
			}
		} 
?>
 <table border="0" width="100%" cellspacing="0" cellpadding="<?php echo CELLPADDING_SUB; ?>">
      <tr>																													
        <td><table border="0" width="100%" cellspacing="0" cellpadding="0">
          <tr>
            <td class="pageHeading"><?php echo HEADING_TITLE_ATTENDEES ; ?></td>
		  </tr>
        </table></td>
      </tr>
<?php
$cust_array=array("name"=>"",
					"email"=>"",
					"streetaddress"=>"",
					"city"=>"",
					"postcode"=>"",
					"state"=>"",
					"city"=>"",
					"country"=>"",
					"attendee" =>""
					);

$cust_info=new objectInfo($cust_array);
for($icnt=0;$icnt<$no_attendees;$icnt++){
	if ($error==true && isset($customers_list[$icnt])){
		$customer=new objectInfo($customers_list[$icnt]);
	} else if ($mode=="edit"){
		$customer=new objectInfo($cart->attendees[$icnt]);
	} else { 
		$customer=$cust_info;
	}
	$customer->name=sprintf(TEXT_ATTENDEE,$icnt+1); 
	if($icnt<1){ 
	$customer_load_query=tep_db_query("select c.customers_id,c.customers_firstname,c.customers_lastname,c.customers_email_address,a.entry_street_address,a.entry_postcode,a.entry_city,a.entry_state,a.entry_zone_id,a.entry_country_id from " . TABLE_CUSTOMERS . " c, " . TABLE_ADDRESS_BOOK. " a where c.customers_id = '$customer_id' and c.customers_id=a.customers_id ");
		if(tep_db_num_rows($customer_load_query)){
			while($customer_load=tep_db_fetch_array($customer_load_query)){
				$customer->first_name=$customer_load['customers_firstname'];
				$customer->last_name=$customer_load['customers_lastname'];
				$customer->email_address=$customer_load['customers_email_address'];
				$customer->street_address=$customer_load['entry_street_address'];
				$customer->city=$customer_load['entry_city'];
				$customer->postcode=$customer_load['entry_postcode'];
				$customer->country=$customer_load['entry_country_id'];
				$customer->state=$customer_load['entry_state'];
				$customer->zone_id=$customer_load['entry_zone_id'];
			 }
		 }
	}
	$focus_option=' onFocus="javascript:clear_error(' . $icnt . ');"';
?> 
		<tr>
			<td class="messageStackWarning" id="error_box_<?php echo $icnt;?>" style="display:<?php echo ($error && isset($errors[$icnt])?"":"none");?>">
				<?php
					if ($error) {
						for ($jcnt=0;$jcnt<=count($errors[$icnt]);$jcnt++){
							echo $errors[$icnt][$jcnt] . '<br>';
						}
					}
				?>
			</td>
		</tr>
      <tr>
        <td><table border="0" width="100%" cellspacing="1" cellpadding="2" >
          <tr>
            <td class="contenttitletop">
			    <table border="0" width="100%" cellspacing="0" cellpadding="2">
              <tr>
			    <td colspan="2" valign="top" align="left"><B><?php echo $customer->name;?></B></td>
			  </tr>
			  <?php if(tep_db_num_rows($customer_query)>0){
			  		if($icnt==0) $style='display:none';
					else $style='display:';
			   ?>
			  	<tr>
			  	<td class="main" colspan="2">
			  	<table border="0"  cellspacing="0" cellpadding="0" width="100%">
			  		<tr>
			  		<td align="left" class="main" width="30%" style="<?php echo $style; ?>">
			  			<?php echo tep_draw_checkbox_field('attendee[]',1,($customer->attendee==1)?true:false,'',' id="attendee[]" onclick="javascript:hide_customerlistbox('.$icnt.');"').' '. TEXT_ADD_EXISTING_CUSTOMER;?>
			  		</td>
					<td class="main" width="70%">
						<?php  echo tep_draw_pull_down_menu('customer_text',$customer_list,check_customer_exists($customer->email_address,($customer->attendee==1)?true:false),"onchange=javascript:fill_details($icnt); onkeydown=javascript:fill_details($icnt); onkeyup=javascript:fill_details($icnt); style='display:none'");?>
					</td>
			  		</tr>
			    </table>
				</td>
			  </tr>
			  <?php } ?>
			  <tr>
                <td class="main"  align="left"><?php echo ENTRY_FIRST_NAME;?></td>
                <td class="main"  align="left" nowrap><?php  echo tep_draw_input_field('first_name[]',$customer->first_name,$focus_option) . '&nbsp;<span class="inputRequirement">' . ENTRY_REQUIRED . '</span>';?></td>
			  </tr>
			  <tr>
                <td class="main" align="left"><?php echo ENTRY_LAST_NAME; ?></td>
                <td class="main" align="left" nowrap><?php  echo tep_draw_input_field('last_name[]',$customer->last_name,$focus_option) . '&nbsp;<span class="inputRequirement">' . ENTRY_REQUIRED . '</span>';?></td>
			  </tr>
              <tr>
                <td nowrap class="main"  align="left" valign="top"><?php echo ENTRY_EMAIL_ADDRESS; ?></td>
                <td class="main"align="left"><?php echo tep_draw_input_field('email_address[]',$customer->email_address,$focus_option) . '&nbsp;<span class="inputRequirement">' . ENTRY_REQUIRED . '</span>'; 
													echo '&nbsp;' . (($icnt==0 && $no_attendees>1)?'<a href="javascript:dofill();">' .  tep_image_button('button_apply_to_all.GIF',IMAGE_APPLY_TO_ALL)  .'</a>':'');?></td>
			  </tr>
			  <tr>
                <td nowrap class="main"  align="left"><?php echo ENTRY_STREET_ADDRESS; ?></td>
                <td class="main" align="left"><?php echo tep_draw_input_field('street_address[]',$customer->street_address,$focus_option) . '&nbsp;<span class="inputRequirement">' . ENTRY_REQUIRED . '</span>'; ?></td>
			  </tr>
			  <tr>
                <td nowrap class="main"  align="left"><?php echo ENTRY_CITY; ?></td>
                <td class="main">
				  <table width="100%" align="center" border="0" cellpadding="0" cellspacing="0">
				     <tr><td  class="main" align="left"><?php echo tep_draw_input_field('city[]',$customer->city,$focus_option) . '&nbsp;<span class="inputRequirement">' . ENTRY_REQUIRED . '</span>'; ?></td>
				  </table>
				</td>
			  </tr>
			  <tr>
                <td nowrap class="main"  align="left"><?php echo ENTRY_POSTCODE ; ?></td>
                <td class="main"  align="left"><?php echo tep_draw_input_field('postcode[]',$customer->postcode,$focus_option) . '&nbsp;<span class="inputRequirement">' . ENTRY_REQUIRED . '</span>'; ?></td>
			  </tr>
			  <tr>
                <td nowrap class="main"  align="left"><?php echo ENTRY_COUNTRY; ?></td>
                <td class="main" width="70%" align="left">
					<?php echo attendees_get_country_list('country[]',$customer->country,'id="country[]" onchange="javascript:show_attendee_state('.$icnt.');"',$focus_option) .'&nbsp;<span class="inputRequirement">' . ENTRY_REQUIRED . '</span>';
				 		//	echo '&nbsp;' . (($icnt==0 && $no_attendees>2)?'<a href="javascript:dofill();">' . TEXT_APPLY_ALL .'</a>':'');
				?></td>
			  </tr>
			  <tr>
                <td nowrap class="main"  align="left"><?php echo ENTRY_STATE; ?></td>
                <td class="main" width="70%" align="left">
				<?php 
					$customer_state=tep_get_zone_name($customer->country, $customer->zone_id, $customer->state);
					if ($error==true && sizeof($state_errors[$icnt])>0){
							$zones_array = array();
							$zones_query = tep_db_query("select zone_name from " . TABLE_ZONES . " where zone_country_id = '" . (int)$customer->country. "' order by zone_name");
							while ($zones_values = tep_db_fetch_array($zones_query)) {
								$zones_array[] = array('id' => $zones_values['zone_name'], 'text' => $zones_values['zone_name']);
							}	
						echo tep_draw_pull_down_menu('state[]', $zones_array,$customer->state,'id="state[]"','');
						echo tep_draw_input_field('state1[]',$customer_state,'id="state1[]" style="display:none"'); 
					} else {
						   echo tep_draw_pull_down_menu('state[]', $zones_array,$customer->state,'id="state[]" style="display:none"','');
							echo tep_draw_input_field('state1[]',$customer_state,'id="state1[]"'); 
					}
					echo tep_draw_hidden_field('customer_state[]');
				?>
				</td>
			  </tr>
            </table></td>
          </tr>
        </table></td>
      </tr>
		<?php if($icnt<1){
		 			unset($customer->first_name);
					unset($customer->last_name);
					unset($customer->email_address);
					unset($customer->street_address);
					unset($customer->city);
					unset($customer->post_code);
					unset($customer->country);
					unset($customer->state);
			  }
  }
?>
    </table>
<?php 
}
  function attendees_get_country_list($name, $selected = '', $parameters = '') { 
   $countries_array = array(array('id' => '', 'text' => PULL_DOWN_DEFAULT)); 
   $countries = attendees_get_countries(); 
   $size = sizeof($countries); 
   for ($i=0; $i<$size; $i++) { 
     $countries_array[] = array('id' => $countries[$i]['countries_id'], 'text' => $countries[$i]['countries_name']); 
   } 

   return tep_draw_pull_down_menu($name, $countries_array, $selected, $parameters); 
}
  function attendees_get_countries($countries_id = '', $with_iso_codes = false) {
    $countries_array = array();
    if ($countries_id) {
      if ($with_iso_codes) {
        $countries = tep_db_query("select countries_name, countries_iso_code_2, countries_iso_code_3 from " . TABLE_COUNTRIES . " where countries_id = '" . (int)$countries_id . "' order by countries_name");
        $countries_values = tep_db_fetch_array($countries);
        $countries_array = array('countries_name' => $countries_values['countries_name'],
                                 'countries_iso_code_2' => $countries_values['countries_iso_code_2'],
                                 'countries_iso_code_3' => $countries_values['countries_iso_code_3']);
      } else {
        $countries = tep_db_query("select countries_name from " . TABLE_COUNTRIES . " where countries_id = '" . (int)$countries_id . "'");
        $countries_values = tep_db_fetch_array($countries);
        $countries_array = array('countries_name' => $countries_values['countries_name']);
      }
    } else {
      $countries = tep_db_query("select countries_id, countries_name from " . TABLE_COUNTRIES . " order by countries_name");
      while ($countries_values = tep_db_fetch_array($countries)) {
        $countries_array[] = array('countries_id' => $countries_values['countries_id'],
                                   'countries_name' => $countries_values['countries_name']);
      }
    }

    return $countries_array;
  } 
function check_customer_exists($email,$id=false){
	global $check_array,$icnt,$mode;
	
	if(!$check_array[$icnt] && $mode!='edit') return;
	$retutn=false;
	if($email=='') return;
	$check_customer=tep_db_query("select customers_id from ".TABLE_CUSTOMERS." where customers_email_address='". tep_db_input($email) ."'");
	if(tep_db_num_rows($check_customer)>0)
		$return=true;
	if($id){
		$customer_id=tep_db_fetch_array($check_customer);
		$return=$customer_id['customers_id'];
	}	
	return $return;
}

function user_compare($a, $b) 
{
    if ($a['date'] == $b['date']) {
        return 0;
    } 
    return ($a['date'] < $b['date']) ? -1 : 1;
}

	function tep_get_products_attributes($products_id){
		global $languages_id,$currencies,$tax_rate,$pattributes;
		
		$temp_query=tep_db_query("select distinct popt.products_options_id, popt.products_options_name, popt.products_options_sort_order from " . TABLE_PRODUCTS_OPTIONS . " popt, " . TABLE_PRODUCTS_ATTRIBUTES . " patrib where patrib.products_id='" . tep_db_input($products_id) . "' and patrib.options_id = popt.products_options_id and popt.language_id = '" . (int)$languages_id . "'" . " order by popt.products_options_sort_order");
		$products_options=array();
		$products_ajx_values="";
		$initial=0;
		$value_extra_option="";
		if (!isset($tax_rate)){
			$product_query=tep_db_query("SELECT products_tax_class_id from " . TABLE_PRODUCTS . " where products_id='" . tep_db_input($products_id) . "'");
			$product_result=tep_db_fetch_array($product_query);
			$tax_rate=tep_get_tax_rate($product_result["products_tax_class_id"]);
		}
		if(tep_db_num_rows($temp_query)>0){
			while($result=tep_db_fetch_array($temp_query)){
					$products_options_values=array(array("id"=>0,"text"=>TEXT_SELECT_ATTRIBUTE));
					if (PRODUCTS_OPTIONS_SORT_BY_PRICE !='1' ) {
						$temp_query1= tep_db_query("select  pa.products_options_sort_order, pa.options_id, pov.products_options_values_id, pov.products_options_values_name, pa.options_values_price, pa.price_prefix from " . TABLE_PRODUCTS_ATTRIBUTES . " pa, " . TABLE_PRODUCTS_OPTIONS_VALUES . " pov where pa.products_id = '" . tep_db_input($products_id) . "' and pa.options_id = '" . $result['products_options_id'] . "' and pa.options_values_id = pov.products_options_values_id and pov.language_id = '" . $languages_id . "'" . " order by pa.products_options_sort_order, pov.products_options_values_name");
					} else {
						$temp_query1= tep_db_query("select pa.products_options_sort_order, pa.options_id, pa.options_values_id, pov.products_options_values_id, pov.products_options_values_name, pa.options_values_price, pa.price_prefix from " . TABLE_PRODUCTS_ATTRIBUTES . " pa, " . TABLE_PRODUCTS_OPTIONS_VALUES . " pov where pa.products_id = '" . tep_db_input($products_id) . "' and pa.options_id = '" . $result['products_options_id'] . "' and pa.options_values_id = pov.products_options_values_id and pov.language_id = '" . $languages_id . "'" . " order by pa.products_options_sort_order, pa.options_values_price");
					}
					while ($options_values = tep_db_fetch_array($temp_query1)) {	
						$value_extra_option=" and attributes_id like '%" . tep_db_input($result['products_options_id']) . '{' . tep_db_input($options_values["products_options_values_id"]) . "}%'";
						$stock_check_query = tep_db_query("select attributes_id from ". TABLE_PRODUCTS_STOCK . " where products_id = '".  tep_db_input($products_id) ."'" . $value_extra_option);
						if (tep_db_num_rows($stock_check_query)>0){
							$temp_name=$options_values['products_options_values_name'];
								$products_options_values[]=array("id"=>$options_values["products_options_values_id"],"text"=>$temp_name);
						}
					} if(count($products_options_values)>1)
						$products_options[]=array("name"=>$result['products_options_name'],"value"=>tep_draw_pull_down_menu("attrValues[" . $initial . "]",$products_options_values,'','id="attrValues[' .$initial . ']" onChange="javascript:selectAttribute(this,'. $initial .');"') . '<input type="hidden" name="attrIds[' . $initial . ']" id="attrIds[' . $initial . ']" value="' .$result['products_options_id'] . '">','price'=>'<span id="attrPrice'. $initial . '">&nbsp;</span>');
				$initial++;
			}
		}	
			return $products_options;
	}

	
	function set_product_values($products_id,$from_ajx=false){
		global $languages_id,$currencies,$tax_rate;
		$temp_query=tep_db_query("select distinct popt.products_options_id, popt.products_options_name, popt.products_options_sort_order from " . TABLE_PRODUCTS_OPTIONS . " popt, " . TABLE_PRODUCTS_ATTRIBUTES . " patrib where patrib.products_id='" . $products_id . "' and patrib.options_id = popt.products_options_id and popt.language_id = '" . (int)$languages_id . "'" . " order by popt.products_options_sort_order");
		$initial=0;
		$attrbcnt=0;
		$value_extra_option="";
		if (!isset($tax_rate)){
			$product_query=tep_db_query("SELECT products_tax_class_id from " . TABLE_PRODUCTS . " where products_id='" . $products_id . "'");
			$product_result=tep_db_fetch_array($product_query);
			$tax_rate=tep_get_tax_rate($product_result["products_tax_class_id"]);
		}$pattributes='{enabled:false,count:0}';
		if (tep_db_num_rows($temp_query)>0){
			 $pattributes="{enabled:true,prices:{";
			while($result=tep_db_fetch_array($temp_query)){
					$pattributes.="op" . tep_db_input($result['products_options_id']) . ":{";
					if (PRODUCTS_OPTIONS_SORT_BY_PRICE !='1' ) {
						$temp_query1= tep_db_query("select  pa.products_options_sort_order, pa.options_id, pov.products_options_values_id, pov.products_options_values_name, pa.options_values_price, pa.price_prefix from " . TABLE_PRODUCTS_ATTRIBUTES . " pa, " . TABLE_PRODUCTS_OPTIONS_VALUES . " pov where pa.products_id = '" . $products_id . "' and pa.options_id = '" . $result['products_options_id'] . "' and pa.options_values_id = pov.products_options_values_id and pov.language_id = '" . $languages_id . "'" . " order by pa.products_options_sort_order, pov.products_options_values_name");
					} else {
						$temp_query1= tep_db_query("select pa.products_options_sort_order, pa.options_id, pa.options_values_id, pov.products_options_values_id, pov.products_options_values_name, pa.options_values_price, pa.price_prefix from " . TABLE_PRODUCTS_ATTRIBUTES . " pa, " . TABLE_PRODUCTS_OPTIONS_VALUES . " pov where pa.products_id = '" . $products_id . "' and pa.options_id = '" . $result['products_options_id'] . "' and pa.options_values_id = pov.products_options_values_id and pov.language_id = '" . $languages_id . "'" . " order by pa.products_options_sort_order, pa.options_values_price");
					}
					$lcnt=0;
					while ($options_values = tep_db_fetch_array($temp_query1)) {
						$value_extra_option=" and attributes_id like '%" . tep_db_input($result['products_options_id']) . '{' . tep_db_input($options_values["products_options_values_id"]) . "}%'";
						$stock_check_query = tep_db_query("select attributes_id from ". TABLE_PRODUCTS_STOCK . " where products_id = '".  $products_id ."'" . $value_extra_option);
						if (tep_db_num_rows($stock_check_query)>0){
							$attrbcnt=$attrbcnt+1;
							$lcnt++;
							$temp_name=$options_values['products_options_values_name'];
								$pattributes.=$options_values["products_options_values_id"] . ":" . $options_values['price_prefix'] . tep_add_tax($options_values['options_values_price'], $tax_rate) . ",";
						}
					}
					$pattributes.="0:0},";
				if($lcnt>0)	
					$initial++;
			}
			$pattributes.="op0:0},count:" . $initial . "}";
		}
		if($attrbcnt>0) return $pattributes; else return '{enabled:false,count:0}';
	}	
	function tep_get_products_breaks($products_id){
		global $currencies;
		$ppbreaks="{enabled:false}";
		$products_price_break_sql = "select * from " . TABLE_PRODUCTS_PRICE_BREAK . " ppb where products_id = '" . $products_id . "' order by quantity";
		$products_price_break_query = tep_db_query($products_price_break_sql);
		$products_price_sql = "select products_price,products_tax_class_id from " . TABLE_PRODUCTS . " p where products_id = '" . $products_id . "'";
		$products_price_query = tep_db_query($products_price_sql);
		$products_price_result = tep_db_fetch_array($products_price_query);
		if(tep_db_num_rows($products_price_break_query)<=0) return $ppbreaks;
		$ppbreaks="{enabled:true,prices:{";
		while($products_price_break_result = tep_db_fetch_array($products_price_break_query)){
			$price= $products_price_break_result['quantity']*tep_add_tax(($products_price_result['products_price'] - $products_price_break_result['discount_per_item']),tep_get_tax_rate($products_price_result["products_tax_class_id"]));
			$ppbreaks.=$products_price_break_result['quantity'] .":" . $price . ",";
		}
		$ppbreaks=substr($ppbreaks,0,-1) . "}}";
		return $ppbreaks;
	}
	
	function ucmp($a, $b) 
	{
	   if ($a == $b) {
		   return 0;
	   }
	   return (intval($a) < intval($b)) ? -1 : 1;
	}

?>
<script language="javascript">
	var prev;
	var products_stock='';
	var prevQuantity=1;
	function setQuantity(object,qty){
		var icnt,n;
		if (!document.getElementById("tablePriceBreaks")) return;
		if (object=="") object=document.getElementById("tablePriceBreaks").rows[1];
		object.className="moduleRowSelected";
		document.getElementById("qty").value=qty;
		if(prev && prev!=object) 
			prev.className="moduleRow";
			prev=object;	
			
		setTotalPrice();
		if (products.priceAttr.enabled){
			for (icnt=0,n=products.priceAttr.count;icnt<n;icnt++){
				if (document.getElementById("attrValues["+icnt+"]").selectedIndex>0) {
					price=getAttributePrice(icnt);
					setAttrDisplayPrice(price,icnt);
				}
			}
		}
			checkStock('stockProductQuan');
	}
	
	function setTotalPrice(){
		var icnt,n,totalPrice,exString='';
		element=document.getElementById("totalProductsPrice");
		if (!element) return;
		if (!products["priceCalc"].length) return;
		totalPrice=0;
		exString+="totalPrice=";
		for (icnt=0,n=products["priceCalc"].length;icnt<n;icnt++){
			exString+=products["priceCalc"][icnt]+"+";
		}
		eval(exString+"0");
		element.innerHTML=formatCurrency(totalPrice);
	}

	function selectAttribute(object,index){
		var price=0;
		if (object.selectedIndex>0) price=getAttributePrice(index);
		setAttrDisplayPrice(price,index);
		setTotalPrice();
		if (object.selectedIndex>0) checkStock("stockAttrQuan");
	}
	
	function setAttrDisplayPrice(price,index){
		if (!document.getElementById("attrPrice"+index)) return;
		if (price!=0){
			document.getElementById("attrPrice"+index).innerHTML=(price>0?'+':'-')+formatCurrency(Math.abs(price));
		} else {
			document.getElementById("attrPrice"+index).innerHTML="&nbsp;";
		}
	}
	
	function selectDiscount(id){
		if (products["saleMaker"].sales[id]){
			document.getElementById("salemaker_info").innerHTML=products["saleMaker"].sales[id].warning;
			document.getElementById("salemaker_info").style.display="block";
		} else {
			document.getElementById("salemaker_info").innerHTML='';
			document.getElementById("salemaker_info").style.display="none";
		}
		setTotalPrice();
	}

	function getProductsPrice(){
		var price=0,quan,id;
		quan=getProductsQuantity();
		if (products["priceBreaks"].enabled && quan>1 && products["priceBreaks"].prices[quan]){
			price=products["priceBreaks"].prices[quan];
		} else if (products["saleMaker"] && products["saleMaker"].enabled){
			salemaker=document.forms["new_product"].elements["salemaker_id"];
			for (icnt=0,n=salemaker.length;icnt<n;icnt++){
				if (salemaker[icnt].checked) {
					id=salemaker[icnt].value;
					break;
				}
			}
			if (id>0){
				price=products["saleMaker"].sales[id].price*quan;
			} else {
				price=parseFloat(document.getElementById("product_price").value)*quan;
			}
		} else {
			price=parseFloat(document.getElementById("product_price").value)*quan;
		}
		return price;
	}
	
	function getAttributePrice(index){
		var price=0,fromIndex,toIndex,icnt,quan,element,element1;
		if (!products.priceAttr.enabled) return price;
		if (index==-1) {
			fromIndex=0;
			toIndex=products.priceAttr.count-1;
		} else {
			fromIndex=toIndex=index;
		}
		quan=getProductsQuantity();
		for (icnt=fromIndex;icnt<=toIndex;icnt++){
			element=document.getElementById("attrIds["+icnt+"]");
			element1=document.getElementById("attrValues["+icnt+"]");
			if (!element || !element1) break;
			attrValue=parseInt(element1.value);
			if (attrValue>0) {
				price+=(products.priceAttr.prices["op"+element.value][attrValue]*quan);
			}
		}
		return price;
	}
	
	function getProductsQuantity(){
		var quan=1;
		if (document.getElementById("qty"))
			quan=parseInt(document.getElementById("qty").value);
		if (!quan || isNaN(quan) || quan<=0) quan=1;
		return quan;
	}
	
	function checkStock(idMsg){
		var ids,command,quan;
		products_stock=document.getElementById('product_stock').value;
		quan=getProductsQuantity();
		
		if(!products.priceBreaks.enabled) 
			quanAutoCheck();
		if (quan>products_stock) {
			toggleOutStock(false);
			return;
		} 
		
		if (!products.valid) toggleOutStock(true);
		if (!products.priceAttr.enabled) return;
		
		ids=getAttributeValues(true);
		if (ids=="") return;
		command="<?php echo tep_href_link(FILENAME_CREATE_ORDER_NEW,'command=check_attrib_stock')?>" + "&products_id="+products.id+"&attrib_ids="+ids+"&quan="+quan;
		toggleLoadMsgs(idMsg,2);
		products.valid=false;
		do_get_command(command);
	}
	
	function toggleLoadMsgs(id,mode){
		var element=document.getElementById(id);
		if (!element) return;
		
		if (mode==2) element.style.display="";
		else {
			element.style.display="none";
		}
	}
	
	function getAttributeValues(allCheck){
		var icnt,n,ids="";
		for (icnt=0,n=products.priceAttr.count;icnt<n;icnt++){
			if (document.getElementById("attrValues["+icnt+"]").value<=0) {
				if (allCheck) return "";
				break;
			}
			if (ids!="") ids+="-";
			ids+=document.getElementById("attrIds["+icnt+"]").value+"{"+document.getElementById("attrValues["+icnt+"]").value+"}";
		}
		return ids;
	}
	
	function toggleOutStock(flag){
		if (flag){
			products.valid=true;
			document.getElementById("outstock").style.display="none";
			document.getElementById("save").style.display="";
			document.getElementById("save1").style.display="";
		} else{
			products.valid=false;
			document.getElementById("outstock").style.display="";
			document.getElementById("save").style.display="none";
			document.getElementById("save1").style.display="none";
		}
	}

	function formatCurrency(Num) {
		var sym_left=products.currency.symbolLeft;
		var sym_right=products.currency.symbolRight;
		if (typeof(Num)=="number") {
			Num=doRound(Num,2);
			Num=""+Num;
		} else {
			Num=""+doRound(parseFloat(Num),2);
		}
		
		dec = Num.indexOf(".");
		end = ((dec > -1) ? "" + Num.substring(dec,Num.length) : ".00");
		Num = "" + parseInt(Num);
	
		var temp1 = "";
		var temp2 = "";
		
		if (end.length == 2) end += "0";
		if (end.length == 1) end += "00";
		if (end == "") end += ".00";
	
		var count = 0;
		for (var k = Num.length-1; k >= 0; k--) {
		var oneChar = Num.charAt(k);
		if (count == 3 && oneChar!="-") {
		temp1 += ",";
		temp1 += oneChar;
		count = 1;
		continue;
		}
		else {
		temp1 += oneChar;
		count ++;
		   }
		}
		for (var k = temp1.length-1; k >= 0; k--) {
		var oneChar = temp1.charAt(k);
		temp2 += oneChar;
		}
		temp2 = sym_left + temp2 + end + sym_right;
		return temp2;
	}
	
	function quanAutoCheck(){
		quan=getProductsQuantity();
		if (prevQuantity!=quan){
			products.valid=false;
			if (products.priceAttr.enabled){
				for (icnt=0,n=products.priceAttr.count;icnt<n;icnt++){
					if (document.getElementById("attrValues["+icnt+"]").selectedIndex>0) {
						price=getAttributePrice(icnt);
						setAttrDisplayPrice(price,icnt);
					}
				}
			}
			setTotalPrice();
			prevQuantity=quan;
		}
	}
function numericOnly(e) {
	var iKeyCode;
	if (!e) {
		var e = window.event;
	}
	if (e.keyCode) {
		iKeyCode = e.keyCode;
	} else {
		if (e.which) {
			iKeyCode = e.which;
		}
	}
	switch(iKeyCode) {
		case 8:
		case 9:
		case 37:
		case 38:
		case 39:
		case 40:
		case 46:
		break;
		case 48:
		case 49:
		case 50:
		case 51:
		case 52:
		case 53:
		case 54:
		case 55:
		case 56:
		case 57:
			if (e.shiftKey || e.altKey){
				return false;
			}
		break;
		case 96:
		case 97:
		case 98:
		case 99:
		case 100:
		case 101:
		case 102:
		case 103:
		case 104:
		case 105:
		//return correct numeric from keypad
			return iKeyCode - 48; break;
		case 110:
		//case 190:
		//if you are supporting decimal points
		//return '.'; break;
		default: return false;
	}
} 
	
	
	function show_manual_price()
	{
	 var tot_value,tot_update_value;
	tot_value=parseFloat(shop_price);
	//tot_update_value=parseFloat(shop_updated_price);
	if(document.getElementById('manual_priceadjust_option').checked==true){
			document.getElementById('mpa').style.display='';
			}
		else {
			document.getElementById('mpa').style.display='none';
			//if(document.getElementById("up_tot")) document.getElementById("up_tot").innerHTML=dollarAmount((tot_update_value));
		 if(document.getElementById("net_tot")) document.getElementById("net_tot").innerHTML=dollarAmount((tot_value));
		}
	
	}
	
	function modify_price()
	{
	    //shop_price comes from do_result
	    var tot_value,tot_update_value;
		var val=0;
		//if(document.getElementById("modify_price_prefix").value=='' ) return;
		
		if(document.getElementById("sign"))
		var sign=document.getElementById("sign").value;
		var purpose=document.getElementById("purpose").value;
		var element=parseFloat(document.getElementById("modify_price_prefix").value);
		if(document.getElementById("modify_price_prefix").value=='' ) element=0;
		if(isNaN(element))
		{
			document.getElementById("modify_price_prefix").value='';
			return;
		}
		tot_value=parseFloat(shop_price);
		//tot_update_value=parseFloat(shop_updated_price);
		
		if(sign=='+'){
		   val=tot_value+element;
		  // update_val=tot_update_value+element;
		 }
		else{
		   val=tot_value-element; 
		  // update_val=tot_update_value-element;
		   //alert (update_val);
		}
		
		// if(document.getElementById("up_tot")) document.getElementById("up_tot").innerHTML=dollarAmount(update_val);
		 if(document.getElementById("net_tot")) document.getElementById("net_tot").innerHTML=dollarAmount(val);
	}
	
</script>
