<?php

/*

  osCommRes, Services Online
  http://www.oscommres.com

  Copyright (c) 2005 osCommRes

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

Copyright 2007 ZacWare Pty. Ltd
*/
// Set flag that this is a parent file
	define( '_FEXEC', 1 );

  require('includes/application_top.php');
  require(DIR_WS_CLASSES . 'currencies.php');
  require(DIR_WS_CLASSES . 'payment.php');
  $currencies = new currencies();
  include(DIR_WS_CLASSES . 'order.php');
  include(DIR_WS_FUNCTIONS . 'subscription_tree.php');
  //subscription type
  $type_array=array('B'=>TEXT_SUBSCRIPTION_BASIC,
					'C'=>TEXT_SUBSCRIPTION_CASUAL,
					'S'=>TEXT_SUBSCRIPTION_SEASONAL
					);
  
  $oID=(isset($HTTP_GET_VARS['oID'])?(int)$HTTP_GET_VARS['oID']:0);
  $action=(isset($HTTP_GET_VARS['action'])?$HTTP_GET_VARS['action']:'');
  $step=(isset($HTTP_GET_VARS['step'])?(int)$HTTP_GET_VARS['step']:1);
  	       $edit_cart=new editOrderCart($oID);
		   

  if ((int)$oID<=0)
    tep_redirect(tep_href_link(FILENAME_ORDERS));

  if (!($step>=1 && $step<=4)){
    tep_redirect(tep_href_link(FILENAME_ORDERS));
  }

  // confirm order entry in the table before procedding
  $orders_query = tep_db_query("select orders_id,customers_id from " . TABLE_ORDERS . "  where orders_id = '" . (int)$oID . "'");
  $order_exists = true;
  if (!tep_db_num_rows($orders_query)) {
      $order_exists = false;
      $action="";
      //$messageStack->add_Session('orders',sprintf(ERROR_ORDER_DOES_NOT_EXIST, $oID), 'error');
      tep_redirect(tep_href_link(FILENAME_ORDERS));
  }
  $order_result=tep_db_fetch_array($orders_query);
  
  // check the order id with element in temporart edit cart and recreate the edit cart
  if (!tep_session_is_registered('edit_order') || $edit_order!=$oID){
          tep_session_unregister('edit_order');
	       $edit_cart=new editOrderCart($oID);
	       $edit_cart->restore_contents();
	       tep_session_register('edit_order');
	       $edit_order=$oID;
  } else {
     if (!tep_session_is_registered('edit_order'))
	   tep_redirect(tep_href_link(FILENAME_ORDERS));
  }
  $order_timestamp=time();
  if (!tep_session_is_registered('order_timestamp')) tep_session_register('order_timestamp');

  if (tep_not_null($action)) {
    switch ($action) {
	case 'insert_subscription':
			// Get Order Info
			$oID = tep_db_prepare_input($HTTP_GET_VARS['oID']);
			$order = new order($oID);
                        //$mode=(isset($HTTP_GET_VARS['mode'])?$HTTP_GET_VARS['mode']:'');
			$id=(isset($HTTP_GET_VARS['id'])?(int)$HTTP_GET_VARS['id']:0);
			$AddedOptionsPrice = 0;

			$InfoQuery = "select su.subscription_costs,sud.subscription_name,su.subscription_tax_class_id,su.subscription_type from " . TABLE_SUBSCRIPTIONS . " su left join " . TABLE_SUBSCRIPTIONS_DESCRIPTION . " sud on sud.subscription_id=su.subscription_id where su.subscription_id='$add_subscription_subscriptions_id'";
			$result = tep_db_query($InfoQuery);
			$row = tep_db_fetch_array($result);
			if(tep_db_num_rows($result)=="0"){
				tep_redirect(tep_href_link(FILENAME_ADDSUBSCRIPTIONS,"oID=$oID&action=add_subscription&step=1&mode=add"));
			}else {
			extract($row, EXTR_PREFIX_ALL, "su");
			}
			$your_date = tep_convert_date_raw($HTTP_POST_VARS["your_start_date"]);
			$subscription_type_sql = "select subscription_date_type from " . TABLE_SUBSCRIPTIONS . " where subscription_id=" . $add_subscription_subscriptions_id;
			$subscription_type_query = tep_db_query($subscription_type_sql);
			$subscription_type_result = tep_db_fetch_array($subscription_type_query);
			if($subscription_type_result['subscription_date_type']=='F')
				$subscription_details_sql = "select subscription_id,subscription_type as type,subscription_date_type,deliveries,deliveries_perday,deliveries_name,subscription_start_date as start_date,subscription_finish_date as finish_date from " . TABLE_SUBSCRIPTIONS . " where subscription_id=" . $add_subscription_subscriptions_id;
			else if($subscription_type_result['subscription_date_type']=='L')
				$subscription_details_sql = "select subscription_id,subscription_type as type,subscription_date_type,deliveries,deliveries_perday,deliveries_name,date_format(date_add(now(),INTERVAL 1 DAY),'%Y-%m-%d') as start_date,date_format(date_add(now(), INTERVAL subscription_period DAY),'%Y-%m-%d') as finish_date from " . TABLE_SUBSCRIPTIONS . " where subscription_id=" . $add_subscription_subscriptions_id;
			else if($subscription_type_result['subscription_date_type']=='P')
				$subscription_details_sql = "select subscription_id,subscription_type as type,subscription_date_type,deliveries,deliveries_perday,deliveries_name,date_format('" . $your_date . "','%Y-%m-%d') as start_date,date_format(date_add('" . $your_date . "', INTERVAL (subscription_period-1) DAY),'%Y-%m-%d') as finish_date from " . TABLE_SUBSCRIPTIONS . " where subscription_id=" . $add_subscription_subscriptions_id;
			else
				$subscription_details_sql = "select subscription_id,subscription_type as type,subscription_date_type,deliveries,deliveries_perday,deliveries_name,subscription_start_date as start_date,subscription_finish_date as finish_date from " . TABLE_SUBSCRIPTIONS . " where subscription_id=" . $add_subscription_subscriptions_id;
			$subscription_details_query = tep_db_query($subscription_details_sql);
			$subscription_details_result = tep_db_fetch_array($subscription_details_query);

			// Following functions are defined at the bottom of this file
			$CountryID = tep_get_country_id($order->billing["country"]);
			$ZoneID = tep_get_zone_id($CountryID, $order->billing["state"]);
			
			$ProductsTax = tep_get_tax_rate($su_subscription_tax_class_id, $CountryID, $ZoneID);
			
			$sql_array=array('orders_id'=>$oID,
					'products_id' => $add_subscription_subscriptions_id,
					'products_name' =>  str_replace("'", "&#39;", $su_subscription_name),
					'products_price' => $su_subscription_costs,
					'final_price' => ($su_subscription_costs + $AddedOptionsPrice),
					'products_tax' => $ProductsTax,
					'products_quantity' => 1,
					'products_type'=>'S',
	 				'date_added'=>'now()',
					'products_model'=>$type_array[$su_subscription_type]
					);
			
			$subscription_first_sql_array = array('orders_id'=>$oID,
									'products_id' => $subscription_details_result["subscription_id"],
									'type' => $subscription_details_result["type"],
									'deliveries' => $subscription_details_result["deliveries"],
									'deliveries_perday' => $subscription_details_result["deliveries_perday"],
									'deliveries_name' => $subscription_details_result["deliveries_name"]
									);
			if($subscription_details_result["subscription_date_type"]=='F' || $subscription_details_result["subscription_date_type"]=='L' || $subscription_details_result["subscription_date_type"]=='P'){
				$subscription_second_sql_array = array('start_date' => $subscription_details_result["start_date"],
												'finish_date' => $subscription_details_result["finish_date"]);
			}else{ 
				$subscription_second_sql_array = array('start_date' => '0000-00-00',
													'finish_date' => '0000-00-00');
			}
			// if the current operation is editing or inserting a new entry
			if ($mode=="edit"){
			   tep_db_perform(TABLE_ORDERS_EDIT_PRODUCTS,$sql_array,'update',"orders_products_id='" . (int)$id  . "'");
				$subscription_sql_array = array_merge($subscription_first_sql_array,$subscription_second_sql_array);
			   tep_db_perform(TABLE_ORDERS_EDIT_SUBSCRIPTIONS,$subscription_sql_array,'update',"orders_products_id='" . (int)$id  . "'");
			   $new_subscription_id=$id;
			} else {
				tep_db_perform(TABLE_ORDERS_EDIT_PRODUCTS,$sql_array);
			    $new_subscription_id = tep_db_insert_id();
				$subscription_third_sql_array = array('orders_products_id' => $new_subscription_id);
				$subscription_sql_array = array_merge($subscription_first_sql_array,$subscription_second_sql_array,$subscription_third_sql_array);
				tep_db_perform(TABLE_ORDERS_EDIT_SUBSCRIPTIONS,$subscription_sql_array);
			}
			tep_redirect(tep_href_link(FILENAME_EDIT_ORDERS, 'oID=' . $oID . '&step=2'));
			break;
    }
  }

?>
<!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; ?>">
<title><?php echo TITLE; ?></title>
<link rel="stylesheet" type="text/css" href="includes/stylesheet.css">
<script language="javascript" src="includes/general.js"></script>
<script language="javascript" src="includes/date-picker.js"></script>
</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF">
<!-- header //-->
<?php
	include('includes/date_format_js.php');
  require(DIR_WS_INCLUDES . 'header.php');
?>
<!-- header_eof //-->

<!-- body //-->
<table border="0" width="100%" cellspacing="2" cellpadding="2">
  <tr> 
<!-- body_text //-->
    <td width="100%" valign="top"><table border="0" width="100%" cellspacing="0" cellpadding="2">
<script language="javascript">    
	function validate_subscription_form(){
		var error="";
		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 false;
			} 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 false;
		}
		return true;
	}

function Validate(obj){
	var error_result="";
	for(i=0;i<obj.length;i++){
		if(obj.elements[i].type=="select-one"){
			if(obj.elements[i].value<=0){
				alert('<?php echo ERR_SELECT_ATTRIBUTES;?>');
				return false;
			}
		}		
	}
	return true;
}

</script>
<?php
  if ($order_exists == true && $action=='') {
    $order_detail = new order($oID);
?>

      <tr>
	<td valign=top><table width="100%" border="0" cellspacing="0" cellpadding="2">
<?php if ($step==1){ ?>
	  <tr>
	    <td colspan="2"><?php echo tep_draw_separator('pixel_trans.gif','1','3'); ?></td>
	  </tr>
	  <tr>
	    <td valign="top">
		<table border="0" cellspacing="2" cellpadding="2" width=60%>
		<tr>
		    <td class="main" width=30%><?php echo TEXT_NAME; ?></td>
		    <td class="main"><?php echo tep_draw_input_field('update_customer_name',tep_html_quotes($order_detail->customer['name']),'size=37',true); ?></td>
		</tr>
		<tr>
		    <td class="main" width=30%><?php echo TEXT_COMPANY; ?></td>
		    <td class="main"><?php echo tep_draw_input_field('update_customer_company',tep_html_quotes($order_detail->customer['company']),'size=37'); ?></td>
		</tr>
		<tr>
		    <td class="main"><?php echo TEXT_ADDRESS; ?></td>
		    <td class="main"><?php echo tep_draw_input_field('update_customer_street_address',tep_html_quotes($order_detail->customer['street_address']),'size=37',true); ?></td>
		</tr>
		<tr>
		    <td class="main"><?php echo TEXT_SUBURB; ?></td>
		    <td class="main"><?php echo tep_draw_input_field('update_customer_suburb',tep_html_quotes($order_detail->customer['suburb']),'size=37',true); ?></td>
		</tr>
		<tr>
		    <td class="main"><?php echo TEXT_POSTCODE; ?></td>
		    <td class="main"><?php echo tep_draw_input_field('update_customer_postcode',tep_html_quotes($order_detail->customer['postcode']),'size=37',true); ?></td>
		</tr>
		<tr>
		    <td class="main"><?php echo TEXT_CITY; ?></td>
		    <td class="main"><?php echo tep_draw_input_field('update_customer_city',tep_html_quotes($order_detail->customer['city']),'size=37',true); ?></td>
		</tr>
		<tr>
		    <td class="main"><?php echo TEXT_STATE; ?></td>
		    <td class="main"><?php echo tep_draw_input_field('update_customer_state',tep_html_quotes($order_detail->customer['state']),'size=37',true); ?></td>
		</tr>
		<tr>
		    <td class="main"><?php echo TEXT_COUNTRY; ?></td>
		    <td class="main"><?php echo tep_draw_input_field('update_customer_country',tep_html_quotes($order_detail->customer['country']),'size=37',true); ?></td>
		</tr>
		</table>
	    </td>
	    </tr>
	  <tr>
	    <td colspan="2"><?php echo tep_draw_separator('pixel_trans.gif','1','5'); ?></td>
	  </tr>
<?php } ?>
      <table>
      </form>
<?php
  }

// Add Subscriptions
if($action == "add_subscription")
{
  $mode=(isset($HTTP_GET_VARS['mode'])?$HTTP_GET_VARS['mode']:'');
  $id=(isset($HTTP_GET_VARS['id'])?(int)$HTTP_GET_VARS['id']:'');
  $add_step=(isset($HTTP_POST_VARS['add_step'])?(int)$HTTP_POST_VARS['add_step']:0);
  if ((int)$add_step==0 && $mode=='edit'){
  	$data_sql = "SELECT op.products_id,p2c.categories_id,op.products_quantity from " . TABLE_ORDERS_PRODUCTS . " op, " . TABLE_PRODUCTS_TO_CATEGORIES . " p2c where op.orders_products_id='" . $id . "' and op.products_id=p2c.products_id";
	 $data_query=tep_db_query($data_sql);
     $data_result=tep_db_fetch_array($data_query);
     $add_subscription_categories_id=$data_result['categories_id'];
     $add_subscription_subscriptions_id=$data_result['products_id'];
     $add_subscription_quantity=$data_result['products_quantity'];
     $step=3;
  }
?>
      <tr>
        <td width="100%"><table border="0" width="100%" cellspacing="0" cellpadding="0">
          <tr>
            <!--<td class="pageHeading"><?php //echo ADDING_CATEGORIES_TITLE; ?> #<?php //echo $oID; ?></td>!-->
            <td class="pageHeading" align="right"><?php echo tep_draw_separator('pixel_trans.gif', 1, HEADING_IMAGE_HEIGHT); ?></td>
            <td class="pageHeading" align="right">
	    <?php
	          echo '<a href="' . tep_href_link(FILENAME_EDIT_ORDERS, 'oID=' . $oID . '&step=2') . '">' . tep_image_button('button_back.gif', IMAGE_BACK) . '</a>'; ?></td>
          </tr>
        </table></td>
      </tr>

<?
	// ############################################################################
	//   Get List of All Products
	// ############################################################################

		$result = tep_db_query("SELECT subscription_name, su.subscription_id, subscription_categories_name, suTsuc.subscription_categories_id FROM " . TABLE_SUBSCRIPTIONS . " su LEFT JOIN " . TABLE_SUBSCRIPTIONS_DESCRIPTION . " sud ON sud.subscription_id=su.subscription_id LEFT JOIN " . TABLE_SUBSCRIPTION_TO_SUBSCRIPTION_CATEGORIES . " suTsuc ON suTsuc.subscription_id=su.subscription_id LEFT JOIN " . TABLE_SUBSCRIPTION_CATEGORIES_DESCRIPTION . " scd ON scd.subscription_categories_id=suTsuc.subscription_categories_id where su.subscription_id = suTsuc.subscription_id " . SUBSCRIPTION_CONDITION_STATUS . "  ORDER BY subscription_categories_name");
		$SubscriptionList = array();
		while($row = tep_db_fetch_array($result))
		{
			extract($row,EXTR_PREFIX_ALL,"db");
			$SubscriptionList[$db_subscription_categories_id][$db_subscription_id] = $db_subscription_name;
			$Subscription_CategoryList[$db_subscription_id] = $db_subscription_categories_name;
			$LastCategory = $db_subscription_categories_name;
		}
		// ksort($ProductList);
		$LastOptionTag = "";
		$SubscriptionSelectOptions = "<option value='0'>Don't Add New Subscription" . $LastOptionTag . "\n";
		$SubscriptionSelectOptions .= "<option value='0'>&nbsp;" . $LastOptionTag . "\n";
		foreach($SubscriptionList as $subscription_Category =>$subscription)
		{
			$SubscriptionSelectOptions .= "<option value='0'>$subscription_Category" . $LastOptionTag . "\n";
			$SubscriptionSelectOptions .= "<option value='0'>---------------------------" . $LastOptionTag . "\n";
			asort($subscription);
			foreach($subscription as $subscription_ID => $subscription_Name)
			{
				$SubscriptionSelectOptions .= "<option value='$subscription_id'> &nbsp; $subscription_Name" . $LastOptionTag . "\n";
			}
			
			if($subscription_Category != $LastCategory)
			{
				$SubscriptionSelectOptions .= "<option value='0'>&nbsp;" . $LastOptionTag . "\n";
				$SubscriptionSelectOptions .= "<option value='0'>&nbsp;" . $LastOptionTag . "\n";
			}
		}
	// ############################################################################
	//   Add Products Steps
	// ############################################################################
		print "<tr><td><table border='0'>\n";
		// Set Defaults
			if(!IsSet($add_subscription_categories_id))
			$add_subscription_categories_id = 0;

			if(!IsSet($add_subscription_subscriptions_id))
			$add_subscription_subscriptions_id = 0;
		// Step 1: Choose Product
			print "<tr class=\"dataTableRow\"><form action='$PHP_SELF?oID=$oID&action=$action&mode=$mode&id=$id' method='POST'>\n";
			print "<td class='dataTableContent' align='right'><b>Select Subscription:</b></td><td class='dataTableContent' valign='top'>";
			//echo tep_draw_pull_down_menu('add_subscription_subscriptions_id',tep_get_subscription_display_tree(),$add_subscription_subscriptions_id);
			$subscription_array = array();
			$subscription_array = tep_get_subscription_array_single();
			if(sizeof($subscription_array)<=0) echo 'Subscription Are Not Available';
			else echo tep_draw_subscription_select_menu('add_subscription_subscriptions_id',$subscription_array,$add_subscription_subscriptions_id,' id="add_subscription_subscriptions_id"');
			print "<td class='dataTableContent' align='center'>".tep_image_submit('button_select.gif', 'search');
			print "<input type='hidden' name='add_subscription_categories_id' value='$add_subscription_categories_id'>";
			print "<input type='hidden' name='add_step' value='3'>";
			print "</td>\n";
			print "</form></tr>\n";
		// Step 3: Choose Options
		if(($add_step > 2) && ($add_subscription_subscriptions_id > 0))
		{
				$add_step = 4;
			}
				print "</td>";
				print "</form></tr>\n";
			print "<tr><td colspan='3'>&nbsp;</td></tr>\n";
		// Step 4: Confirm
		if($add_step > 3)
		{
		  	$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';
			$post_subscription_id = (isset($HTTP_POST_VARS['add_subscription_subscriptions_id'])?(int)$HTTP_POST_VARS['add_subscription_subscriptions_id']:0);
			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 = '" . $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 "<tr class=\"dataTableRow\"><form name='add_new_subscription' action='$PHP_SELF?oID=$oID&action=insert_subscription&mode=$mode&id=$id' method='POST' onSubmit='return validate_subscription_form();'>\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 = '" . $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='" .$add_subscription_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'>";
					//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 class=\"dataTableRow\"><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 class="dataTableRow">
						<td class="smallText" valign="top">
								<?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 class="dataTableRow">
						<td class="smallText" valign="top" colspan="2"><?php echo $subscription_details;?></td>
					  </tr>
					  <?php  if($cos_and_type_value['subscription_date_type']=='P'){?>
					  <tr class="dataTableRow">
						<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  "<tr><td class='dataTableContent'align='right' vailgn='middle' colspan='3'>";
					print tep_image_submit('button_add.gif', 'add') . "</td></tr>";
				}
		}

			 if(IsSet($add_subscription_options))
			{
				foreach($add_subscription_options as $option_id => $option_value_id)
				{
					print "<input type='hidden' name='add_subscription_options[$option_id]' value='$option_value_id'>";
				}
			}
			print "<input type='hidden' name='add_subscription_categories_id' value='$add_subscription_categories_id'>";
			print "<input type='hidden' name='add_subscription_subscriptions_id' value='$add_subscription_subscriptions_id'>";
			print "<input type='hidden' name='add_step' value='5'>";
			//print "</td>\n";
			print "</form></tr>\n";
		}
		
		print "</table></td></tr>\n";?>		
<?php }
 ?>
 <?php if($cos_and_type_value['subscription_date_type'] == 'P'){?>
<script language="javascript" type="text/javascript">
	check_date();
	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>
<?php }?>
    </table></td>
<!-- body_text_eof //-->
  </tr>
</table>
<!-- body_eof //-->

<!-- footer //-->
<?php require(DIR_WS_INCLUDES . 'footer.php'); ?>
<!-- footer_eof //-->
</body>
</html>
<?
  ////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // Function    : tep_get_country_id
  //
  // Arguments   : country_name		country name string
  //
  // Return      : country_id
  //
  // Description : Function to retrieve the country_id based on the country's name
  //
  ////////////////////////////////////////////////////////////////////////////////////////////////
  function tep_get_country_id($country_name) {

    $country_id_query = tep_db_query("select * from " . TABLE_COUNTRIES . " where countries_name = '" . $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
  //
  // Arguments   : country_id		country id string
  //               zone_name		state/province name
  //
  // Return      : zone_id
  //
  // Description : Function to retrieve the zone_id based on the zone's name
  //
  ////////////////////////////////////////////////////////////////////////////////////////////////
  function tep_get_zone_id($country_id, $zone_name) {

    $zone_id_query = tep_db_query("select * from " . TABLE_ZONES . " where zone_country_id = '" . $country_id . "' and zone_name = '" . $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_field_exists
  //
  // Arguments   : table	table name
  //               field	field name
  //
  // Return      : true/false
  //
  // Description : Function to check the existence of a database field
  //
  ////////////////////////////////////////////////////////////////////////////////////////////////
  function tep_field_exists($table,$field) {

    $describe_query = tep_db_query("describe $table");
    while($d_row = tep_db_fetch_array($describe_query))
    {
      if ($d_row["Field"] == "$field")
      return true;
    }


    return false;
  }

  ////////////////////////////////////////////////////////////////////////////////////////////////
  //
  // Function    : tep_html_quotes
  //
  // Arguments   : string	any string
  //
  // Return      : string with single quotes converted to html equivalent
  //
  // Description : Function to change quotes to HTML equivalents for form inputs.
  //
  ////////////////////////////////////////////////////////////////////////////////////////////////
  function tep_html_quotes($string) {
    return str_replace("'", "&#39;", $string);
  }

require(DIR_WS_INCLUDES . 'application_bottom.php');
?>