<?php
/*
	osCommerce, Open Source E-Commerce Solutions 
	http://www.oscommerce.com 
	
	Copyright (c) 2003 osCommerce 
	
	osCommRes, Services Oline 
	http://www.oscommres.com 
	Copyright (c) 2005 osCommRes 
	
	Freeway eCommerce 
	http://www.zac-ware.com/freeway 
	Copyright (c) 2007 ZacWare
	
	Released under the GNU General Public License
*/


// Set flag that this is a parent file
	define( '_FEXEC', 1 );
	
if (!function_exists('tep_db_connect')) require('includes/application_top.php');
   //if($HTTP_GET_VARS['cPath'] && $HTTP_GET_VARS['cPath']>0 && !check_restrick()) tep_redirect(tep_href_link(FILENAME_DEFAULT));
	
	$products_id=isset($HTTP_GET_VARS["products_id"])?(int)$HTTP_GET_VARS["products_id"]:0;
	$cPath=isset($HTTP_GET_VARS["cPath"])?(int)$HTTP_GET_VARS["cPath"]:'';
	$command=isset($HTTP_GET_VARS["command"])?tep_db_prepare_input($HTTP_GET_VARS["command"]):'';
	if ($command!=""){
		if ($command=="fetch_attrib_val"){
			$select_attrib=isset($HTTP_GET_VARS["select_attrib"])?(int)$HTTP_GET_VARS["select_attrib"]:0;
			$select_index=isset($HTTP_GET_VARS["select_index"])?(int)$HTTP_GET_VARS["select_index"]:0;
			$prev_ids=isset($HTTP_GET_VARS["prev_ids"])?tep_db_prepare_input($HTTP_GET_VARS["prev_ids"]):'';
			echo "fetch_attrib_val@@"+tep_output_string($select_index)+"@@"+tep_get_attributes($select_attrib,$prev_ids,true);
			
		} else if ($command=="check_attrib_stock"){
			$attrib_ids=isset($HTTP_GET_VARS["attrib_ids"])?tep_db_prepare_input($HTTP_GET_VARS["attrib_ids"]):'';
			$quan=isset($HTTP_GET_VARS["quan"])?(int)$HTTP_GET_VARS["quan"]:1;
			echo "check_attrib_stock@@";
			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 products_id=" . tep_db_input($products_id) . " and attributes_id='" . tep_db_input($attrib_ids) . "' and attribute_status='1' and products_quantity>=" . tep_db_input($quan));
				if (tep_db_num_rows($stock_query)>0) echo "1";
				else echo "0";
			}
		} else if ($command=="store_reminder"){
			$attrib_ids=isset($HTTP_GET_VARS["attrib_ids"])?tep_db_prepare_input($HTTP_GET_VARS["attrib_ids"]):'';
			$email=isset($HTTP_GET_VARS["email"])?tep_db_prepare_input($HTTP_GET_VARS["email"]):'';
			$quan=isset($HTTP_GET_VARS["quan"])?(int)$HTTP_GET_VARS["quan"]:1;
			echo "store_reminder@@";
			if ($attrib_ids!=''){
				$temp_array=split("-",$attrib_ids);
				usort($temp_array,"ucmp");
				$attrib_ids=join("-",$temp_array);
				$update_query=tep_db_query("INSERT into " . TABLE_PRODUCTS_REMINDERS . "(products_id,attributes_id,date_added,email_address,quantity) VALUES('" . tep_db_input($products_id) . "','" . tep_db_input($attrib_ids) . "',now(),'" . tep_db_input($email) . "'," . tep_db_input($quan) . ")");
			}
		}
		exit;
	}

   $check_restrict_customer="";
   $customer_group_id=0;
   $check_restrict_customer=" and ((p.restrict_to_customers='' OR ISNULL(p.restrict_to_customers)) AND (p.restrict_to_groups='' OR ISNULL(p.restrict_to_groups)))";
   if (tep_session_is_registered('customer_id')){
   		$customer_group_id=get_customer_group_id();
   		$check_restrict_customer=substr($check_restrict_customer,0,-1)." OR (p.restrict_to_customers like '%".tep_db_input($customer_id)."%' OR p.restrict_to_groups like '%".tep_db_input($customer_group_id)."%'))";
   }
	// load the details into merge fields
	$template_details=array();
	
	$tpl["SECTION_NO_PRODUCT"]=0;
	$tpl["SECTION_PRODUCT"]=0;
	
	require(DIR_WS_LANGUAGES . $language . '/' . FILENAME_PRODUCT_INFO);

    $product_info_query = tep_db_query("select p.products_id,p.products_price_break,pd.products_name, pd.products_description, p.author_name,p.products_model, p.products_quantity, p.products_image_1,p.products_image_2,p.products_image_3,p.products_image_4,p.products_image_5,
							p.products_title_1,p.products_title_2,p.products_title_3,p.products_title_4,p.products_title_5,pd.products_url, p.products_price, p.products_tax_class_id, p.products_date_added, p.products_date_available, p.products_quantity,p.products_price_break,p.manufacturers_id,p.is_attributes from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd where p.products_status = '1' and p.products_id = '" . tep_db_input($products_id) . "' and pd.products_id = p.products_id and pd.language_id = '" . (int)$languages_id . "'" . $check_restrict_customer);
						
/*	
	echo "select p.products_id,p.products_price_break,pd.products_name, pd.products_description, p.author_name,p.products_model, 
	      p.products_quantity, p.products_image_1,p.products_image_2,p.products_image_3,p.products_image_4,p.products_image_5,
		  p.products_title_1,p.products_title_2,p.products_title_3,p.products_title_4,p.products_title_5,pd.products_url, 
		  p.products_price, p.products_tax_class_id, p.products_date_added, p.products_date_available, 
		  p.products_quantity,p.products_price_break,p.manufacturers_id,p.is_attributes from 
		  " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd where p.products_status = '1' and 
		  p.products_id = '" . $products_id . "' and pd.products_id = p.products_id and 
		  pd.language_id = '" . (int)$languages_id . "'" . $check_restrict_customer;
							
	
*/	$GLOBALS["TPL_CONTENT"]=@file_get_contents(DIR_WS_TEMPLATES . TEMPLATE_NAME . "/content/" .CONTENT_PRODUCT_INFO . ".tpl.php");
	

	if (tep_db_num_rows($product_info_query)>0 && $GLOBALS["TPL_CONTENT"]!=""){
	
		
		$tpl["SECTION_NO_PRODUCT"]=0;
		$tpl["SECTION_PRODUCT"]=1;
		$product_info=tep_db_fetch_array($product_info_query);

		$JS_DETAILS=array("PRODUCT_ID"=>tep_db_prepare_input($products_id),'PRODUCT_STOCK'=>$product_info["products_quantity"],
					'PRODUCT_PRICE_BREAKS'=>"{enabled:false}",
					'PRODUCT_PRICE_ATTR'=>"{enabled:false,count:0}",
					'CURRENCY_DETAIL'=>"{symbolLeft:'" .$currencies->currencies[$currency]['symbol_left'] . "',symbolRight:'" . $currencies->currencies[$currency]['symbol_right'] . "'}",
					'PRICE_CALC_FUNCTIONS'=>"['getProductsPrice()','getAttributePrice(-1)']",
					'AJX_URL'=>"'" . tep_href_link(FILENAME_PRODUCT_INFO,'t=1','NONSSL',true,false) ."'",
					'ERROR_MSGS'=>"{'email':'" . TEXT_ERR_EMAIL_ADDRESS . "','attrEmpty':'" . TEXT_ERROR_ATTRIBUTE_EMPTY . "','qty':'" . ERROR_QUANTITY . "','forced':'" . ERROR_XSELL_FORCED . "','forcedattrEmpty':'" . ATTIBUTE_SELECT. "'}",
					'SALEMAKER_DATAS'=>'{enabled:false}',
					'FORCED_ITEMS'=>'{enabled:false}'
					);

		$JS_START="";	
	
			
		tep_db_query("update " . TABLE_PRODUCTS_DESCRIPTION . " set products_viewed = products_viewed+1 where products_id = '" . tep_db_input($products_id) . "' and language_id = '" . (int)$languages_id . "'");
	
		$tax_rate=tep_get_tax_rate($product_info["products_tax_class_id"]);

		if ($new_price = tep_get_products_special_price($product_info['products_id'])) {
		  $products_dprice = '<s>' . $currencies->display_price($product_info['products_price'], $tax_rate,'1',true) . '</s> <span class="productSpecialPrice">' . $currencies->format(tep_add_tax($new_price, tep_get_tax_rate($product_info['products_tax_class_id']))) . '</span>';
		  $products_tot_price=$currencies->format(tep_add_tax($new_price, tep_get_tax_rate($product_info['products_tax_class_id'])));
		  $products_price=tep_add_tax($new_price, $tax_rate);
		  $products_original_price=$new_price;
		} else {
		  $products_tot_price=$products_dprice = $currencies->display_price($product_info['products_price'], $tax_rate,'1',true);
		  $products_price=tep_add_tax(tep_get_plain_products_price($product_info['products_price']), $tax_rate);
		  $products_original_price=$product_info['products_price'];
		}
		$special_price=$new_price;
		if (tep_not_null($product_info['products_model'])) {
		  $products_name = $product_info['products_name'] . '<span class="smallText" align="right">[' . $product_info['products_model'] . ']</span>';
		} else {
		  $products_name = $product_info['products_name'];
		}
	
	
		$temp_query = tep_db_query("select categories_name,cd.categories_id from " . TABLE_CATEGORIES_DESCRIPTION . " cd , " . TABLE_PRODUCTS_TO_CATEGORIES . " ptc where cd.categories_id=ptc.categories_id and ptc.products_id='".tep_db_input($products_id)."'");
		$temp = tep_db_fetch_array($temp_query);
		$tpl["VALUE_CATEGORIES_NAME"]=$temp["categories_name"];
		$category_id=$temp["categories_id"];
		// prepare for the images
		$images=array(defined('HEADER_COLS_MULTIPLE_IMAGE')?constant('HEADER_COLS_MULTIPLE_IMAGE'):3);
		$img_string="";
		$title_string="";
		for ($icnt=1;$icnt<=5;$icnt++){
			$show_image=trim($product_info['products_image_' . $icnt]);
			if ($show_image!="" && (file_exists(DIR_FS_CATALOG . DIR_WS_IMAGES . "big/" . $show_image) ||  file_exists(DIR_WS_IMAGES . $show_image) ) ){
				$title_string.="'" . addslashes($product_info["products_title_" . $icnt]) . "',";
					$images[]=array('IMAGE'=>tep_product_small_image($show_image,$product_info["products_title_" . $icnt],'onClick="javascript:set_image(' . ($icnt-1) .');" style="cursor:pointer;cursor:hand;"'),'TITLE'=>$product_info["products_title_" . $icnt]);
				if ($img_string=="") {
				  $first_image=$show_image;
				}
				if (file_exists(DIR_FS_CATALOG . DIR_WS_IMAGES . "big/" . $show_image)){
					$img_string.="'" . DIR_WS_IMAGES . "big/" . $product_info["products_image_" . $icnt] . "',";
				} else {
					$img_string.="'" . DIR_WS_IMAGES . $product_info["products_image_" . $icnt] . "',";
				}
			}
		}
		
		
		$tpl["SECTION_IMAGE"]=0;
		$tpl["SECTION_MULTIPLE_IMAGE"]=0;
		
		if (count($images)>1){
			$tpl["SECTION_IMAGE"]=1;
			if (file_exists(DIR_FS_CATALOG . DIR_WS_IMAGES . "big/" .$first_image)){
				$temp='<image src="' . DIR_WS_IMAGES . "big/" . $first_image . '" id="imgContainer">';
			} else {
				$temp='<image src="' . DIR_WS_IMAGES . $first_image . '" id="imgContainer">';
			}
			$tpl["VALUE_FIRST_IMAGE"]=$temp;
			$tpl["VALUE_FIRST_IMAGE_TITLE"]=tep_output_string($product_info['products_title_1']);
			if (count($images)>2){
				$tpl["SECTION_MULTIPLE_IMAGE"]=1;
				$tpl["REPEAT_MULTIPLE_IMAGE"]=$images;
				$img_string=substr($img_string,0,-1);
				$title_string=substr($title_string,0,-1);
	
				if ($img_string!="") $JS_START.='load_images(' . $img_string  .");\n";
				if ($title_string!="") $JS_START.='load_titles(' . $title_string  .");\n";
			} 
		}

		do_replace();
		$tpl["SECTION_PRODUCTS_PRICE_BREAK"]=0;
		$tpl["SECTION_PRODUCTS_PRICE"]=0;
		
		//set price & quantity details
		if ($product_info["products_price_break"]=="Y"){
			$tpl["SECTION_PRODUCTS_PRICE_BREAK"]=1;
			$tpl["REPEAT_PRODUCTS_PRICE_BREAK"]=tep_get_products_breaks($product_info,$tax_rate);
			$tpl["VALUE_PRICE_BREAK_QUAN"]=TEXT_QUANTITY;
			$tpl["VALUE_PRICE_BREAK_PRICE"]=TEXT_PRICE;
			$tpl["VALUE_INPUT_QUAN"]="<input type='hidden' name='qty' value='1' id='qty'>";
			if (!$tpl["REPEAT_PRODUCTS_PRICE_BREAK"]) {
				$product_info["products_price_break"]='N';
				$tpl=array("SECTION_PRODUCTS_PRICE_BREAK"=>0);
			} else {
				$products_price=tep_add_tax($product_info['products_price'], $tax_rate);
				$products_dprice=$currencies->format($products_price);
			} 
		} 
		if ($product_info["products_price_break"]!="Y"){
			$tpl["SECTION_PRODUCTS_PRICE"]=1;
			$tpl["VALUE_PRODUCTS_PRICE"]='<b>' . TEXT_PRICE . ':&nbsp;' . $products_dprice . '</b>';
			$tpl["VALUE_PRODUCTS_QUANTITY"]='<b>' . TEXT_QUANTITY . '</b>:&nbsp;' . tep_draw_input_field('qty',1,'id="qty" size="6" onBlur="javascript:checkStock(\'\');" onKeyDown="javascript:return numericOnly(event);"');

			$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($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 <= " . tep_db_input($product_info['products_price']) . " or sale_pricerange_from = '0') and (sale_pricerange_to >= " . tep_db_input($product_info['products_price']) . " or sale_pricerange_to = '0') order by sale_deduction_value");
			if (tep_db_num_rows($sale_query)>0){
				$tpl["SECTION_PRODUCTS_SALEMAKER"]=1;
				$tpl["VALUE_SELECT_SALEMAKER_DISCOUNT"]=TEXT_SELECT_SALEMAKER_DISCOUNT;
				$sales=array();
				$JS_DETAILS['SALEMAKER_DATAS']='{enabled:true,sales:{';
				
				$sales[]=array("OPTION"=>tep_draw_radio_field('salemaker_id',0,true,'id="salemaker_id" onClick="javascript:selectDiscount(0);"'),"OPTION_TEXT"=>TEXT_NO_DISCOUNT);
				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;
						
					}
					$JS_DETAILS['SALEMAKER_DATAS'].=tep_add_tax(tep_get_salemaker_price($special_price,$product_info["products_price"],$sale),$tax_rate) . ",warning:'" .htmlspecialchars($sale["choice_warning"]) . "'},";
					$sales[]=array("OPTION"=>tep_draw_radio_field('salemaker_id',$sale["sale_id"],false,' onClick="javascript:selectDiscount(' . $sale["sale_id"] . ');"'),"OPTION_TEXT"=>$choice_text);
				}
				$JS_DETAILS['SALEMAKER_DATAS']=substr($JS_DETAILS['SALEMAKER_DATAS'],0,-1) . "}}";
				$tpl["REPEAT_PRODUCTS_SALEMAKER"]=$sales;
			} else {
				$tpl["SECTION_PRODUCTS_SALEMAKER"]=0;
			}
			$JS_START.="checkStock('');\nsetInterval('quanAutoCheck()',1000);\n";
		}
		
		$tpl["VALUE_PRODUCTS_DESCRIPTION"]=$product_info['products_description'];
		do_replace();

		ob_start();
		include(DIR_WS_MODULES . FILENAME_XSELL_PRODUCTS_BUYNOW);
		echo tep_draw_separator('pixel_trans.gif', '100%', '10');
	
		//include(DIR_WS_MODULES . FILENAME_ALSO_PURCHASED_PRODUCTS);
	
		$tpl["VALUE_EXTRA_MODULES"]=ob_get_contents();
		do_replace();
		ob_end_clean();

		// prepare for heading
		if (SHOW_HEADING_TITLE_ORIGINAL=='yes') {
			$tpl["SECTION_ORIGINAL_HEAD"]=1;
			$tpl["VALUE_HEAD_NAME"]=$products_name;
			$tpl["VALUE_HEAD_PRICE"]=$products_dprice;
			$tpl["VALUE_TABLE_HEAD_FIRST"]="";
			$tpl["VALUE_TABLE_HEAD_LAST"]="";
		} else {
			$temp=$temp1="";
			if (MAIN_TABLE_BORDER == 'yes'){
				$temp=table_image_border_top(false, false, $products_name . "\tleft\t" . $products_dprice . "\tright","\t",true,true);
				$temp1=table_image_border_bottom(true);
			}
			$tpl["SECTION_ORIGINAL_HEAD"]=0;
			$tpl["VALUE_TABLE_HEAD_FIRST"]=$temp;
			$tpl["VALUE_TABLE_HEAD_LAST"]=$temp1;
		}
		do_replace();

		//Support Packs
		$tpl["SECTION_SUPPORT_PACKS"]=0;
		$pack_query=tep_db_query("select sud.subscription_name,su.support_minutes,psp.no_users from  " . TABLE_PRODUCTS . " p, " .TABLE_SUBSCRIPTIONS_DESCRIPTION  . " sud, " . TABLE_SUBSCRIPTIONS ." su, " . TABLE_PRODUCTS_TO_SUPPORT_PACKS . " psp where sud.subscription_id=su.subscription_id and sud.subscription_id=psp.subscription_id and psp.product_id=p.products_id and sud.language_id='" . tep_db_input($languages_id) . "' and p.products_id='" . tep_db_input($products_id) . "'");
		if(tep_db_num_rows($pack_query)>0) { 
			$tpl["SECTION_SUPPORT_PACKS"]=1;
			$tpl["VALUE_SUPPORT_PACKS"]='Support Packs: ';
			$temp=array();
			while($pack_result=tep_db_fetch_array($pack_query)){
				 $temp[]=array('TEXT'=>$pack_result['support_minutes'] . ' minutes ' . $pack_result['subscription_name'] . ' for ' . $pack_result['no_users'].' users');
			}
			$tpl["REPEAT_SUPPORT_PACKS"]=$temp;
		}
		do_replace();
		//Support Packs
		
		
		//get attributes
		$tpl["SECTION_PRODUCTS_ATTR"]=0;
		if ($product_info['is_attributes']=='Y'){
			$tpl["SECTION_PRODUCTS_ATTR"]=1;
			$tpl["VALUE_PRODUCTS_ATTR"]=TEXT_PRODUCT_OPTIONS;
			$tpl["REPEAT_PRODUCTS_ATTR"]=tep_get_products_attributes(0,"",false,1);
			if (count($tpl["REPEAT_PRODUCTS_ATTR"])<=0) $tpl=array("SECTION_PRODUCTS_ATTR"=>0);
		}
		do_replace();

		//reviews
		$tpl["SECTION_REVIEW"]=0;
		$tpl["SECTION_ADMIN_REVIEW"]=0;
		$tpl["SECTION_CUST_REVIEW_FIRST"]=0;
		$tpl["SECTION_CUST_REVIEW"]=0;
	
		$review=DISPLAY_REVIEW; 
		if (strlen($review)!=2) $review="YN";
		$show_admin=substr($review,0,1);
		$show_customer=substr($review,1,1);
		if ($show_admin=="Y"){
			$temp_query = tep_db_query("select rd.reviews_text from " . TABLE_REVIEWS . " r, " . TABLE_REVIEWS_DESCRIPTION . " rd where r.products_id='" . (int)$products_id . "' and r.admin_review='Y' and r.reviews_id = rd.reviews_id and rd.languages_id = '" . (int)$languages_id . "' limit 1");
			if (tep_db_num_rows($temp_query)>0){
				$temp_result=tep_db_fetch_array($temp_query);
				$tpl["SECTION_REVIEW"]=1;
				$tpl["SECTION_ADMIN_REVIEW"]=1;
				$tpl["VALUE_ADMIN_REVIEW"]=TEXT_ADMIN_REVIEW;
				$tpl["VALUE_ADMIN_REVIEW_TEXT"]=str_replace(array("<html>","</html>","<head>","</head>","<title>","</title>","<body>","</body>","\\"),"",$temp_result["reviews_text"]);
			}
		}
		if ($show_customer=="Y"){
			$temp_query = tep_db_query("select r.customers_name,rd.reviews_text,rd.reviews_id from " . TABLE_REVIEWS . " r, " . TABLE_REVIEWS_DESCRIPTION . " rd where products_id = '" . (int)$products_id . "' and r.reviews_id=rd.reviews_id and r.admin_review ='N' and rd.languages_id = '" . (int)$languages_id . "' order by r.date_added desc limit 3");
			if (tep_db_num_rows($temp_query)>0 && $show_admin=="Y"){
				$tpl["SECTION_CUST_REVIEW_FIRST"]=1;
				$tpl["SECTION_REVIEW"]=1;
				$tpl["VALUE_CUST_REVIEW_FIRST"]='<a href="' . tep_href_link(FILENAME_PRODUCT_REVIEWS,'cPath=' . tep_output_string($cPath) . '&products_id=' . $products_id) . '">' . tep_template_image_button('button_customer_reviews.gif',IMAGE_CUSTOMER_REVIEWS) . '</a>';
			} else if (tep_db_num_rows($temp_query)>0){
				$tpl["SECTION_CUST_REVIEW"]=1;
				$tpl["VALUE_REVIEWS"]=TEXT_REVIEWS;
				$tpl["SECTION_REVIEW"]=1;
				$tpl["VALUE_MORE_REVIEWS"]='<a href="' . tep_href_link(FILENAME_PRODUCT_REVIEWS, tep_get_all_get_params()) . '">' . tep_template_image_button('button_reviews.gif', IMAGE_BUTTON_REVIEWS) . '</a>';
				$temp=array();
				while($temp_result=tep_db_fetch_array($temp_query)){
					$temp[]=array("IMAGE"=>tep_template_image('arrow_white.gif'),"TEXT"=>'<a href="' . tep_href_link(FILENAME_PRODUCT_REVIEWS_INFO,'products_id=' . $products_id .'&reviews_id=' . $temp_result['reviews_id']) . '">' . substr(strip_tags($temp_result['reviews_text']),0,40) .'</a></td></tr>',
									"NAME"=>$temp_result["customers_name"]);
				}
				$tpl["REPEAT_CUST_REVIEW"]=$temp;
			}
		}
		do_replace();
		$tpl["SECTION_BUY"]=0;
		if (HIDE_ALSO_AVAILABLE=="false"){
			// fetch other products in the same category
			$temp_query = tep_db_query("select pd.products_id,p.products_status,p.products_quantity,pd.products_name,p.products_price,p.products_tax_class_id,p.products_image_1,p.products_title_1 from " . TABLE_PRODUCTS . " p," . TABLE_PRODUCTS_DESCRIPTION . " pd," . TABLE_PRODUCTS_TO_CATEGORIES . " pc where pc.categories_id=" . (int)$current_category_id . " and p.products_id!=" . tep_db_input($products_id) . " and pc.products_id=p.products_id and pd.products_id=p.products_id " .$check_restrict_customer . " and pd.language_id=" . tep_db_input($languages_id) . " order by rand() limit 0,3");
			if(tep_db_num_rows($temp_query)>0){
				$tpl["SECTION_BUY"]=1;
				$tpl["VALUE_BUY_TITLE"]=TEXT_BUY;
				$temp=array(2);
				while($temp_result = tep_db_fetch_array($temp_query)){	  		
					if($fetch_row['products_status']=='0') {
						$pimage=tep_product_email_image($temp_result["products_image_1"],'title="' . $temp_result["products_title_1"] . "'",50,50);
						$pname= $temp_result['products_name'];
					} else {
						$pimage='<a class="brown" href="' . tep_href_link(FILENAME_PRODUCT_INFO,'cPath='.tep_output_string($cPath).'&products_id='.$temp_result['products_id']) . '">' . tep_product_small_image($temp_result["products_image_1"],$temp_result["products_title_1"]) . '</a>';
						$pname='<a class="brown" href="' . tep_href_link(FILENAME_PRODUCT_INFO,'cPath='.tep_output_string($cPath).'&products_id='.$temp_result['products_id']) . '">' . $temp_result['products_name'] . '</a>';
					}
					$pprice = $currencies->display_price($temp_result['products_price'], tep_get_tax_rate($temp_result['products_tax_class_id']),'1',true);
					
					$temp[]=array('IMAGE'=>$pimage,'NAME'=>$pname,'PRICE'=>$pprice);
				}
				$tpl["REPEAT_BUY"]=$temp;
			}
		}
		do_replace();
	
		$tpl["VALUE_PRODUCTS_URL"]="";

		// check some fields from product detail
		if (tep_not_null($product_info['products_url'])){
			$tpl["VALUE_PRODUCTS_URL"]=sprintf(TEXT_MORE_INFORMATION, tep_href_link(FILENAME_REDIRECT, 'action=url&goto=' . urlencode($product_info['products_url']), 'NONSSL', true, false)) . '<br>' .tep_draw_separator('pixel_trans.gif', '100%', '10') . '<br>';
		} 
		if (HIDE_PRODUCT_ADDED_TEXT=='false'){
			if ($product_info['products_date_available'] > getServerDate()) {
				$tpl["VALUE_PRODUCTS_DATE_AVAIL"]=sprintf(TEXT_DATE_AVAILABLE, tep_date_long($product_info['products_date_available'])) . '<br>' .tep_draw_separator('pixel_trans.gif', '100%', '10') . '<br>';
			} else {
				$tpl["VALUE_PRODUCTS_DATE_AVAIL"]=sprintf(TEXT_DATE_ADDED, tep_date_long($product_info['products_date_added'])) . '<br>' .tep_draw_separator('pixel_trans.gif', '100%', '10') . '<br>';
			}
		} else {
			$tpl["VALUE_PRODUCTS_DATE_AVAIL"]="";
		}
		
		$tpl["VALUE_BUTTON_CART"]='<span id="addCart">' . tep_template_image_button('button_in_cart.gif', IMAGE_BUTTON_IN_CART,'onClick="javscript:submitData();" style="cursor:pointer;cursor:hand"') . '</span>';
		
        $tpl["VALUE_WISH_CART"]='<span id="addWish">' .((tep_session_is_registered('customer_id')) ?'<a href="' . tep_href_link(FILENAME_WISHLIST, tep_get_all_get_params(array('action')) . 'action=add_wishlist') . '">' . tep_template_image_button('button_add_wishlist.gif', IMAGE_BUTTON_ADD_WISHLIST) . '</a>' : '');
		
		$tpl["VALUE_TOTAL_PRICE"]=TEXT_TOTAL_PRICE . ' : <span id="totalProductsPrice">' . $products_tot_price . '</span>';
		
		$tpl["VALUE_REMINDER_SUCCESS"]=TEXT_REMINDER_SUCCESS;
		$tpl["VALUE_STOCK_OUT"]=TEXT_OUT_STOCK;
		$tpl["VALUE_STOCK_OUT_DETAILS"]=TEXT_OUT_STOCK_DETAILS;
		$tpl["VALUE_STOCK_REMIND_EMAIL"]='<b>' . TEXT_EMAIL .'</b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' . tep_draw_input_field('remind_email','',' id="remind_email" size="20"');
		$tpl["VALUE_REMIND_BUTTON"]=tep_template_image_button('button_remind_me.gif', IMAGE_BUTTON_REMINDME,'style="cursor:pointer;cursor:hand" onclick="javascript:storeReminder();" align="absmiddle"');


		$sub_sql = "select distinct ps.subscription_id from " . TABLE_PRODUCTS_TO_SUBSCRIPTION . " ps," . TABLE_SUBSCRIPTIONS . " s where products_id = '" . (int)$HTTP_GET_VARS['products_id'] . "' and s.subscription_id in (select subscription_id from " . TABLE_PRODUCTS_TO_SUBSCRIPTION . " where products_id = '" . tep_db_input($products_id) . "') group by s.subscription_id";
		$sub_query = tep_db_query($sub_sql);
		$check_sub = tep_db_fetch_array($sub_query);
		$rows=tep_db_num_rows($sub_query);
		if($rows > 0) {
			// this is for product linked with subscription
			$link=tep_href_link(FILENAME_SUBSCRIPTION_INFO,'subscription_id=' . $check_sub['subscription_id']);
		} else {
			$link=tep_href_link(FILENAME_PRODUCT_INFO, tep_get_all_get_params(array('action')) . 'action=add_product');
		}

	
	
		$tpl['VALUE_PRODUCT_FORM']=tep_draw_form('frmProduct', $link);
		$tpl["VALUE_ROWSEP1"]=tep_draw_separator('pixel_trans.gif', '5', '3');
		$tpl["VALUE_ROWSEP2"]=tep_draw_separator('pixel_trans.gif', '5', '10');
		$tpl["VALUE_HIDDEN_VALUES"]=tep_draw_hidden_field('products_id', $product_info['products_id']) .  tep_draw_hidden_field('products_attribute') . tep_draw_hidden_field('price',$products_price,'id="price"');
		$tpl["VALUE_LOAD_MSG_QUAN"]=$tpl["VALUE_LOAD_MSG_ATTR"]=TEXT_CHECK_STOCK;
		do_replace();
				
		$js_content=@file_get_contents(DIR_WS_JAVASCRIPT . "product_info.js.php");
		reset($JS_DETAILS);
		while(list($key,$value)=each($JS_DETAILS)){
			$js_content=str_replace("{{" . $key . "}}",$value,$js_content);
		}
		$js_content=@file_get_contents(DIR_WS_INCLUDES . "http.js") . $js_content;
		$GLOBALS["TPL_CONTENT"]=$js_content . $GLOBALS["TPL_CONTENT"];
		$js_content="";
		$tpl["VALUE_SCRIPTS"]=$js_content;
		$tpl["VALUE_START_SCRIPTS"]='<script language="javascript">' . $JS_START . '</script>';
		do_replace();
	} else {
		$tpl["SECTION_NO_PRODUCT"]=1;
		$tpl["VALUE_PRODUCT_NOT_FOUND"]=TEXT_PRODUCT_NOT_FOUND;
		do_replace();
	} 


	
  $product_check_query = tep_db_query("select count(*) as total from " . TABLE_PRODUCTS . " p, " . TABLE_PRODUCTS_DESCRIPTION . " pd where p.products_status = '1' and p.products_id = '" . (int)$HTTP_GET_VARS['products_id'] . "' and pd.products_id = p.products_id and pd.language_id = '" . (int)$languages_id . "'");
  $product_check = tep_db_fetch_array($product_check_query);

	$content = CONTENT_PRODUCT_INFO;
	$javascript = 'popup_window.js';
	

	require(DIR_WS_TEMPLATES . TEMPLATE_NAME . '/' . TEMPLATENAME_MAIN_PAGE);

	require(DIR_WS_INCLUDES . 'application_bottom.php');


	function do_replace(){
		$template_details=$GLOBALS["tpl"];
		$template_content=$GLOBALS["TPL_CONTENT"];
		$replaced_content=$template_content;
			while(list($key,$value)=each($template_details)){
				switch(substr($key,0,strpos($key,'_'))){
					case "VALUE":
						$replaced_content=str_replace("{{" . $key . "}}",$value,$replaced_content);
						break;
					case "SECTION":
						if ($value!=1){
							//$replaced_content=preg_replace("/\{\{" . $key ."_START\}\}((.|\n)*)\{\{" . $key . "_END\}\}/","",$replaced_content);
							$start_pos=strpos($replaced_content,"{{" . $key . "_START}}");
							$end_pos=strpos($replaced_content,"{{" . $key . "_END}}");
							if ($start_pos!==false && $end_pos!==false){
								$temp_content=substr($replaced_content,0,$start_pos);
								$temp_content.=substr($replaced_content,$end_pos+strlen("{{" . $key ."_END}}"));
								$replaced_content=$temp_content;
								unset($temp_content);
							}
						} else {
							$replaced_content=str_replace(array("{{" .$key . "_START}}","{{" .$key . "_END}}"),"",$replaced_content);
						}
						break;
					case "REPEAT":
						$merged_total_content="";
						$start_pos=strpos($replaced_content,"{{" . $key . "_START}}")+strlen("{{" . $key ."_START}}");
						$end_pos=strpos($replaced_content,"{{" . $key . "_END}}");
						$repeat_content=substr($replaced_content,$start_pos,$end_pos-$start_pos);
						if (is_numeric($value[0])) {
							$total_cols=$value[0];
							$icnt=1;
						} else {
							$total_cols=$icnt=0;
						}
						$col=0;
						for ($n=count($value);$icnt<$n;$icnt++){
							$merged_content=$repeat_content;
							if ($total_cols>0){
								if ($col==0) $merged_total_content.='<tr>' . "\n";
							}
							reset($value[$icnt]);
							while(list($itemkey,)=each($value[$icnt])){
								$merged_content=str_replace("{{" . $key . "_" . $itemkey . "}}",$value[$icnt][$itemkey],$merged_content);
							}
	
							$merged_total_content.="\n" . $merged_content;
							$col++;
							if ($col>=$total_cols) $col=0;
						}
						if ($col<$total_cols) {
							for ($icnt=$col;$col<=$total_cols;$col++) $merged_total_content.="<td>&nbsp;</td>\n";
						}
						//$replaced_content=preg_replace("/\{\{" . $key ."_START\}\}((.|\n)*)\{\{" . $key . "_END\}\}/",$merged_total_content,$replaced_content);
						$replaced_content=substr($replaced_content,0,$start_pos) . $merged_total_content . substr($replaced_content,$end_pos);
						$replaced_content=str_replace(array("{{" .$key . "_START}}","{{" .$key . "_END}}"),"",$replaced_content);
						break;
				}
			}
		$GLOBALS["TPL_CONTENT"]=$replaced_content;
		$GLOBALS["tpl"]=array();
	}
	
	function tep_get_products_attributes($select_option=0,$prev_ids="",$from_ajx=false){
		global $products_id,$languages_id,$currencies,$tax_rate;
		
		if ($select_option>0) $extra_option.=" and popt.products_options_id=" . $select_option;
				
		$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 ($prev_ids!="") {
			$prev_ids=split("-",$prev_ids);
			for ($icnt=0,$n=count($prev_ids);$icnt<$n;$icnt++){
				$value_extra_option.=" and attributes_id like'%" .$prev_ids[$icnt] . "%'";
			}
			$value_extra_option.=" and attributes_id like'%" .$select_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){
			if (!$from_ajx) $GLOBALS["JS_DETAILS"]["PRODUCT_PRICE_ATTR"]="{enabled:true,prices:{";
			while($result=tep_db_fetch_array($temp_query)){
				if (!$from_ajx){
					$products_options_values=array(array("id"=>0,"text"=>TEXT_SELECT_ATTRIBUTE));
					$GLOBALS["JS_DETAILS"]["PRODUCT_PRICE_ATTR"].="op" . $result['products_options_id'] . ":{";
				}
				//if ($initial==0){
					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 = '" . tep_db_input($result['products_options_id']) . "' and pa.options_values_id = pov.products_options_values_id and pov.language_id = '" . tep_db_input($languages_id) . "'" . " order by pov.products_options_values_name, pa.products_options_sort_order, pov.products_options_values_name asc");
					} 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 = '" . tep_db_input($result['products_options_id']) . "' and pa.options_values_id = pov.products_options_values_id and pov.language_id = '" . tep_db_input($languages_id) . "'" . " order by pov.products_options_values_name+0, pa.products_options_sort_order, pa.options_values_price asc");
					}
					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'];
							//if ($options_values['options_values_price'] != '0') $temp_name.=' (' . $options_values['price_prefix'] . $currencies->format(tep_add_tax($options_values['options_values_price'], $tax_rate)) .') ';
							if ($options_values['price_prefix']!='+' && $options_values['price_prefix']!='-'){
								$options_values['price_prefix']='+';
							}
							if ($from_ajx) 	$products_ajx_values.=$options_values["products_options_values_id"] . ":" . $temp_name . ":" . $options_values['price_prefix'] . tep_add_tax($options_values['options_values_price'], $tax_rate) . ",";
							else {
								$products_options_values[]=array("id"=>$options_values["products_options_values_id"],"text"=>$temp_name);
								$GLOBALS["JS_DETAILS"]["PRODUCT_PRICE_ATTR"].=$options_values["products_options_values_id"] . ":" . $options_values['price_prefix'] . tep_add_tax($options_values['options_values_price'], $tax_rate) . ",";
							}
						}
					}
				//}
				if (!$from_ajx){
					$GLOBALS["JS_DETAILS"]["PRODUCT_PRICE_ATTR"].="0:0},";
					$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[' . tep_output_string($initial) . ']" id="attrIds[' . tep_output_string($initial) . ']" value="' .tep_output_string($result['products_options_id']) . '">','PRICE'=>'<span id="attrPrice'. tep_output_string($initial) . '">&nbsp;</span>');
				}
				$initial++;
			}
			if (!$from_ajx) $GLOBALS["JS_DETAILS"]["PRODUCT_PRICE_ATTR"].="op0:0},count:" . count($products_options) . "}";
		}
		if ($from_ajx) return $products_ajx_values;
		else return $products_options;
	}
	function ucmp($a, $b) 
	{
	   if ($a == $b) {
		   return 0;
	   }
	   return (intval($a) < intval($b)) ? -1 : 1;
	}
?>
