<?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');
  $currencies = new currencies();
  // Loding DropDown Boxes Using Ajax
  $command = (isset($HTTP_GET_VARS['command'])?$HTTP_GET_VARS['command']:'');
  if($command == "fetch_attrib_qty"){	
	   $attrib = (isset($HTTP_GET_VARS['attrib'])?$HTTP_GET_VARS['attrib']:'');
		$value = (isset($HTTP_GET_VARS['value_array'])?$HTTP_GET_VARS['value_array']:'');
	    $add_product_products_id = (isset($HTTP_GET_VARS['add_prd_id'])?$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 $instock_quantity;
		exit;
	}
  if($command == "fetch_attrib_val"){
		$att_id = (isset($HTTP_GET_VARS['sel_attrib'])?$HTTP_GET_VARS['sel_attrib']:'');
		$prd_id = (isset($HTTP_GET_VARS['product_id'])?$HTTP_GET_VARS['product_id']:'');
		$combo_name = (isset($HTTP_GET_VARS['combo_name'])?$HTTP_GET_VARS['combo_name']:'');
		$pre_id = (isset($HTTP_GET_VARS['previous_id'])?$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;
			}
			//$pre_n = count($pre_ids)-1;
		}
		$p = count($pre_ids);
		//print_r($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 = " .$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);
		//print_r($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= " . $att_id);	
	//echo "select products_options_id from products_options_values_to_products_options where products_options_values_id= " . $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 = " . $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;
			 }
		  }
		}
		
	//echo "load" . $load_ids;
	$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= ". $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;
		 exit;
	}
  require(DIR_WS_CLASSES . 'payment.php');
  include(DIR_WS_CLASSES . 'order.php');

  $orders_statuses = array();
  $orders_status_array = array();
  $orders_status_query = tep_db_query("select orders_status_id, orders_status_name from " . TABLE_ORDERS_STATUS . " where language_id = '" . (int)$languages_id . "'");
  while ($orders_status = tep_db_fetch_array($orders_status_query)) {
    $orders_statuses[] = array('id' => $orders_status['orders_status_id'],
                               'text' => $orders_status['orders_status_name']);
    $orders_status_array[$orders_status['orders_status_id']] = $orders_status['orders_status_name'];
  }
  
  $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) {
	// Add a Product
	case 'insert_product':
			// 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;
			$attribute_ids="";
			// Get Product Attribute Info
			if(IsSet($add_product_options))
			{
				foreach($add_product_options as $option_id => $option_value_id)
				{
					$result = tep_db_query("SELECT * FROM " . TABLE_PRODUCTS_ATTRIBUTES . " pa LEFT JOIN " . TABLE_PRODUCTS_OPTIONS . " po ON po.products_options_id=pa.options_id LEFT JOIN " . TABLE_PRODUCTS_OPTIONS_VALUES . " pov ON pov.products_options_values_id=pa.options_values_id WHERE products_id='$add_product_products_id' and options_id=$option_id and options_values_id=$option_value_id");
					$row = tep_db_fetch_array($result);
					extract($row, EXTR_PREFIX_ALL, "opt");
					$AddedOptionsPrice += $opt_options_values_price;
					$option_value_details[$option_id][$option_value_id] = array ("options_values_price" => $opt_options_values_price);
					$option_names[$option_id] = $opt_products_options_name;
					$option_values_names[$option_value_id] = $opt_products_options_values_name;
					$attribute_ids.=$option_id . '{' . $option_value_id . '}-';
				}
				$attribute_ids=substr($attribute_ids,0,-1);
				$attribute_ids=tep_get_sorted_attribute_ids($attribute_ids);
			}
			
			// Get Product Info
			$InfoQuery = "select p.products_model,p.products_price,pd.products_name,p.products_tax_class_id,p.products_sku from " . TABLE_PRODUCTS . " p left join " . TABLE_PRODUCTS_DESCRIPTION . " pd on pd.products_id=p.products_id where p.products_id='$add_product_products_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_EDIT_ORDERS,"oID=$oID&action=add_product&step=1&mode=add"));
			  // change from(N)
			} else {
			 extract($row, EXTR_PREFIX_ALL, "p");
		 	 $dct_price=tep_discount_price($add_product_products_id,$row['products_price'],tep_get_tax_rate($row['products_tax_class_id']),$order_result['customers_id']);
			 if($dct_price['text']==0 || $dct_price['text']==''){
			   $discount_price=$row['products_price']; 
			 }else if($dct_price['id']=='GD'){
			   $discount_price=$dct_price['text']; 
			 }else if($dct_price['id']=='SP'){
			  $discount_price=$dct_price['text']; 
			 }
			 //changes from (N)
			}
			// 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($p_products_tax_class_id, $CountryID, $ZoneID);

			$sqlQuery = "select * from " . TABLE_ORDERS_EDIT_PRODUCTS . " where orders_id=$oID and products_id=$add_product_products_id and products_type='P'";
			$duplicate_product = tep_db_query($sqlQuery);
			if(tep_db_num_rows($duplicate_product)>0 && $mode!='edit'){
				while($data = tep_db_fetch_array($duplicate_product))
				{
					$id=$data['orders_products_id'];
					$sqlQuery1 = "select * from " . TABLE_ORDERS_EDIT_PRODUCTS_ATTRIBUTES . " where orders_id=$oID and orders_products_id=$id order by products_options_id";
					$duplicate_att = tep_db_query($sqlQuery1);
					if(tep_db_num_rows($duplicate_att)>0){
						$att_ids="";
						while($col = tep_db_fetch_array($duplicate_att))
						{
							$att_ids.=$col['products_options_id'] . '{' . $col['products_options_values_id']. '}-';
						}
						$att_ids=substr($att_ids,0,-1);
						if($att_ids==$attribute_ids)
						{
							$add_product_quantity+=(int)$data['products_quantity'];
							$mode='edit';
							break;
						}
					}
					else
					{
						$add_product_quantity+=(int)$data['products_quantity'];
						$mode='edit';
						break;

					}
				}
			}
			$sku=$row['products_sku'];
			if ($attribute_ids!=''){
				$sku_query=tep_db_query("select sku from " . TABLE_PRODUCTS_STOCK . " where products_id='" . $add_product_products_id . "' and attributes_id='" . $att_ids . "'");
				$sku_result=tep_db_fetch_array($sku_query);
				$sku=$sku_result["sku"];
			}
			  $sql_array=array('orders_id'=>$oID,
				'products_id' => $add_product_products_id,
				'products_model' =>$p_products_model,
				'products_name' =>str_replace("'", "&#39;", $p_products_name),
				'products_price' =>$p_products_price,
				'final_price' => ($discount_price + $AddedOptionsPrice),
				'products_tax' => $ProductsTax,
				'products_quantity' =>$add_product_quantity  ,
				'products_type'=>'P',
				'products_sku'=>$sku
				);
				
			// 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  . "'");
			   $new_product_id=$id;
               tep_db_query("DELETE from " . TABLE_ORDERS_EDIT_PRODUCTS_ATTRIBUTES . " where orders_products_id='" . $id . "'");
			}
			else{
			   tep_db_perform(TABLE_ORDERS_EDIT_PRODUCTS,$sql_array);
			   $new_product_id = tep_db_insert_id();
			}
			
			// add or edit process
			if(IsSet($add_product_options))
			{
				foreach($add_product_options as $option_id => $option_value_id)
				{
					$Query = "insert into " . TABLE_ORDERS_EDIT_PRODUCTS_ATTRIBUTES . " set
						orders_id = $oID,
						orders_products_id = $new_product_id,
						products_options = '" . $option_names[$option_id] . "',
						products_options_id = '" . $option_id ."',
						products_options_values = '" . $option_values_names[$option_value_id] . "',
						products_options_values_id = '". $option_value_id ."',
						options_values_price = '" . $option_value_details[$option_id][$option_value_id]["options_values_price"] . "',
						price_prefix = '+';";
					tep_db_query($Query);
				}
			}
		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/http.js"></script>
</head>
<body marginwidth="0" marginheight="0" topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0" bgcolor="#FFFFFF">
<!-- header //-->
<?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  validateForm1_niloption(prd_quantity){
   var chk = 1;
  if (document.quanform1.add_product_quantity.value=='' || parseInt(document.quanform1.add_product_quantity.value)=='0'	 || isNaN(document.quanform1.add_product_quantity.value) || parseInt(document.quanform1.add_product_quantity.value) < '0'){
  	chk = 2;
	alert('<?php echo ERR_TEXT_QUANTITY; ?>');
	return false;
	} 
 if ((document.quanform1.add_product_quantity.value).indexOf('.') != -1){
	chk=2;
	alert('<?php echo ERR_TEXT_QUANTITY1; ?>');
	return false;
	}
   if (document.quanform1.add_product_quantity.value > prd_quantity ) {
	 chk = 2;
	 alert ('Error : Product Quantity Out of Stock');
	 return false;
	 }
	 if(chk == 1)
	 document.quanform1.submit();
}
/* function  validateForm1(prd_quantity){
 if(document.quanform.add_product_quantity.value==''){
 	alert('<?php echo ERR_TEXT_QUANTITY?>');
	return false;
 }
  if (document.quanform.add_product_quantity.value<0 ||  parseInt(document.quanform.add_product_quantity.value)=='0' || isNaN(document.quanform.add_product_quantity.value)){
  	alert('<?php echo ERR_TEXT_VALID_QUANTITY?>');
	return false;
	}
   if (document.quanform.add_product_quantity.value > prd_quantity ) {
	 alert ('Error : Product Quantity Out of Stock');
	 return false;
	 }
}*/
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
  }
 
if($action == "add_product")
{
  $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);
  $aid=$HTTP_POST_VARS['add_product_options'];
 
  if ((int)$add_step==0 && $mode=='edit'){
  	$data_sql = "SELECT op.products_id,p2c.categories_id,op.products_quantity from " . TABLE_ORDERS_EDIT_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_product_categories_id=$data_result['categories_id'];
     $add_product_products_id=$data_result['products_id'];
     $add_product_quantity=$data_result['products_quantity'];
     $data_query=tep_db_query("SELECT products_options_id,products_options_values_id from " . TABLE_ORDERS_EDIT_PRODUCTS_ATTRIBUTES . " where orders_products_id='" . $id . "' order by products_options_id");
     while($data_result=tep_db_fetch_array($data_query))
	 { 
	 	$add_product_options[$data_result['products_options_id']]=$data_result['products_options_values_id'];
	 }
     $add_step=4;
  }
?>
      <tr>
        <td width="100%"><table border="0" width="100%" cellspacing="0" cellpadding="0">
          <tr>
            <!--<td class="pageHeading"><?php //echo ADDING_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 products_name, p.products_id, categories_name, ptc.categories_id FROM " . TABLE_PRODUCTS . " p LEFT JOIN " . TABLE_PRODUCTS_DESCRIPTION . " pd ON pd.products_id=p.products_id LEFT JOIN " . TABLE_PRODUCTS_TO_CATEGORIES . " ptc ON ptc.products_id=p.products_id LEFT JOIN " . TABLE_CATEGORIES_DESCRIPTION . " cd ON cd.categories_id=ptc.categories_id ORDER BY categories_name");
		$ProductList = array();
		while($row = tep_db_fetch_array($result))
		{
			extract($row,EXTR_PREFIX_ALL,"db");
			$ProductList[$db_categories_id][$db_products_id] = $db_products_name;
			$CategoryList[$db_categories_id] = $db_categories_name;
			$LastCategory = $db_categories_name;
		}
		// ksort($ProductList);
		$LastOptionTag = "";
		$ProductSelectOptions = "<option value='0'>Don't Add New Product" . $LastOptionTag . "\n";
		$ProductSelectOptions .= "<option value='0'>&nbsp;" . $LastOptionTag . "\n";
		foreach($ProductList as $Category => $Products)
		{
			$ProductSelectOptions .= "<option value='0'>$Category" . $LastOptionTag . "\n";
			$ProductSelectOptions .= "<option value='0'>---------------------------" . $LastOptionTag . "\n";
			asort($Products);
			foreach($Products as $Product_ID => $Product_Name)
			{
				$ProductSelectOptions .= "<option value='$Product_ID'> &nbsp; $Product_Name" . $LastOptionTag . "\n";
			}
			
			if($Category != $LastCategory)
			{
				$ProductSelectOptions .= "<option value='0'>&nbsp;" . $LastOptionTag . "\n";
				$ProductSelectOptions .= "<option value='0'>&nbsp;" . $LastOptionTag . "\n";
			}
		}
	
	
	// ############################################################################
	//   Add Products Steps
	// ############################################################################
	

		print "<tr><td><table border='0'>\n";
		
		// Set Defaults
		
		// Step 1: Choose Product
			print "<tr class=\"dataTableRow\"><form name=prod action='$PHP_SELF?oID=$oID&action=$action&mode=$mode&id=$id' method='POST'>\n";
			print "<td class='dataTableContent' align='right'><b>STEP 1:</b></td><td class='dataTableContent' valign='top'>";
			$products_array = array();
			$products_array = tep_get_products_array_single();
			if(sizeof($products_array)<=0) echo 'Products Are Not Available';
			else echo tep_draw_products_select_menu('add_product_products_id',$products_array,$add_product_products_id,' id="add_product_products_id"');
			print "<td class='dataTableContent' align='center'>" .  tep_image_submit('button_select.gif', 'search');
			print "<input type='hidden' name='add_product_categories_id' value='$add_product_categories_id'>";
			print "<input type='hidden' name='add_step' value='3'>";
			print "</td></tr>\n";
            print "<tr><td colspan='3'>&nbsp;</td></tr>\n";
			// changes from(N)
			$pro_query=tep_db_query("select products_price,products_tax_class_id from " . TABLE_PRODUCTS . " where products_id='" . $add_product_products_id . "'");
			$product=tep_db_fetch_array($pro_query);
			$tax_rate=tep_get_tax_rate($product["products_tax_class_id"]);
			if($tax_rate!=0 && $add_product_products_id!="" && $add_product_products_id > 0){
				$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){
				  print "<tr class=\"dataTableRow\"><td align='left' class='smalltext'><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>";
				  print "<tr><td colspan='3'>&nbsp;</td></tr>\n";
				} else {
				  print "<tr class=\"dataTableRow\"><td align='left' class='smalltext'><b>Price:</b></td><td align='left' class='smalltext' colspan='2'>&nbsp;" . $currencies->format(tep_add_tax($discount_price,$tax_rate));
				  print "</td></tr>";
				  print "<tr><td colspan='3'>&nbsp;</td></tr>\n";
				  print "</form>";
				}
			}else if($add_product_products_id!="" && $add_product_products_id > 0) {
				$pro_query=tep_db_query("select products_price,products_tax_class_id from " . TABLE_PRODUCTS . " where products_id='" . $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){
				  print "<tr class=\"dataTableRow\"><td align='left' class='smalltext'><b>Price:</b></td><td align='left' class='smalltext' colspan='2'>&nbsp;" . $currencies->format(abs($res_query['products_price']));
				  print "</td></tr>";
				  print "<tr><td colspan='3'>&nbsp;</td></tr>\n";
				}else if($discount_price['id']=='GD'){
				  print "<tr class=\"dataTableRow\"><td align='left' class='smalltext'><b>Price:</b></td><td align='left' class='smalltext' colspan='2'>&nbsp;" . $currencies->format($discount_price['text']);
				  print "</td></tr>";
				  print "<tr><td colspan='3'>&nbsp;</td></tr>\n";
				}else if($discount_price['text']>0 && $discount_price['id']=='SP') {
				  print "<tr class=\"dataTableRow\"><td align='left' class='smalltext'><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 "<tr><td colspan='3'>&nbsp;</td></tr>\n";
				}
				// changes from(N)
				print "</form>";
			}	
		// Step 3: Choose Options
		if(($add_step > 2) && ($add_product_products_id > 0))
		{
			// Get Options for Products
			$result = tep_db_query("SELECT * FROM " . TABLE_PRODUCTS_ATTRIBUTES . " pa LEFT JOIN " . TABLE_PRODUCTS_OPTIONS . " po ON po.products_options_id=pa.options_id LEFT JOIN " . TABLE_PRODUCTS_OPTIONS_VALUES . " pov ON pov.products_options_values_id=pa.options_values_id,". TABLE_PRODUCTS ." p WHERE p.products_id='$add_product_products_id' and p.products_id=pa.products_id and p.is_attributes= '".Y."' order by po.products_options_sort_order");
		//	echo "SELECT * FROM " . TABLE_PRODUCTS_ATTRIBUTES . " pa LEFT JOIN " . TABLE_PRODUCTS_OPTIONS . " po ON po.products_options_id=pa.options_id LEFT JOIN " . TABLE_PRODUCTS_OPTIONS_VALUES . " pov ON pov.products_options_values_id=pa.options_values_id,". TABLE_PRODUCTS ." p WHERE p.products_id='$add_product_products_id' and p.products_id=pa.products_id and p.is_attributes= '".Y."' order by po.products_options_sort_order";
			// Skip to Step 4 if no Options
			if(tep_db_num_rows($result) == 0)
			{
				$add_step = 4;
				
			}
			else
			{
			  $total_stock_query = tep_db_query("select attributes_id from " .TABLE_PRODUCTS_STOCK . " where attribute_status='1' and products_id='$add_product_products_id' ");
			 
			 // Total product status checking
			    if(tep_db_num_rows($total_stock_query) == 0){
				print "<tr class=\"dataTableRow\">\n";
				print "<td class='dataTableContent' align='right'></td><td class='dataTableContent' valign='top' colspan='2'><i> '". TEXT_OUT_OF_STOCK ."'</i></td>";
				print "</tr>\n";	
			 } else { 
				while($row = tep_db_fetch_array($result))
				{ 
					extract($row,EXTR_PREFIX_ALL,"db");
					$Options[$db_products_options_id] = $db_products_options_name;
					$ProductOptionValues[$db_products_options_id][$db_products_options_values_id] = $db_products_options_values_name;
				}
			
			print "<td class='dataTableContent' align='right' valign=top><table width='100%' border='0'><tr class=\"dataTableRow\"><td class='dataTableContent' align='right' valign=top><b>STEP 2:</b></td></tr></table><td><table border='0'>";

			
// Modification for Ajax
				 if($aid == ""){
		            $aid = array();
			         if($add_product_options){
			           foreach($add_product_options as $key => $value)
			                $aid[$key]= $value; 
				        }
			        }			
		    if (is_array($aid)){
		      while (list($key, $value) = each ($aid)) {
  				 $attrb.= $key."{".$value."}-";
			   } 
			  $rest = substr($attrb, 0, -1); 
			}
			//echo $rest;
			$instock_quantity = "";
			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);
			
			}
			else
			{ 
				$out_of_stock=tep_check_stock($add_product_products_id, 0);
				if($out_of_stock=="")
					$instock_quantity=tep_get_products_stock($add_product_products_id);
			}

				
				$attributes_array = array();
				if($ProductOptionValues){
				foreach($ProductOptionValues as $OptionID => $OptionValues)
						$attributes_array[] = array('id'=>$OptionID); 	
				  }
				if($add_product_options)
				$add_product_option = array_values($add_product_options);
				$cnt = count($ProductOptionValues);
				$iname = 0;
				$iload='0';
				print "<tr class=\"dataTableRow\"><form name='quanform' action='$PHP_SELF?oID=$oID&action=insert_product&mode=$mode&id=$id' method='POST' >\n";
				if($ProductOptionValues){ 
				foreach($ProductOptionValues as $OptionID => $OptionValues)
				{ 
				    if($ProductOptionValues){
				//	if($iload==0)
					$OptionOption = "<tr ><td class='dataTableContent' valign='top'><b>" . $Options[$OptionID] . "</b></td><td><select class='inputNormal' onBlur='javascript:toggle_focus(this,1);' onFocus='javascript:toggle_focus(this,2);' id='add_products_options[$OptionID]' name='add_product_options[$OptionID]' onchange='javascript:load_stock(this,$add_product_products_id,$iname);' style='width:120px'>";
					//else
					//$OptionOption = "<tr ><td class='dataTableContent' valign='top'><b>" . $Options[$OptionID] . "</b></td><td><select class='inputNormal'  disabled='disabled'  onBlur='javascript:toggle_focus(this,1);' onFocus='javascript:toggle_focus(this,2);' id='add_products_options[$OptionID]' name='add_product_options[$OptionID]' onchange='javascript:load_stock(this,$add_product_products_id,$iname);' style='width:120px'>";
					}
					$iload++;
					$OptionOption.="<option value='0'>".TEXT_SELECT;
					$iname++ ;
					if($cnt == count($ProductOptionValues)){ 
					foreach($OptionValues as $OptionValueID => $OptionValueName)
					{
					$add = false;
					$stock_check_query = tep_db_query("select attributes_id from ". TABLE_PRODUCTS_STOCK . " where attribute_status='1' and products_id=$add_product_products_id");
					while($stock_check = tep_db_fetch_array($stock_check_query)){
					      $temp = split('-',$stock_check['attributes_id']);
					      $n = count($temp);
						  for($icnt=0; $icnt<$n ; $icnt++){
						  	  $split = split('{',$temp[$icnt]);
						      if($split[0]==$OptionID){
							     $id_pos = strpos($split[1],'}');
								 $opt_val_id = substr($split[1],0,$id_pos);
								  if($opt_val_id ==$OptionValueID )
								  $add = true;
							  }    
						  }   
					}if($add) 
					$OptionOption .= "<option value='$OptionValueID'> $OptionValueName\n";
					}
					$cnt = $cnt - 1;
					}
					if( $cnt < count($ProductOptionValues) && IsSet($add_product_options) ){
					foreach($OptionValues as $OptionValueID => $OptionValueName)
					{
					for($j=1;$j<= count($add_product_options);$j++){	
						if($add_product_option[$j]== $OptionValueID){
							$OptionOption .= "<option value='$OptionValueID'> $OptionValueName\n";}
					}}
					}
					$OptionOption .= "</select></td></tr>\n";
					
					if(IsSet($add_product_options))
					$OptionOption = str_replace("value='" . $add_product_options[$OptionID] . "'","value='" . $add_product_options[$OptionID] . "' selected",$OptionOption);
					
					print $OptionOption;
					}
				}
				
				print "<tr>";
				print "<td class='dataTableContent' align=''><b>Quantity</b></td>";
				print "<td class='' valign='top'>";
			//if($out_of_stock==""){
				print tep_draw_input_field('add_product_quantity',$add_product_quantity,' size="2"');
				print "</table></td>";
				print "<td colspan='4'  align='center' valign='bottom'>";
				print tep_image_button('button_add.gif',IMAGE_ADD,'style="cursor:pointer;cursor:hand" onClick="javascript:validateForm1(' . $instock_quantity . ');" name="button_add"');
			//}		
				if(IsSet($add_product_options))
			{
				foreach($add_product_options as $option_id => $option_value_id)
				{
					print "<input type='hidden' name='add_product_options[$option_id]' value='$option_value_id'>";
				}
			}
			print "<input type='hidden' name='add_product_categories_id' value='$add_product_categories_id'>";
			print "<input type='hidden' name='add_product_products_id' value='$add_product_products_id'>";
			print "<input type='hidden' name='add_step' value='5'>";
			print "<input type='hidden' name='attributes_id' value='$rest'>";
			print "</td>\n";
			print "</form></tr>\n";
			  }
			}

			print "<tr><td colspan='3'>&nbsp;</td></tr>\n";
		}

		// Step 4: Confirm
		if($add_step > 3 && count($add_product_options)==0)
		{	
		   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,1);
				if($out_of_stock=="")
					$instock_quantity=tep_get_attributes_stock($add_product_products_id, $rest);

			}
			else
			{
				$out_of_stock=tep_check_stock($add_product_products_id, 1);
				if($out_of_stock=="")
					$instock_quantity=tep_get_products_stock($add_product_products_id);
			}
			print "<tr class=\"dataTableRow\"><form name='quanform1' action='$PHP_SELF?oID=$oID&action=insert_product&mode=$mode&id=$id' method='POST'>\n";
			print "<td class='dataTableContent' align='right'><b>STEP 2:</b></td>";
			print "<td class='dataTableContent' valign='top'>";
			if($out_of_stock==""){
				print tep_draw_input_field('add_product_quantity',$add_product_quantity,' size="2"') . " Quantity</td>";
				print "<td class='dataTableContent' align='center'>";
				print  tep_image_button('button_add.gif',IMAGE_ADD,'style="cursor:pointer;cursor:hand" onClick="javascript:validateForm1_niloption(' . $instock_quantity . ');" name="button_add"');
			}
			else
				print $out_of_stock . ' ' . TEXT_OUT_OF_STOCK;
			
			?>
			
			<?php
			print "<input type='hidden' name='add_product_categories_id' value='$add_product_categories_id'>";
			print "<input type='hidden' name='add_product_products_id' value='$add_product_products_id'>";
			print "<input type='hidden' name='add_step' value='5'>";
			print "<input type='hidden' name='attributes_id' value='$rest'>";
			print "</td>\n";
			print "</form></tr>\n";
			}
		print "</table></td></tr>\n";
		}
	?>
    </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_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);
  }?>
 <script language="javascript">
 var attrib=new Array();
var attribs = new Array();
<?php 
	for($i=0;$i<sizeof($attributes_array);$i++){ ?>
	attrib[<?php echo $i;?>]="<?php echo $attributes_array[$i]['id'];?>";
<?php 	}
if($add_product_options) ?>
var add_products_options_count = " <?PHP echo count($add_product_options);  ?>";
function  validateForm1(prd_quantity){
	 var value_array = new Array();
	 var chk = 1;
     var add_product_products_id = document.quanform.add_product_products_id.value;
     var obj = document.quanform;
   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;
			}
		}		
	}
   if (document.quanform.add_product_quantity.value=='' || parseInt(document.quanform.add_product_quantity.value)=='0'	 || isNaN(document.quanform.add_product_quantity.value) || parseInt(document.quanform.add_product_quantity.value) < '0'){
	alert('<?php echo ERR_TEXT_QUANTITY?>');
	return false;
	}
	if ((document.quanform.add_product_quantity.value).indexOf('.') != -1){
	alert('<?php echo ERR_TEXT_QUANTITY1; ?>');
	return false;
	}
	
   if(attrib != "" && add_products_options_count == 0){
   		for(icnt=0;icnt<attrib.length;icnt++){
		  value_array[icnt] =  document.quanform.elements["add_products_options["+ attrib[icnt] +"]"].options[document.quanform.elements["add_products_options["+ attrib[icnt] +"]"].selectedIndex].value;
		}   
     command ="<?php echo tep_href_link(FILENAME_ADDPRODUCTS);?>?command=fetch_attrib_qty&attrib="+attrib+"&value_array="+value_array+"&add_prd_id="+add_product_products_id;
	 do_get_command(command);
   }
  
   if (document.quanform.add_product_quantity.value > prd_quantity && add_products_options_count > 0 ) {
	 alert ('Error : Product Quantity Out of Stock');
	 return false;
	 }
	 if(add_products_options_count > 0){
	   document.quanform.submit();
	 }
}
function validateForm2(prd_quantity){
   var chk = 1;
   if ((document.quanform.add_product_quantity.value).indexOf('.') != -1){
	chk = 2;
	alert('<?php echo ERR_TEXT_QUANTITY1; ?>');
	return false;
	}
   if (document.quanform.add_product_quantity.value > parseInt(prd_quantity) ) {
     chk = 2;
	 alert ('Error : Product Quantity Out of Stock');
	 return false;
	 }
	 if(chk == 1){
	  document.quanform.submit();
	 }
} 

 function load_stock(att_name,prd_id,cnt){
		att_id =att_name.value;
		combo_name = att_name.name;
		var pre_ids ="";
		var attrib_length = attrib.length;
	
			  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_ADDPRODUCTS);?>?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 do_result(result){
	//alert(result);
	if(result.length < 5)  validateForm2(result);
	else{
		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]+"]"));
		
			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]+"]"));
			}
		}
	  }	
	}
	function add_options(textArr,valueArr,optionElement){
		// clear the previous details
		while(optionElement.options.length>1){
			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
			  }
		}
	}
 
 </script> 

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