<?php
//=================================================================
// KOOBI R7 - CMS - PORTALSOFTWARE(c) DREAM4(r) 
// HTTP://WWW.DREAM4.DE
//=================================================================
// ACHTUNG!
// DIESER PROGRAMMCODE IST URHERRECHTLICH GESCHUETZT
// DIE URHEBERRECHTE LIEGEN BEI DEN JEWEILIGEN AUTOREN.
// AENDERUNGEN IN DIESER DATEI ERFOLGEN AUF EIGENE GEFAHR!
// ES IST NICHT GESTATTET, DEN COPYRIGHTHINWEIS ZU AENDERN ODER ZU
// ENTFERNEN. NUR WENN SIE EINE COPYRIGHTHINWEIS-ENTFERNUNG BESTELLT
// HABEN, DUERFEN SIE DIESEN ENTFERNEN.
//================================================================
// BEI FRAGEN WENDEN SIE SICH BITTE AN: KONTAKT@DREAM4.DE
//=================================================================
class Shop
{
	var $_product_new_tpl = 'shop_start_products_new.tpl';
	var $_product_tpl = 'products.tpl';
	var $_product_detail_tpl = 'product.tpl';
	var $_shop_start_tpl = 'shop_start.tpl';
	var $_shop_browse_tpl = 'shop_browse.tpl';
	var $_shop_topseller_tpl = 'shop_start_topseller.tpl';
	var $_start_angebote_tpl = 'shop_start_offers.tpl';
	var $_upload_path = 'uploads/shop/icons_thumbnails/';
	var $_start_limit;
	var $_newest_colums;
	var $_topseller_limit;
	var $_topseller_colums;
	var $_small_navi_limit;    
	var $_limit;                
	var $_colums;               
	var $_offer_limit;
	var $_colums_offers;
	var $_low_amount;          
	var $deZip;
	var $chZip;
	var $atZip;
	var $frZip;
	var $itZip;
	var $_similar_limit;
	var $_similar_limit_row;
	var $_accessories_limit;
	var $_accessories_limit_row;
	var $_maxlength_prodtext;
	var $_browse_tab_limit;
	
	
	function AjQuickSearch($name)
	{
		
		$LC = @$_SESSION['Langcode'];
		define('AJAX_OUTPUT',1);

		$q = preg_replace('/[^-A-Za-zA-ÖO-öo-y0-9_. ]/', '', $name) ;
		$q = strtolower($q);
		if (!$q) return;
		
		$res = array();
		$result = $GLOBALS['db']->Query("SELECT Titel_{$LC} AS Name FROM " . PREFIX . "_shop_produkte WHERE Titel_{$LC} LIKE '%" . $q . "%' AND Aktiv='1' ");
		while($row = $result->fetchrow())
		{
			array_push($res, $row->Name);
		}
		
		foreach ($res as $key=>$value) 
		{
			if (strpos(strtolower($value), $q) !== false) echo stripslashes(koobispecialchars($value)) . "\n"; // $key;
		}
	}
	
	
	//=================================================================
	// Shop-Startseiten-Aufruf
	//=================================================================
	function shopStart($colums=2,$out=1,$shop_start=0)
	{
		
		define('NO_PAGENAV',1);
		unset($_SESSION['r_land']);
		
		$hnav_ext = '';
		$GLOBALS['tmpl']->assign('headernav', "<a href=\"index.php?p=shop&amp;start=1\">" . $GLOBALS['config_vars']['Shop'] . "</a>" . $hnav_ext);
		$GLOBALS['tmpl']->assign('pagetitle_html', $GLOBALS['config_vars']['Shop']);
		
		$GLOBALS['tmpl']->assign('products_array', $this->listProducts(3,$out,1,0,0,$this->_start_limit));
		if(get_active('shop_topseller')) $GLOBALS['tmpl']->assign('topseller_array', $this->listProducts($this->_topseller_colums,$out,1,1,$this->_topseller_limit));
		
		if(get_active('shop_angebote'))
		{
			$GLOBALS['tmpl']->assign('angebote_array', $this->listProducts(3,$out,1,0,0,$this->_offer_limit,0,1,1));
			$GLOBALS['tmpl']->assign('angebote_in_shop', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/' . $this->_start_angebote_tpl));
		}
		
		if(get_active('shop_newinshop')) $GLOBALS['tmpl']->assign('new_in_shop', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/' . $this->_product_new_tpl));
		if(get_active('shop_topseller')) $GLOBALS['tmpl']->assign('topseller_in_shop', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/' . $this->_shop_topseller_tpl));
		
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/' . $this->_shop_start_tpl));
	}

	//=================================================================
	// Bestellungen listen
	//=================================================================
	function myOrders()
	{
		if(UGROUP != 2)
		{
			if(isset($_POST['sub']) && $_POST['sub'] == 'sendrequest')
			{
				
				if(empty($_POST['subject']))
				{
					//echo "<div class='error_box_ajax'>" . $GLOBALS['config_vars']['Shop_status_rNoSubj'] . "</div>";
				} else if(empty($_POST['text']))
				{
					//echo "<div class='error_box_ajax'>" . $GLOBALS['config_vars']['Shop_status_rNoMsg'] . "</div>";
				} else {
					$msg = $GLOBALS['config_vars']['Shop_oder_request_ty'];
					$msg = str_replace('%%NAME%%', $_SESSION['benutzer_vorname'] . ' ' . $_SESSION['benutzer_nachname'], $msg);
					$tex = $_POST['text'];
					$tex = stripslashes(str_replace("%%N%%","\n", $tex));
					
					$Koobi = new Koobi;
					$shop_settings = $GLOBALS['db']->RowQuery("SELECT Email_Bestellung FROM " . PREFIX . "_shop_einstellungen");
					
					// Mail an Admin
					$Koobi->koobi_mail($shop_settings->Email_Bestellung, $tex , $_POST['subject'] . ' (' . $_SESSION['login_email'] . ')' , $_SESSION['login_email'], $_SESSION['benutzer_vorname'] . ' ' . $_SESSION['benutzer_nachname'], 'text', '', '');		
					$GLOBALS['tmpl']->assign('msg', $msg);
				}
			}
			
			
			$orders = array();
			$db_where = '';
			$nav_where = '';
			
			if(isset($_GET['show']) && !empty($_GET['show']))
			{
				switch($_GET['show'])
				{
					case 'ok':
						$db_where = " AND (Status = 'ok' OR Status = 'oksend') ";
						$nav_where = "&amp;show=ok";
					break;
					
					case 'wait':
						$db_where = " AND (Status = 'wait') ";
						$nav_where = "&amp;show=wait";
					break;
					
					case 'failed':
						$db_where = " AND (Status = 'failed') ";
						$nav_where = "&amp;show=failed";
					break;
				}
			}
			
			$num = $GLOBALS['db']->RowQuery("SELECT COUNT(Id) AS NUM FROM " . PREFIX . "_shop_bestellungen WHERE Benutzer = '" . UID . "' {$db_where} ORDER BY Datum DESC");
			$limit = 10;
			$seiten = ceil($num->NUM / $limit);
			$a = prepage() * $limit - $limit;
			
			$orders_summ = $GLOBALS['db']->RowQuery("SELECT SUM(Betrag) AS Betrag FROM " . PREFIX . "_shop_bestellungen WHERE Benutzer = '" . UID . "' AND (Status = 'oksend' OR Status = 'ok')");
			$orders_summ->Betrag = $this->getPrice($orders_summ->Betrag);
			$orders_summWait = $GLOBALS['db']->RowQuery("SELECT SUM(Betrag) AS Betrag FROM " . PREFIX . "_shop_bestellungen WHERE Benutzer = '" . UID . "' AND (Status = 'wait')");
			$orders_summWait->Betrag = $this->getPrice($orders_summWait->Betrag);
			$orders_summFailed = $GLOBALS['db']->RowQuery("SELECT SUM(Betrag) AS Betrag FROM " . PREFIX . "_shop_bestellungen WHERE Benutzer = '" . UID . "' AND (Status = 'failed')");
			$orders_summFailed->Betrag = $this->getPrice($orders_summFailed->Betrag);
			
			$orders_query = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_bestellungen WHERE Benutzer = '" . UID . "' {$db_where} ORDER BY Datum DESC LIMIT $a,$limit");
			while($orders_row = $orders_query->fetchrow())
			{
				$orders_row->Betrag = $this->getPrice($orders_row->Betrag);
				$orders_row->Bestellung = base64_decode($orders_row->Bestellung);
				$orders_row->SText = $GLOBALS['config_vars']['Shop_status_' . $orders_row->Status];
				array_push($orders, $orders_row);
			}
		
			$GLOBALS['tmpl']->assign('orders_array', $orders);
			$GLOBALS['tmpl']->assign('orders_summ', $orders_summ);
			$GLOBALS['tmpl']->assign('orders_summWait', $orders_summWait);
			$GLOBALS['tmpl']->assign('orders_summFailed', $orders_summFailed);
			if($num->NUM > $limit) $GLOBALS['tmpl']->assign('pages', pagenav($seiten, '', "<a class=\"page_navigation\" href=\"index.php?p=shop&amp;action=myorders{$nav_where}&amp;page={s}\">{t}</a>"));
			
		}
		
		$GLOBALS['tmpl']->assign('headernav', '<a href="index.php?p=shop">' . $GLOBALS['config_vars']['Shop'] . '</a>' .  $GLOBALS['config_vars']['PageSep'] . $GLOBALS['config_vars']['Shop_go_myorders']);
		$GLOBALS['tmpl']->assign('pagetitle_html', $GLOBALS['config_vars']['Shop'] . $GLOBALS['config_vars']['PageSep'] . $GLOBALS['config_vars']['Shop_go_myorders']);
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/myorders.tpl'));
	}
	
	//=================================================================
	// Neuheiten in einer Kategorie
	//=================================================================
	function showTopByCateg($method='new')
	{
		$dbw = '';
		switch($method)
		{
			case 'new':
				$oby = 'a.Id DESC';
			break;
			
			case 'topseller':
				$oby = 'a.Verkauft DESC';
			break;
			
			case 'offers':
				$dbw = "AND (Preis != '0.00' AND Preis_Liste > Preis AND Preis_Liste_Gueltig >= " . stime() . ")";
				$oby = ' rand()';
			break;
			
			default: 
				$oby = 'a.Id DESC';
			break;
		}
		
		
		$search_in_child = $this->get_child_items($_REQUEST['cid']);
		$db_cid = (isset($_REQUEST['cid']) && !empty($_REQUEST['cid'])) ? " AND (Kategorie = '" . (int)$_REQUEST['cid'] . "'" . $search_in_child . ")" : "";
		
		$products_items = array();
		$sql_products = $GLOBALS['db']->Query("SELECT 
			a.Preis,
			a.Preis_Liste_Gueltig,
			a.Preis_Liste,
			a.Bild,
			a.Id,
			a.Kategorie,
			b.Name_1 as KatDefault,
			a.Titel_" . $_SESSION['Langcode'] . " as Titel,
			b.Name_" . $_SESSION['Langcode'] . " as Kategorie_Name 
		FROM 
			" . PREFIX . "_shop_produkte as a,
			" . PREFIX . "_shop_kategorie as b  
		WHERE 
			a.Aktiv=1 {$db_cid} AND b.Id = a.Kategorie  
			{$dbw} 
		ORDER BY 
			{$oby}
		LIMIT " . $this->_browse_tab_limit);

		while($row_products = $sql_products->FetchArray())
		{
			if(!$row_products['Kategorie_Name']) $row_products['Kategorie_Name'] = $row_products['KatDefault'];
			
			// Gueltigkeit eines Preises
			if(($row_products['Preis_Liste']>$row_products['Preis']) && ($row_products['Preis_Liste']>0) && ($row_products['Preis_Liste_Gueltig'] == 0) || ($row_products['Preis_Liste']>$row_products['Preis'] && $row_products['Preis_Liste_Gueltig'] != 0 && $row_products['Preis_Liste_Gueltig'] < stime()))
			{
				$row_products['Preis'] = $row_products['Preis_Liste'];
			} 
			
			$row_products['Bild_Orig'] = $row_products['Bild'];
			$row_products['Bild_Klein'] = (is_file(BASE_DIR . '/' . $this->_upload_path . 'small/' . $row_products['Bild'])) ? $this->_upload_path . 'small/' . $row_products['Bild'] : 'system/shopthumb.php?smode=small&amp;img=' . $row_products['Bild'];
			$row_products['netto_price_orig'] = $this->getPrice($row_products['Preis']);
			$row_products['Preis'] = $this->getPrice($row_products['Preis']);
			$row_products['netto_price'] = $this->getNettoPrice($row_products['Preis'], $row_products['Kategorie'], $_SESSION['user_country']);
			$row_products['Preis'] = ($this->justNetto($_SESSION['user_country'])) ? $row_products['netto_price'] : $row_products['Preis'];
			if(NETTO_SHOP==1 || $this->userNettoshop()==1) $row_products['price_ust_ex'] = $row_products['netto_price_orig'] - $row_products['netto_price'];
			$row_products['product_ust'] = $this->getUst($row_products['Kategorie']);
			$row_products['ProdLink'] = "index.php?p=shop&amp;action=showproduct&amp;id=" . $row_products['Id'] . "&amp;cid=" . $row_products['Kategorie'] . "&amp;pname=" . $this->get_clean_name($row_products['Titel']);
			array_push($products_items, $row_products);
		}
			
		$GLOBALS['tmpl']->assign('price_onlynetto', ($this->justNetto($_SESSION['user_country']) ? 1 : 0) );
		$GLOBALS['tmpl']->assign('no_nettodisplay', ($this->noNettoDisplay($_SESSION['user_country']) ? 1 : 0) );
		return $products_items;
	}
	
	//=================================================================
	// Artikel-Uebersicht
	//=================================================================
	function browseShop($colums=2,$out=1,$shop_start=0)
	{
		$Lc = $_SESSION['Langcode'];
		
		
		if(@$_REQUEST['cid']==0)
		{
			$headernav = "<a href=\"index.php?p=shop&amp;start=1\">" . $GLOBALS['config_vars']['Shop'] . "</a>";
			$pagetitle = clean_page_title($headernav, '');
		} else {
			$headernav = getNavigationPath($_REQUEST['cid'], 'shop_kategorie', 'shop', 'cid', 'Id', "Name_{$Lc}", '', '', '', '', 'Parent_Id', $GLOBALS['config_vars']['Shop']);
			$pagetitle = clean_page_title($headernav, '');
		}
		
		
		
		$GLOBALS['tmpl']->assign('tab_items', $this->showTopByCateg('new'));
		$GLOBALS['tmpl']->assign('newin_shop', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/shop_browse_tabs.tpl'));
		$GLOBALS['tmpl']->assign('tab_items', $this->showTopByCateg('topseller'));
		$GLOBALS['tmpl']->assign('topseller_shop', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/shop_browse_tabs.tpl'));
		$GLOBALS['tmpl']->assign('tab_items', $this->showTopByCateg('offers'));
		$GLOBALS['tmpl']->assign('offers_shop', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/shop_browse_tabs.tpl'));
		
		$GLOBALS['tmpl']->assign('headernav',$headernav);
		$GLOBALS['tmpl']->assign('pagetitle_html', $pagetitle);
		$GLOBALS['tmpl']->assign('products', $this->listProducts($this->_colums,$out,0,0));
		$GLOBALS['tmpl']->assign('shop_products', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/' . $GLOBALS['shopsettings']->Template_Produkte . '.tpl'));
		
		
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/' . $this->_shop_browse_tpl));
	}
	
	function getSubCategs($cid)
	{
		$Lc = $_SESSION['Langcode'];
		$sql = $GLOBALS['db']->Query("SELECT *, Name_1 as DefName, Name_{$Lc} as Name, Id as catid FROM " . PREFIX . "_shop_kategorie WHERE Parent_Id = '$cid'");
		$subcategs = array();
		while($row = $sql->fetchrow())
		{
			if(!$row->Name) $row->Name = $row->DefName;
			$row->NumCount = $this->getArticleCount($row->catid);
			$row->ParentC = $this->get_parent_shopcateg($row->catid);
			$row->NavOp = ($this->get_parent_shopcateg($row->ParentC)==0) ? $cid : $this->get_parent_shopcateg($row->ParentC);
			$row->BildKategorie = ($row->Bild_Kategorie != NULL && is_file(BASE_DIR . '/uploads/shop/icons_categs/' . $row->Bild_Kategorie)) ? $row->Bild_Kategorie : '';
			array_push($subcategs, $row);
		}
		return $subcategs;
	}
	
	function getPrice($price)
	{
		$row_r = $GLOBALS['db']->RowQuery("SELECT Rabatt FROM " . PREFIX . "_benutzer_gruppen WHERE Id = '" . $_SESSION['user_group'] . "'");
		$price = $this->getRabatt($price,$row_r->Rabatt);
		
		if(isset($_SESSION['Multiplikator']) && !empty($_SESSION['Multiplikator']))
		{
			$out = $price * $_SESSION['Multiplikator'];
		} else {
			$out = $price;
		}
		
		#$out = $this->getCouponPrice($out);
		return $out;
	}
	
	function checkDiscount()
	{	
		$row_r = $GLOBALS['db']->RowQuery("SELECT Rabatt FROM " . PREFIX . "_benutzer_gruppen WHERE Id = '" . $_SESSION['user_group'] . "'");
		if($row_r->Rabatt >= '0.01')
		{
			$GLOBALS['tmpl']->assign('Discount', 1);
			$GLOBALS['tmpl']->assign('Discount_Val', $row_r->Rabatt);
		}
	}
	
	//=================================================================
	// Funktion zum hochladen von Bildern aus dem Produkt heraus
	//=================================================================
	function upload_multi()
	{
		$images = '';
		$db_images = '';
		$allowed = array('image/pjpeg','image/jpeg','image/x-png','image/png');
		if(isset($_FILES['files']))
		{
			for($i=0;$i<count($_FILES['files']['tmp_name']);$i++)
			{
				if(!empty($_FILES['files']['tmp_name'][$i]))
				{
					switch($_FILES['files']['type'][$i])
					{
						case 'image/pjpeg' :
						case 'image/jpeg' :
						case '' :
							$new_name = md5(time() . mt_rand(10001, 19999) . $_FILES['files']['tmp_name'][$i]) . '.jpg';
						break;
						
						case 'image/x-png' :
						case 'image/png' :
							$new_name = md5(time() . mt_rand(10001, 19999) . $_FILES['files']['tmp_name'][$i]) . '.png';
						break;
						
						case 'image/gif' :
							$new_name = md5(time() . mt_rand(10001, 19999) . $_FILES['files']['tmp_name'][$i]) . '.gif';
						break;
					}
					
					@move_uploaded_file($_FILES['files']['tmp_name'][$i], BASE_DIR . '/uploads/shop/icons/' . $new_name);
					@chmod(BASE_DIR . '/uploads/shop/icons/' . $new_name,0777);
					$images[] = $new_name;
				}
			}
			if(!empty($images)) $db_images = @implode("|", $images);
			
			// Alte Bilder entfernen?
			if(isset($_REQUEST['del_old']) && $_REQUEST['del_old'] == 1)
			{
				$row_o = $GLOBALS['db']->RowQuery("SELECT Bilder FROM " . PREFIX . "_shop_produkte WHERE Id = '" . $_REQUEST['id'] . "'");
				$old = explode('|', $row_o->Bilder);
				foreach($old as $del)
				{
					@unlink(BASE_DIR . '/uploads/shop/icons/' . $del);
					@unlink(BASE_DIR . '/uploads/shop/icons_thumbnails/xsmall/' . $del);
					@unlink(BASE_DIR . '/uploads/shop/icons_thumbnails/small/' . $del);
					@unlink(BASE_DIR . '/uploads/shop/icons_thumbnails/medium/' . $del);
					@unlink(BASE_DIR . '/uploads/shop/icons_thumbnails/normal/' . $del);
					@unlink(BASE_DIR . '/uploads/shop/icons_thumbnails/big/' . $del);
				}
				$images = '';
			} else {
				$row_o = $GLOBALS['db']->RowQuery("SELECT Bilder FROM " . PREFIX . "_shop_produkte WHERE Id = '" . $_REQUEST['id'] . "'");
				if(!empty($row_o->Bilder)) 
				{
					$images = $row_o->Bilder . '|';
				} else {
					$images = '';
				}
			}
			$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_produkte SET Bilder = '{$images}{$db_images}' WHERE Id = '" . $_REQUEST['id'] . "'");
		}
	}
	
	//=================================================================
	// Alle gesehenen Artikel auflisten
	//=================================================================
	function listAllSeenProducts($showall=0)
	{
		if(isset($_REQUEST['subaction']) && !empty($_REQUEST['subaction']))
		{
			switch($_REQUEST['subaction'])
			{
				case 'sendfriend':
					if(isset($_POST['prodid']) && !empty($_POST['prodid']) && isset($_POST['prod_tell_email']) && !empty($_POST['prod_tell_email']))
					{
						$prod_tell = '';
						$prefl = ($_SERVER['SERVER_PORT']==443) ? "https://" : "http://";
						$prefix = $prefl . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
						foreach($_POST['prodid'] as $id => $key)
						{
							$arr = $GLOBALS['db']->ArrQuery("SELECT Titel_1 as TitelDef, Titel_" . $_SESSION['Langcode'] . " as Titel FROM " . PREFIX . "_shop_produkte WHERE Id = '{$id}'");
							if(!$arr['Titel']) $arr['Titel'] = $arr['TitelDef'];
							$prod_tell .= stripslashes($arr['Titel']) . "\n" . $prefix . "?area=" . AREA . "&lang=" . $_SESSION['lang'] . "&p=shop&action=showproduct&id={$id}&cid={$key}\n\n";
						}
						
						
						$text = $GLOBALS['config_vars']['Shop_tellSeenText'];
						$text = str_replace('%N%', "\n", $text);
						$text = str_replace('%NAME%', substr(@$_POST['prod_tell_name'],0,100), $text);
						$text = str_replace('%ARTICLES%', $prod_tell, $text);
						$text = str_replace('%SENDER%', substr(@$_POST['prod_tell_rname'],0,100), $text);
						$text = str_replace('%SENDERMAIL%', substr(@$_POST['prod_tell_remail'],0,100), $text);
						
						$Koobi = new Koobi;
						$Koobi->koobi_mail($_POST['prod_tell_email'], $text, $GLOBALS['config_vars']['Shop_tellSubject'], $GLOBALS['settings']['Mail_Absender'], stripslashes($GLOBALS['settings']['Mail_Name']), "text", "");
						$GLOBALS['tmpl']->assign('send', 1);
					} else {
						$GLOBALS['tmpl']->assign('nocheckbox', 1);
					}
				break;
				
				case 'del':
					if(isset($_POST['prodid']) && !empty($_POST['prodid']))
					{
						foreach($_POST['prodid'] as $id => $key) unset($_SESSION['prod_seen'][$id]);
					} else {
						$GLOBALS['tmpl']->assign('nocheckbox', 1);
					}
				break;
				
				case 'merge':
					if(isset($_POST['prodid']) && !empty($_POST['prodid']))
					{
						foreach($_POST['prodid'] as $id => $key) $this->mergeProduct($id, '', $key);
						echo "<script>window.open('index.php?redir=1&p=misc&do=mergeproduct&prodid=$id&red=&cid=$key', 'merge_win', 'scrollbars=1,width=900,height=600,top=0,left=0');</script>";
					} else {
						$GLOBALS['tmpl']->assign('nocheckbox', 1);
					}
				break;
			}
		}
		
		
					
		$Products = $this->showProductsVarious($showall);
		$GLOBALS['tmpl']->assign('headernav', '<a href="index.php?p=shop">' . $GLOBALS['config_vars']['Shop'] . '</a>' .  $GLOBALS['config_vars']['PageSep'] . $GLOBALS['config_vars']['Shop_showSeenProducts']);
		$GLOBALS['tmpl']->assign('pagetitle_html', $GLOBALS['config_vars']['Shop'] . $GLOBALS['config_vars']['PageSep'] . $GLOBALS['config_vars']['Shop_showSeenProducts']);
		$GLOBALS['tmpl']->assign('seen_products_array', $Products);
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/all_seen_products.tpl'));
	}
	
	
	//=================================================================
	// Produkte auflisten (gesehene Artikel)
	//=================================================================
	function showProductsVarious($showall=0,$Array=0)
	{
		$seen_products = '';
		$lim_ls = ($showall != '0') ? 300 : 5;
		$Array = (isset($_SESSION['prod_seen']) && is_array($_SESSION['prod_seen'])) ? $_SESSION['prod_seen'] : $Array;
		
		if(is_array($Array) && !empty($Array))
		{
			foreach($Array as $val => $key) $ps[] = $val;
			krsort($ps);
			$seen_products = array();
			$seen_count = 1;
			foreach($ps as $val => $key)
			{
				if($seen_count <= $lim_ls)
				{
					$row_products = $GLOBALS['db']->ArrQuery("SELECT 
						a.Lagerbestand,
						a.Preis,
						a.Preis_Liste_Gueltig,
						a.Preis_Liste,
						a.Fsk18,
						a.Bild,
						a.Id,
						a.Kategorie,
						a.Titel_" . $_SESSION['Langcode'] . " as Titel,
						a.Beschreibung_" . $_SESSION['Langcode'] . " as Beschreibung,
						b.Name_1 as KatDefault,
						b.Name_" . $_SESSION['Langcode'] . " as Kategorie_Name 
					FROM 
						" . PREFIX . "_shop_produkte as a,
						" . PREFIX . "_shop_kategorie as b  
					WHERE a.Aktiv=1 AND a.Id = '" . $key. "' AND b.Id = a.Kategorie ");
					if(is_array($row_products))
					{
						if(!$row_products['Kategorie_Name']) $row_products['Kategorie_Name'] = $row_products['KatDefault'];

						// Gueltigkeit eines Preises
						if(($row_products['Preis_Liste']>$row_products['Preis']) && ($row_products['Preis_Liste']>0) && ($row_products['Preis_Liste_Gueltig'] == 0) || ($row_products['Preis_Liste']>$row_products['Preis'] && $row_products['Preis_Liste_Gueltig'] != 0 && $row_products['Preis_Liste_Gueltig'] < stime()))
						{
							$row_products['Preis'] = $row_products['Preis_Liste'];
						} 
						
						$row_products['Bild_Orig'] = $row_products['Bild'];
						$row_products['Bild_Klein'] = (is_file(BASE_DIR . '/' . $this->_upload_path . 'small/' . $row_products['Bild'])) ? $this->_upload_path . 'small/' . $row_products['Bild'] : 'system/shopthumb.php?smode=small&amp;img=' . $row_products['Bild'];
						
						//=================================================================
						// Normalpreise
						//=================================================================
						$row_products['netto_price_orig'] = $this->getPrice($row_products['Preis']);
						$row_products['Preis'] = $this->getPrice($row_products['Preis']);
						
						//=================================================================
						// Nettopreis
						//=================================================================
						$row_products['netto_price'] = $this->getNettoPrice($row_products['Preis'], $row_products['Kategorie'], $_SESSION['user_country']);
						
						//=================================================================
						// Wenn nur Nettopreis angezeigt werden soll...
						//=================================================================
						$row_products['Preis'] = ($this->justNetto($_SESSION['user_country'])) ? $row_products['netto_price'] : $row_products['Preis'];
						
						//=================================================================
						// Shop soll Netto ausgeben
						//=================================================================
						if(NETTO_SHOP==1 || $this->userNettoshop()==1) $row_products['price_ust_ex'] = $row_products['netto_price_orig'] - $row_products['netto_price'];
						
						//=================================================================
						// Welcher Prozentsatz ist enthalten?
						//=================================================================
						$row_products['product_ust'] = $this->getUst($row_products['Kategorie']);
						$row_products['ProdLink'] = "index.php?p=shop&amp;action=showproduct&amp;id=" . $row_products['Id'] . "&amp;cid=" . $row_products['Kategorie'] . "&amp;pname=" . $this->get_clean_name($row_products['Titel']);
						
						//=================================================================
						// PopUp-Text
						//=================================================================
						$row_products['Pop_Text'] = "<h4>" . koobispecialchars($row_products['Titel']) . "</h4><br />" . koobispecialchars($row_products['Beschreibung']);
						
						//=================================================================
						// Gibt es Varianten?
						//=================================================================
						$r_varcheck = $GLOBALS['db']->RowQuery("SELECT DISTINCT(Id) FROM " . PREFIX . "_shop_varianten WHERE ArtId = '" . $row_products['Id'] . "'");
						if(is_object($r_varcheck) && $r_varcheck->Id >= 1) $row_products['Vars'] = 1;
			
						array_push($seen_products, $row_products);
						$seen_count++;
					} else {
						unset($_SESSION['prod_seen'][$key]);
					}
				}
			}
		}
		
		$GLOBALS['tmpl']->assign('price_onlynetto', ($this->justNetto($_SESSION['user_country']) ? 1 : 0) );
		$GLOBALS['tmpl']->assign('no_nettodisplay', ($this->noNettoDisplay($_SESSION['user_country']) ? 1 : 0) );
		
		if(!empty($seen_products))
		{
			$GLOBALS['tmpl']->assign('is_seen_products',1);
			return $seen_products;
		}
	}
	
	function shippingTime($prod_id)
	{
		$r = $GLOBALS['db']->RowQuery("SELECT Lieferzeit_" . $_SESSION['Langcode'] . " AS Lieferzeit FROM " . PREFIX . "_shop_packzeiten WHERE Id = '{$prod_id}'");
		return (is_object($r)) ? $r->Lieferzeit : '';
	}
	
	
	//=================================================================
	//=================================================================
	// Produkt anzeigen
	//=================================================================
	//=================================================================
	function displayProduct($merge=0,$id=0,$smallimages=0)
	{
		if(isset($_POST['pricealert_email']) && !empty($_POST['pricealert_email']) && !empty($_POST['pricealert_newprice']))
		{
			$_POST['pricealert_newprice'] = number_format(str_replace(',','.',$_POST['pricealert_newprice']),'2','.','');
			if(!preg_match("/^[ -._A-Za-zÀ-ÖØ-öø-ÿ0-9\-]+(\.[_A-Za-zÀ-ÖØ-öø-ÿ0-9\-]+)*@([a-zA-Z0-9\-]+\.)+([a-zA-Z]{2,4})$/", $_POST['pricealert_email']) || !is_numeric($_POST['pricealert_newprice']) || $_POST['pricealert_newprice']<'0.01')
			{
				
				$GLOBALS['tmpl']->assign('pricealert_error', 1);
			} else {
				$res = $GLOBALS['db']->RowQuery("SELECT Id FROM " . PREFIX . "_shop_preisalarm WHERE ProdId = '" . $_REQUEST['id'] . "' AND Email = '" . $_POST['pricealert_email'] . "'");
				$GLOBALS['tmpl']->assign('pricealert_ok', 1);
				if(!is_object($res))
				{
					$prod_link = $_SERVER['REQUEST_URI'];
					$prod_link = explode('index.php?', $prod_link);
					$prod_link = 'index.php?' . $prod_link[1];
					$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_shop_preisalarm (Id,ProdId,Email,Datum,Ip,Preis) VALUES ('','" . $_REQUEST['id'] . "','" . $_POST['pricealert_email'] . "','" . time() . "', '" . $_SERVER['REMOTE_ADDR']. "', '" . $_POST['pricealert_newprice'] . "')");
				}
			}
		}
		
		//=================================================================
		// Produktanfrage
		//=================================================================
		$_SESSION['whole_name'] = @$_SESSION['benutzer_vorname'] . ' ' . @$_SESSION['benutzer_nachname'];
		$error = '';
		$use_code = -1;
		if(isset($_REQUEST['subaction']) && $_REQUEST['subaction'] == 'product_request')
		{
			if($GLOBALS['settings']['Sicherheitscode']==1) 
			{
				$GLOBALS['tmpl']->assign('use_code', 1);
				$use_code = 1;
			}
			
			if(!isset($_REQUEST['sub']) && $use_code == 1 || (empty($_POST['product_request_text']))) giveSecure();
			
			//=================================================================
			// Produktanfrage senden
			//=================================================================
			if(isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'product_request' && !empty($_POST['product_request_text']))
			{
				if($use_code==1)
				{
					$scode_form = (isset($_POST['scode']) && !empty($_POST['scode'])) ? $_POST['scode'] : '';
					$scode_ses = @$_SESSION['scode'];
					
					if(($use_code && @empty($_POST['scode'])) || (!$_SESSION['scode'] && $use_code) || ($scode_form != $scode_ses && ($use_code)))
					{
						$error .= $GLOBALS['config_vars']['Reg_SecurecodeWrong'] . "<br />";
						giveSecure();
						$secureCode = rand_string(4); 
						$_SESSION['scode'] = $secureCode; 
					} else {
						$_SESSION['scode'] = $_POST['scode'];
						giveSecure($_SESSION['scode']);
						$secureCode = $_POST['scode']; 
					}
				}
				
				if(empty($_POST['product_request_email'])) $error .= $GLOBALS['config_vars']['Shop_prod_request_nomail'] . "<br />";
				if(empty($_POST['product_request_name'])) $error .= $GLOBALS['config_vars']['Shop_prod_request_noname'] . "<br />";
				
				if($error)
				{
					$GLOBALS['tmpl']->assign('product_request_text', @$_POST['product_request_text']);
					$GLOBALS['tmpl']->assign('error', $error);
				} else {
					giveSecure();
					
					$msg = $GLOBALS['config_vars']['Shop_prod_request_text'];
					$msg = str_replace("--N--","\n",$msg);
					$msg = str_replace("--BENUTZER--",stripslashes($_POST['product_request_name']),$msg);
					$msg = str_replace("--DATUM--",date('d.m.Y',stime()),$msg);
					$msg = str_replace("--PRODNAME--",$_POST['prod_name'],$msg);
					$msg = str_replace("--ID--",$_POST['id'],$msg);
					$msg = str_replace("--LINK--", thisHome() . "index.php?p=shop&action=showproduct&id=" . $_POST['id'] . "&cid=" . $_POST['cid'], $msg);
					$msg = str_replace("--TEXT--",stripslashes($_POST['product_request_text']),$msg);
					
					$Koobi = new Koobi;
					$shop_settings = $GLOBALS['db']->RowQuery("SELECT Name_Abs,Email_Produktanfrage FROM " . PREFIX . "_shop_einstellungen");
					$Koobi->koobi_mail($shop_settings->Email_Produktanfrage, $msg, $GLOBALS['config_vars']['Shop_prod_request_mailsubject'], $_POST['product_request_email'], stripslashes($_POST['product_request_name']), 'text', '', '');		
					$GLOBALS['tmpl']->assign('msg_send', 1);
				}
			}		
		}
		
		//=================================================================
		// Bewertung
		//=================================================================
		if(get_active('shop_bewertung'))
		{
			if($_SESSION['user_group'] != 2)
			{
				if(isset($_REQUEST['sub']) && $_REQUEST['sub'] == 'prod_vote' && !empty($_REQUEST['prod_vote_text']) && $_REQUEST['prod_vote_points'] <= 5)
				{
					$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_shop_bewertung (Id,Produkt,Bewertung,Bewertung_Punkte,Benutzer,Datum,Ip,Offen) VALUES ('','" . $_REQUEST['id'] . "','" . $_REQUEST['prod_vote_text'] . "','" . $_REQUEST['prod_vote_points'] . "','" . $_SESSION['benutzer_id'] . "','" . stime() . "','" . $_SERVER['REMOTE_ADDR'] . "',0)");
					
					$Koobi = new Koobi;
					$shop_settings = $GLOBALS['db']->RowQuery("SELECT Email_Wertung,Name_Abs,Email_Abs FROM " . PREFIX . "_shop_einstellungen");
					
					//=================================================================
					// Email senden
					//=================================================================
					$msg = $GLOBALS['config_vars']['Shop_prod_vote_textEmail'];
					$msg = str_replace("--N--","\n",$msg);
					$msg = str_replace("--BENUTZER--",$_SESSION['user_name'],$msg);
					$msg = str_replace("--DATUM--",date('d.m.Y',stime()),$msg);
					$msg = str_replace("--PRODNAME--",$_POST['prod_name'],$msg);
					$msg = str_replace("--ID--",$_POST['id'],$msg);
					$msg = str_replace("--ADMINLINK--", thisHome() . "admin/index.php?do=shop&sub=article_votes&id=" . $_POST['id'] . "&noframes=1", $msg);
					$msg = str_replace("--TEXT--",stripslashes($_REQUEST['prod_vote_text']),$msg);
					$Koobi->koobi_mail($shop_settings->Email_Wertung, $msg, $GLOBALS['config_vars']['Shop_prod_vote_mailsubject'], $shop_settings->Email_Abs, stripslashes($shop_settings->Name_Abs), 'text', '', '');		
					$r = str_replace('&amp;','&',base64_decode($_REQUEST['red']));
					refer("{$r}#vote");
				}
			}
			
			$votes = array();
			$sql_v = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_bewertung WHERE Produkt = '" . $_REQUEST['id'] . "' AND Offen = 1 ORDER BY Datum DESC");
			while($row_v = $sql_v->fetchrow())
			{
				$row_v->Benutzer = getUsername($row_v->Benutzer);
				$row_v->Bewertung = nl2br(strip_tags(koobispecialchars($row_v->Bewertung)));
				array_push($votes, $row_v);
			}
			
			$GLOBALS['tmpl']->assign('votes',$votes);
			$GLOBALS['tmpl']->assign('shop_bewertung',1);
		}
		
		unset($_SESSION['r_land']);
		$just_netto = ($this->justNetto($_SESSION['user_country'])) ? true : false;
		
		$_SESSION['prod_seen'][$_REQUEST['id']] = time();//time();
		
		if($id!='0') $_REQUEST['id'] = $id;
		if(permission('shop_images'))
		{
			$this->upload_multi();
			
			$allowed = array('image/pjpeg','image/jpeg','image/x-png','image/png','image/gif');
			if(isset($_FILES['file']) && !empty($_FILES['file']) && in_array($_FILES['file']['type'], $allowed))
			{
				switch($_FILES['file']['type'])
				{
					case 'image/pjpeg' :
					case 'image/jpeg' :
					case '' :
						$new_name = md5(time() . mt_rand(10001, 19999) . $_FILES['file']['tmp_name']) . '.jpg';
					break;
					
					case 'image/x-png' :
					case 'image/png' :
						$new_name = md5(time() . mt_rand(10001, 19999) . $_FILES['file']['tmp_name']) . '.png';
					break;
					
					case 'image/gif' :
						$new_name = md5(time() . mt_rand(10001, 19999) . $_FILES['file']['tmp_name']) . '.gif';
					break;
				}
				@move_uploaded_file($_FILES['file']['tmp_name'], BASE_DIR . '/uploads/shop/icons/' . $new_name);
				$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_produkte SET Bild = '$new_name' WHERE Id = '" . $_REQUEST['id'] . "'");
			}
		}
		
		$Lc = $_SESSION['Langcode'];
		$count = '';
		$count_vars = '';
		$price_ext_first = '';
		$price_ext = '';
		$vars = '';
		$vars_second = '';
		$var_options_second = '';
		$Bilder_Klein = '';
		
		
		
		if($Lc != 1)
		{
			$q_l = "
				Spez_1_$Lc AS Spez_1,
				Spez_2_$Lc AS Spez_2,
				Spez_3_$Lc AS Spez_3,
				Spez_4_$Lc AS Spez_4,
				Spez_5_$Lc AS Spez_5,
				Spez_6_$Lc AS Spez_6,
				Spez_7_$Lc AS Spez_7,
				Spez_8_$Lc AS Spez_8,
				Spez_9_$Lc AS Spez_9,
				Spez_10_$Lc AS Spez_10,
				Spez_11_$Lc AS Spez_11,
				Spez_12_$Lc AS Spez_12,
				Spez_13_$Lc AS Spez_13,
				Spez_14_$Lc AS Spez_14,
				Spez_15_$Lc AS Spez_15,
				";
		} else {
			$q_l = "";
		}
		
		$row_products = $GLOBALS['db']->ArrQuery("
		SELECT *,
			$q_l  
			Zub_c AS Tuningteile,
			Titel_$Lc as Titel,
			Beschreibung_$Lc as Beschreibung, 
			Beschreibung_lang_$Lc as BeschreibungLang,
			Beschreibung_1 as BeschreibungDef, 
			Beschreibung_lang_1 as BeschreibungLangDef  
		FROM 
			" . PREFIX . "_shop_produkte WHERE Aktiv=1 AND Id = '" . $_REQUEST['id'] . "'");
		if(!is_array($row_products))
		{
			$GLOBALS['tmpl']->assign('notfound',1);
			$GLOBALS['tmpl']->assign('headernav', $GLOBALS['config_vars']['Shop']);
			$GLOBALS['tmpl']->assign('pagetitle_html', $GLOBALS['config_vars']['Shop']);
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/' . $this->_product_detail_tpl));
		} else {
			if(!isset($_SESSION['product_view_'][$row_products['Id']]))
			{
				$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_produkte SET Klicks=Klicks+1 WHERE Id = '" . $row_products['Id'] . "'");
				$_SESSION['product_view_'][$row_products['Id']] = 'true';
			}
			
			
			if(!$row_products['Beschreibung']) $row_products['Beschreibung'] = $row_products['BeschreibungDef'];
			if(!$row_products['BeschreibungLang']) $row_products['BeschreibungLang'] = $row_products['BeschreibungLangDef'];
			
			$row_products['KategorieName'] = $this->getCategName($row_products['Kategorie']);
			//=================================================================
			// Varianten neu
			//=================================================================
			$var_check = $GLOBALS['db']->Query("SELECT DISTINCT(ArtId) FROM " . PREFIX . "_shop_varianten WHERE ArtId='" . $row_products['Id'] . "'");
			$num_check = $var_check->numrows();
			if($num_check >= 1)
			{
				$vars_categs = array();
				$sql_vars = $GLOBALS['db']->Query("
				SELECT 
					Id AS Kat_Id,
					Name_" . $_SESSION['Langcode'] . " AS Kat_Name,
					Beschreibung_" . $_SESSION['Langcode'] . " AS Kat_Beschreibung 
				FROM 
					" . PREFIX . "_shop_varianten_kategorien WHERE Aktiv = 1 AND KatId = '" . $_REQUEST['cid'] . "'
				");
				while($row_array = $sql_vars->fetcharray())
				{
					$vars_options = array();
					$sql_vars_options = $GLOBALS['db']->Query("SELECT *, Name_" . $_SESSION['Langcode'] . " AS VarName FROM " . PREFIX . "_shop_varianten WHERE KatId='" . $row_array['Kat_Id'] . "' AND ArtId='" . $_REQUEST['id'] . "' ORDER BY Position ASC");
					while($row_vars_array = $sql_vars_options->fetcharray())
					{
						if(NETTO_SHOP==1 || $this->userNettoshop()==1 || $this->justNetto($_SESSION['user_country']))
						{
							$row_vars_array['Price'] = $row_vars_array['Operant'] . $this->getNettoPrice($this->getPrice($row_vars_array['Wert']), $row_products['Kategorie'], $_SESSION['user_country']);
						} else {
							$row_vars_array['Price'] = $row_vars_array['Operant'] . $this->getPrice($row_vars_array['Wert']);
						}
						array_push($vars_options, $row_vars_array);
					}
					$row_array['vars'] = $vars_options; 
					if($row_array['vars']) array_push($vars_categs, $row_array);
				}
				
				$GLOBALS['tmpl']->assign('vars_categs', $vars_categs);
			}
			
			$GLOBALS['tmpl']->assign('no_vars', 1);
			
			//=================================================================
			// Bild
			//=================================================================
			$row_products['Bild_Orig'] = $row_products['Bild'];
			
			if($smallimages==1)
			{
				$row_products['Bild'] = (is_file(BASE_DIR . '/' . $this->_upload_path . 'medium/' . $row_products['Bild'])) ? $this->_upload_path . 'medium/' . $row_products['Bild'] : 'system/shopthumb.php?smode=4&amp;img=' . $row_products['Bild'];
			} else {
				$row_products['Bild'] = (is_file(BASE_DIR . '/' . $this->_upload_path . 'normal/' . $row_products['Bild'])) ? $this->_upload_path . 'normal/' . $row_products['Bild'] : 'system/shopthumb.php?smode=2&amp;img=' . $row_products['Bild'];
			}
			
			$row_products['Lieferzeit'] = $this->shippingTime($row_products['Lieferzeit']);
			$row_products['VIcon'] = $this->getAvIcon($row_products['Bestellt'],$row_products['Lagerbestand'], $row_products['Verfuegbar']);
			$row_products['VMsg'] = $this->getAvMsg($row_products['Bestellt'],$row_products['Lagerbestand'], $row_products['Verfuegbar']);
		
			//=================================================================
			// Normalpreise
			//=================================================================
			$row_products['netto_price_orig'] = $this->getPrice($row_products['Preis']) + $price_ext + $price_ext_first;
			$row_products['netto_price_orig_list'] = $this->getPrice($row_products['Preis_Liste']) + $price_ext + $price_ext_first;
			$row_products['Preis'] = $this->getPrice($row_products['Preis']) + $price_ext + $price_ext_first;
			$row_products['Preis_Liste'] = $this->getPrice($row_products['Preis_Liste']) + $price_ext + $price_ext_first;
			
			//=================================================================
			// Nettopreis
			//=================================================================
			$row_products['netto_price'] = $this->getNettoPrice($row_products['Preis'], $row_products['Kategorie'], $_SESSION['user_country']);
			$row_products['netto_price_list'] = $this->getNettoPrice($row_products['Preis_Liste'], $row_products['Kategorie'], $_SESSION['user_country']);
			
			//=================================================================
			// Wenn nur Nettopreis angezeigt werden soll...
			//=================================================================
			
			$row_products['Preis_Liste'] = ($just_netto==true) ? $row_products['netto_price_list'] : $row_products['Preis_Liste'];
			
			// Gueltigkeit eines Preises
			if(($row_products['Preis_Liste']>0) && ($row_products['Preis_Liste_Gueltig'] == 0) || ($row_products['Preis_Liste_Gueltig'] != 0 && $row_products['Preis_Liste_Gueltig'] < stime()))
			{
				$row_products['netto_price_orig'] = $this->getPrice($row_products['Preis_Liste']) + $price_ext + $price_ext_first;
				$row_products['Preis'] = ($just_netto==true) ? $row_products['netto_price_list'] : $row_products['Preis_Liste'];
				$row_products['netto_price'] = $this->getNettoPrice($row_products['Preis'], $row_products['Kategorie'], $_SESSION['user_country']);
				$row_products['Preis_Liste'] = 0;
				
				
			} elseif(($row_products['Preis_Liste']>$row_products['Preis'])) {
				$row_products['netto_price_orig'] = $this->getPrice($row_products['Preis']) + $price_ext + $price_ext_first;
				$row_products['Preis'] = ($just_netto==true) ? $row_products['netto_price'] : $row_products['Preis'];
				$row_products['netto_price'] = $this->getNettoPrice($row_products['Preis'], $row_products['Kategorie'], $_SESSION['user_country']);
				$row_products['Angebot'] = 1;
				
			} else {
				$row_products['Preis_Liste'] = ($just_netto==true) ? $row_products['netto_price_list'] : $row_products['Preis_Liste'];
				$row_products['Preis'] = ($just_netto==true) ? $row_products['netto_price'] : $row_products['Preis'];
				$row_products['netto_price_orig'] = $this->getPrice($row_products['Preis']) + $price_ext + $price_ext_first;
				$row_products['netto_price'] = $this->getNettoPrice($row_products['Preis'], $row_products['Kategorie'], $_SESSION['user_country']);
			}
			
			//=================================================================
			// Shop soll Netto ausgeben
			//=================================================================
			if(NETTO_SHOP==1 || $this->userNettoshop()==1)$row_products['price_ust_ex'] = $row_products['netto_price_orig'] - $row_products['netto_price'];
			
			//=================================================================
			// Welcher Prozentsatz ist enthalten?
			//=================================================================
			$row_products['product_ust'] = $this->getUst($row_products['Kategorie']);
			$row_products['product_ust_js'] = ($row_products['product_ust'] < 10) ? '1.0' . str_replace('.','',$row_products['product_ust']) : '1.' . str_replace('.','',$row_products['product_ust']);
			//=================================================================
			// Einheiten 
			//=================================================================
			if($row_products['EinheitId'] > 0 && $row_products['EinheitCount'] != '0.00')
			{
				$EinheitArray = $this->getUnits($row_products['EinheitId']);
				$row_products['Einheit'] = $EinheitArray['Einheit'];
				$row_products['EinheitMz'] = $EinheitArray['EinheitMz'];
				$row_products['EinheitOut'] = ($row_products['EinheitCount']>1) ? $EinheitArray['EinheitMz'] : $EinheitArray['Einheit'];
				$row_products['EinheitPreisEinzel'] =  $row_products['Preis'] / $row_products['EinheitCount'];
				$row_products['EinheitPreisEinzelNetto'] =  $row_products['netto_price'] / $row_products['EinheitCount'];
			}
			
			//=================================================================
			// Seiten-Navi zusammensetzen 
			//=================================================================
			$headernav = getNavigationPath($row_products['Kategorie'], 'shop_kategorie', 'shop', 'cid', 'Id', 'Name_'.$_SESSION['Langcode'], '', '', '', '', 'Parent_Id', $GLOBALS['config_vars']['Shop']);
			$pagetitle = clean_page_title($headernav, $row_products['Titel']);
			
			$row_products['Parent'] = $this->get_parent_shopcateg($row_products['Kategorie']);
			$row_products['Navop'] = ($this->get_parent_shopcateg($row_products['Parent'])==0) ? $row_products['Parent'] : $this->get_parent_shopcateg($row_products['Parent']);
			$row_products['ProdLink'] = "index.php?p=shop&amp;action=showproduct&amp;id=" . $row_products['Id'] . "&amp;cid=" . $row_products['Kategorie'] . "&amp;pname=" . $this->get_clean_name($row_products['Titel']);
			
			if($count == $count_vars) $GLOBALS['tmpl']->assign('to_basket', 1);
			
			//=================================================================
			// Ausfuehrliche Details
			//=================================================================
			$LC = $_SESSION['Langcode'];
			if($LC != 1)
			{
				$q_l = "
					Spez_1_$LC AS Spez_1,
					Spez_2_$LC AS Spez_2,
					Spez_3_$LC AS Spez_3,
					Spez_4_$LC AS Spez_4,
					Spez_5_$LC AS Spez_5,
					Spez_6_$LC AS Spez_6,
					Spez_7_$LC AS Spez_7,
					Spez_8_$LC AS Spez_8,
					Spez_9_$LC AS Spez_9,
					Spez_10_$LC AS Spez_10,
					Spez_11_$LC AS Spez_11,
					Spez_12_$LC AS Spez_12,
					Spez_13_$LC AS Spez_13,
					Spez_14_$LC AS Spez_14,
					Spez_15_$LC AS Spez_15 
					";
			} else {
				$q_l = "*";
			}
			$det_spez = $GLOBALS['db']->ArrQuery("SELECT $q_l FROM " . PREFIX . "_shop_kategorie_spezifikation WHERE Kategorie = '" . $row_products['Kategorie'] . "'");
			if(is_array($det_spez) && $det_spez['Spez_1']) $GLOBALS['tmpl']->assign('det_spez', $det_spez);
			
			//=================================================================
			// Weitere Bilder
			//=================================================================
			if($row_products['Bilder'] != '')
			{
				$Bilder_Klein = array();
				$bilder = explode('|', $row_products['Bilder']);
				$count = 1;
				foreach($bilder as $bild)
				{
					if($count <= 3) 
					{
						$arr['Bild'] = (is_file(BASE_DIR . '/' . $this->_upload_path . 'small/' . $bild)) ? $this->_upload_path . 'small/' . $bild : 'system/shopthumb.php?smode=small&amp;img=' . $bild;
						$arr['Bild_Normal'] = (is_file(BASE_DIR . '/' . $this->_upload_path . 'normal/' . $bild)) ? $this->_upload_path . 'normal/' . $bild : 'system/shopthumb.php?smode=2&amp;img=' . $bild;
						if(!empty($bild)) array_push($Bilder_Klein, $arr);
					}
					$count++;
				}
			} else {
				$GLOBALS['tmpl']->assign('img_pop', 1);
			}
			
			if($merge==1)
			{
				$row_products['count'] = $count;
				return $row_products;
			} else {
				// Aehnliche Produkte (Schlagwoerter Tab 4)
				if($row_products['Schlagwoerter'] != NULL) 
				{
					$GLOBALS['tmpl']->assign('Zub_d_products_array', $this->similarProducts($row_products['Schlagwoerter']));
					$GLOBALS['tmpl']->assign('Zub_d_products', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/small_similar_products.tpl'));
				}
				
				// Teile (Tab 1)
				if($row_products['Zub_a'] != NULL) 
				{
					$GLOBALS['tmpl']->assign('Zub_a_products_array', $this->similarProducts($row_products['Zub_a'],1));
					$GLOBALS['tmpl']->assign('Zub_a_products', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/small_zuba_products.tpl'));
				}
				
				// Teile (Tab 2)
				if($row_products['Zub_b'] != NULL) 
				{
					$GLOBALS['tmpl']->assign('Zub_b_products_array', $this->similarProducts($row_products['Zub_b'],1));
					$GLOBALS['tmpl']->assign('Zub_b_products', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/small_zubb_products.tpl'));
				}
				
				// Teile (Tab 3)
				if($row_products['Zub_c'] != NULL) 
				{ 
					
					$GLOBALS['tmpl']->assign('Zub_c_products_array', $this->similarProducts($row_products['Zub_c'],1));
					$GLOBALS['tmpl']->assign('Zub_c_products', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/small_zubc_products.tpl'));
				}
				
				// Artikelbestand gering?
				if($row_products['Lagerbestand'] <= $this->_low_amount)
				{
					$GLOBALS['tmpl']->assign('low_amount',1);
				}
				
				// Artikel ausverkauft?
				if($row_products['Lagerbestand'] == '0' && $row_products['Verfuegbar']!=4)
				{
					$GLOBALS['tmpl']->assign('not_on_store',1);
					$GLOBALS['tmpl']->assign('not_available',1);
				}
				
				if($row_products['Verfuegbar']==4)
				{
					$GLOBALS['tmpl']->assign('order_for_you',1);
				}
				
				// Zubehoer-Tabs
				$Lc = $_SESSION['Langcode'];
				$Tabs = $GLOBALS['db']->RowQuery("
				SELECT 
					Teile_1_Name_{$Lc} AS TAB1,
					Teile_2_Name_{$Lc} AS TAB2,
					Teile_3_Name_{$Lc} AS TAB3 
				FROM " . PREFIX . "_shop_kategorie_zubehoer WHERE Kategorie = '" . $row_products['Kategorie'] ."'");
				
				if(@$Tabs->TAB1 == NULL) $Tabs->TAB1 = $GLOBALS['config_vars']['Shop_accessories'];
				if(@$Tabs->TAB2 == NULL) $Tabs->TAB2 = $GLOBALS['config_vars']['Shop_parts'];
				if(@$Tabs->TAB3 == NULL) $Tabs->TAB3 = $GLOBALS['config_vars']['Shop_tuningparts'];
				$GLOBALS['tmpl']->assign('tabs',$Tabs);
				
				// Versandfreibetrag
				$p_free = $GLOBALS['shopsettings']->Versandfreibetrag;
				$p_price = $row_products['Preis'];
				$p_title = $row_products['Titel'];
				$GLOBALS['tmpl']->assign('shipping_free', (($p_price >= $p_free && ($p_free>0.01)) ? 1 : 0));
				
				$row_products['diff'] = $row_products['Preis_Liste'] - $row_products['Preis'];
				if($row_products['diff']>0) $row_products['diffpro'] = ($row_products['diff'] * 100) / $row_products['Preis_Liste'];
				
			
				$row_products['valid_till_info'] = $GLOBALS['config_vars']['Shop_valid_to']. ' ' . date('d.m.Y',$row_products['Preis_Liste_Gueltig']);
				$row_products['man'] = $this->getManufacturerById($row_products['Hersteller']);
				$row_products['GewichtF'] = file_size(($row_products['Gewicht']/1024),1);
				$row_products['GewichtRaw'] = ($row_products['Gewicht_Ohne']>=1) ? file_size(($row_products['Gewicht_Ohne']/1024),1) : 0;
				
				
				$GLOBALS['tmpl']->assign('p_title',$row_products['Titel']);
				$GLOBALS['tmpl']->assign('price_alert', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/shop_pricealert.tpl'));
				$GLOBALS['tmpl']->assign('st_prices', $this->getStaffelPreise($row_products['Id'],$row_products['Kategorie']));
				$GLOBALS['tmpl']->assign('red', base64_encode(redir()));
				$GLOBALS['tmpl']->assign('count', $count);
				$GLOBALS['tmpl']->assign('images', $Bilder_Klein);
				$GLOBALS['tmpl']->assign('headernav', $headernav);
				$GLOBALS['tmpl']->assign('vars', $vars);
				$GLOBALS['tmpl']->assign('vars_second', $vars_second);
				$GLOBALS['tmpl']->assign('price_onlynetto', ($this->justNetto($_SESSION['user_country']) ? 1 : 0) );
				$GLOBALS['tmpl']->assign('p', $row_products);
				$GLOBALS['tmpl']->assign('TaxValue', $this->getUstByCateg($row_products['Kategorie']));
				$GLOBALS['tmpl']->assign('redir', redir());
				$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/' . $this->_product_detail_tpl));
				$GLOBALS['tmpl']->assign('pagetitle_html', $pagetitle);
			}
		}
	}
	
	function getUstByCateg($categ)
	{
		$res1 = $GLOBALS['db']->RowQuery("SELECT UstId FROM " . PREFIX . "_shop_kategorie WHERE Id = '$categ'");
		$res2 = $GLOBALS['db']->RowQuery("SELECT Wert FROM " . PREFIX . "_shop_ustzone WHERE Id = '$res1->UstId'");
		return number_format($res2->Wert,'2','.','');
	}
	
	
	function similarProducts($words,$accessories=0)
	{
		unset($_SESSION['r_land']);
		
		$similar_products = array();
		
		if($accessories==0)
		{
			$lim_ls = $this->_similar_limit;
			$Array = explode(',',$words);
			
			$query_sw = " AND (Schlagwoerter = '{$words}' ";
			foreach($Array as $Key)
			{
				$Key = addslashes($Key);
				$query_sw .= " OR Schlagwoerter = '{$Key}' OR Schlagwoerter LIKE '{$Key},%' OR Schlagwoerter LIKE '%,{$Key}' OR Schlagwoerter LIKE '%,{$Key},%'";
			}
			$query_sw .= ")";
		} else {
			$lim_ls = $this->_accessories_limit;
			$Array = explode(',',$words);
			$query_sw = " AND (Id = '" . addslashes($_REQUEST['id']) . "' ";
			foreach($Array as $Key) $query_sw .= " OR Id = '". addslashes($Key)."'";
			$query_sw .= ")";
		}
		$q = "SELECT Fsk18, Zub_b, MinBestellung, Preis_Liste,Preis_Liste_Gueltig,Preis,Bild,Id,Kategorie,Titel_" . $_SESSION['Langcode'] . " as Titel,Beschreibung_" . $_SESSION['Langcode'] . " as Beschreibung FROM " . PREFIX . "_shop_produkte WHERE Aktiv=1 {$query_sw} AND Id != '" . addslashes($_REQUEST['id']) . "' ORDER BY RAND() LIMIT {$lim_ls}";
		$arr = $GLOBALS['db']->Query($q);
		while($row_products = $arr->fetcharray())
		{
			// Gueltigkeit eines Preises
			if(($row_products['Preis_Liste']>$row_products['Preis']) && ($row_products['Preis_Liste']>0) && ($row_products['Preis_Liste_Gueltig'] == 0) || ($row_products['Preis_Liste']>$row_products['Preis'] && $row_products['Preis_Liste_Gueltig'] != 0 && $row_products['Preis_Liste_Gueltig'] < stime()))
			{
				$row_products['Preis'] = $row_products['Preis_Liste'];
			} 
						
			$row_products['Bild_Orig'] = $row_products['Bild'];
			$row_products['Bild_Klein'] = (is_file(BASE_DIR . '/' . $this->_upload_path . 'small/' . $row_products['Bild'])) ? $this->_upload_path . 'small/' . $row_products['Bild'] : 'system/shopthumb.php?smode=small&amp;img=' . $row_products['Bild'];
			$row_products['netto_price_orig'] = $this->getPrice($row_products['Preis']);
			$row_products['Preis'] = $this->getPrice($row_products['Preis']);
			$row_products['netto_price'] = $this->getNettoPrice($row_products['Preis'], $row_products['Kategorie'], $_SESSION['user_country']);
			$row_products['Preis'] = ($this->justNetto($_SESSION['user_country'])) ? $row_products['netto_price'] : $row_products['Preis'];
			
			if(NETTO_SHOP==1 || $this->userNettoshop()==1) $row_products['price_ust_ex'] = $row_products['netto_price_orig'] - $row_products['netto_price'];
			
			$row_products['product_ust'] = $this->getUst($row_products['Kategorie']);
			$row_products['ProdLink'] = "index.php?p=shop&amp;action=showproduct&amp;id=" . $row_products['Id'] . "&amp;cid=" . $row_products['Kategorie'] . "&amp;pname=" . seotitle(koobispecialchars($row_products['Titel']));
			
			
			// PopUp-Text
			$row_products['Pop_Text'] = "<strong>" . koobispecialchars($row_products['Titel']) . "</strong><br />" . koobispecialchars($row_products['Beschreibung']);
			
			
			
			// Gibt es Varianten?
			$r_varcheck = $GLOBALS['db']->RowQuery("SELECT DISTINCT(Id) FROM " . PREFIX . "_shop_varianten WHERE ArtId = '" . $row_products['Id'] . "'");
			if(is_object($r_varcheck) && $r_varcheck->Id >= 1) $row_products['Vars'] = 1;
			
			array_push($similar_products, $row_products);
		}

		if(!empty($similar_products))
		{
			return $similar_products;
		}
	}
	
	//=================================================================
	// Staffelpreise
	//=================================================================
	function getStaffelPreise($prodid,$categ)
	{
		$staffel = array();
		$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_staffelpreise WHERE ArtikelId = '{$prodid}' ORDER BY Von ASC");
		while($row = $sql->fetchrow())
		{
			array_push($staffel, $row);
		}
		return $staffel;
	}
	
	
	//=================================================================
	// Produktuebersicht
	//=================================================================
	function listProducts($colums=0,$out=1,$shop_start=0,$topseller=0,$ex_limit=0,$no_colums=0,$recorder=0,$angebote=0)
	{
		$Title_S = '';
		$Manu_S = '';
		$na_sort = '';
		$is_offers = '';
		$is_topseller = '';
		$is_new = '';
		$is_lowamount = '';
		$Price_s = '';
		$Price_n = '';
		
		$Products = array();
		$Lc = $_SESSION['Langcode'];
		
		if($no_colums==1)
		{
			$lim = $ex_limit;
			if($recorder == 1) $lim = 100;
		} else {
			$lim = ($shop_start==1) ? $this->_start_limit : $this->_limit;
			$this->_colums = ($colums!=0) ? $colums : 2;
			if($ex_limit != 0) $lim = $ex_limit;
			
			if(!isset($_REQUEST['shop_q']) || @$_REQUEST['shop_q']=='') 
			{
				$shop_q = "shop_q=empty&amp;";
				$_REQUEST['shop_q'] = "empty";
			}
			
			if(isset($_REQUEST['shop_q']) && !empty($_REQUEST['shop_q']) && strlen($_REQUEST['shop_q'])>=2 && $_REQUEST['shop_q']!='empty')
			{
				$q_s = urldecode($_REQUEST['shop_q']);
				$search_s = $q_s;
				
				$Title_S = "(Titel_$Lc LIKE '%{$search_s}%' OR  Titel_$Lc LIKE '%" . koobispecialchars($search_s) . "%' OR 
				Beschreibung_$Lc LIKE '%{$search_s}%' OR  Beschreibung_$Lc LIKE '%" . koobispecialchars($search_s) . "%' OR 
				Artikelnummer = '{$search_s}' OR  
				Schlagwoerter LIKE '%{$search_s}%' OR Schlagwoerter LIKE '%" . koobispecialchars($search_s) . "%') AND ";
			}
			
			if(isset($_REQUEST['man'])) 
			{
				$q_m = (int)$_REQUEST['man'];
				$Manu_S  = ($q_m != 0) ? " Hersteller = '$q_m' AND " : "";
			}
			
		}
		if($shop_start==1)
		{
			$s_lim = "LIMIT 0,3";
			$db_ss =  " AND Startseite = '1' ";
			$db_sort = " Id DESC " /* posi_overview,Id DESC */;
		} else {
			$s_lim = "";
			$db_ss = "";
			$db_sort = " Id DESC ";
		}
		
		if($topseller==1)
		{
			$lim = $ex_limit;//$this->_topseller_limit;
			$db_ss = " AND Startseite = '1' ";
			$s_lim = "LIMIT 0,3";
			$db_sort = " Verkauft DESC ";
		}
		
		if($angebote==1)
		{
			
			$lim = $this->_offer_limit;
			$db_ss = " AND Startseite = '1' ";
			$s_lim = "LIMIT 0,3";
			$db_sort = " RAND() ";
			$Manu_S = " (Preis != Preis_Liste AND Preis != '0.00' AND Preis_Liste_Gueltig >= '" . stime() . "') AND ";
		}
		
		if(isset($_REQUEST['pf']) && isset($_REQUEST['pt']) && !empty($_REQUEST['pf']) && !empty($_REQUEST['pt']))
		{
			$_REQUEST['pf'] = number_format(preg_replace('/([^.0-9]*)/', '',$_REQUEST['pf']),2,'.','');
			$_REQUEST['pt'] = number_format(preg_replace('/([^.0-9]*)/', '',$_REQUEST['pt']),2,'.','');
			if($_REQUEST['pt'] > '0.00')
			{
				$Price_s = " AND ((Preis_Liste BETWEEN '$_REQUEST[pf]' AND '$_REQUEST[pt]') OR (Preis < Preis_Liste AND (Preis BETWEEN '$_REQUEST[pf]' AND '$_REQUEST[pt]') AND Preis_Liste_Gueltig >= '" . stime() . "')) ";
				$Price_n = "&amp;pf=$_REQUEST[pf]&amp;pt=$_REQUEST[pt]";
			}
		} else {
			$_REQUEST['pf'] = '1.00';
			$_REQUEST['pt'] = '1000.00';
		}
			
		if(isset($_REQUEST['offers']) && $_REQUEST['offers'] == 1)
		{
			$s_lim = "";
			$db_ss = "";
			$db_sort = " Id DESC ";
			$Manu_S = " (Preis != Preis_Liste AND Preis != '0.00' AND Preis_Liste_Gueltig >= '" . stime() . "') AND ";
			$is_offers = "&amp;offers=1";
		}
		
		if(isset($_REQUEST['topseller']) && $_REQUEST['topseller'] == 1)
		{
			$s_lim = "";
			$db_ss = "";
			$db_sort = " Verkauft DESC ";
			$is_topseller = "&amp;topseller=1";
		}
		
		if(isset($_REQUEST['lowamount'])  && $_REQUEST['lowamount'] == 1)
		{
			$s_lim = "";
			$db_ss = "";
			$db_sort = " Lagerbestand ASC ";
			$Manu_S = " (Lagerbestand <= " . $this->_low_amount . ") AND ";
			$is_lowamount = "&amp;lowamount=1";
		}
		
		$kat_desc = $GLOBALS['db']->ArrQuery("SELECT Beschreibung_" . $_SESSION['Langcode'] . " AS cat_desc FROM " . PREFIX . "_shop_kategorie WHERE Id = '" . (int)$_REQUEST['cid'] . "'");
		$GLOBALS['tmpl']->assign('cat_desc', $kat_desc['cat_desc']);
		
		// Limitierungs-Aufruf Produkte
		$this->_limit = (isset($_REQUEST['limit']) && !empty($_REQUEST['limit'])) ? $_REQUEST['limit'] : $this->_limit;
		$num = 0;
		$a = 0;
		$limit = $lim;
		
		//=================================================================
		// Alle weiteren 4 Ebenen durchgehen, ob Artikel vorhanden sind
		//=================================================================
		#$search_in_child = $this->get_child_items($_REQUEST['cid']);
		#$db_cid = (isset($_REQUEST['cid']) && !empty($_REQUEST['cid'])) ? " AND (Kategorie = '" . (int)$_REQUEST['cid'] . "'" . $search_in_child . ")" : "";
		
		//=================================================================
		// Multi-Kategorien
		//=================================================================
		$db_cid = (isset($_REQUEST['cid']) && !empty($_REQUEST['cid'])) ? " AND (Kategorie = '" . (int)$_REQUEST['cid'] . "' OR Kategorie_Multi  = '" . (int)$_REQUEST['cid'] . "' OR Kategorie_Multi like '%," . (int)$_REQUEST['cid'] . ",%' OR Kategorie_Multi like '%," . (int)$_REQUEST['cid'] . "' OR Kategorie_Multi like '" . (int)$_REQUEST['cid'] . ",%')" : "";
		
		
		
		
		
		if(!defined('NO_PAGENAV'))
		{
			$q_s = $GLOBALS['db']->RowQuery("SELECT COUNT(Id) AS ResCount FROM " . PREFIX . "_shop_produkte WHERE $Manu_S $Title_S Aktiv=1 $Price_s $db_cid $db_ss ORDER BY $db_sort  $s_lim");
			$num = $q_s->ResCount;
			
			//=================================================================
			// Wie viele Seiten gibt das System zurueck?
			//=================================================================
			if(!$limit) $limit = 10;
			$seiten = ceil($num / $limit);
			$a = prepage() * $limit - $limit;
		}
		
		
		if($no_colums==1)
		{
			$db_lim = "0,$limit";
		} else {
			$GLOBALS['tmpl']->assign('title_sort', 'title_asc');
			$GLOBALS['tmpl']->assign('price_sort', 'price_asc');
			$GLOBALS['tmpl']->assign('date_sort', 'date_asc');
			// Es wird eine Sortierung aufgerufen
			if(isset($_REQUEST['list']))
			{
				switch($_REQUEST['list'])
				{
					case '':
					case 'date_asc':
						$db_sort = " Erstellt ASC";
						$na_sort = "&amp;list=date_asc";
						$GLOBALS['tmpl']->assign('date_sort', 'date_desc');
						$GLOBALS['tmpl']->assign('img_date_sort', 'sorter_up.png');
					break;
					
					case 'date_desc':
						$db_sort = " Erstellt DESC";
						$na_sort = "&amp;list=date_desc";
						$GLOBALS['tmpl']->assign('date_sort', 'date_asc');
						$GLOBALS['tmpl']->assign('img_date_sort', 'sorter_down.png');
					break;
					
					case 'title_asc':
						$db_sort = " Titel_$Lc ASC";
						$na_sort = "&amp;list=title_asc";
						$GLOBALS['tmpl']->assign('title_sort', 'title_desc');
						$GLOBALS['tmpl']->assign('img_title_sort', 'sorter_up.png');
					break;
					
					case 'title_desc':
						$db_sort = " Titel_$Lc DESC";
						$na_sort = "&amp;list=title_desc";
						$GLOBALS['tmpl']->assign('title_sort', 'title_asc');
						$GLOBALS['tmpl']->assign('img_title_sort', 'sorter_down.png');
					break;
					
					case 'price_asc':
						$db_sort = " Preis_Liste ASC";
						$na_sort = "&amp;list=price_asc";
						$GLOBALS['tmpl']->assign('price_sort', 'price_desc');
						$GLOBALS['tmpl']->assign('img_price_sort', 'sorter_up.png');
					break;
					
					case 'price_desc':
						$db_sort = " Preis_Liste DESC";
						$na_sort = "&amp;list=price_desc";
						$GLOBALS['tmpl']->assign('price_sort', 'price_asc');
						$GLOBALS['tmpl']->assign('img_price_sort', 'sorter_down.png');
					break;
				}
			} else {
				// $GLOBALS['tmpl']->assign('title_sort', 'title_desc');
			}
			$db_lim = "$a,$limit";
		}
		
		
		$q_s = "SELECT 
			 	Id,
				Fsk18, 
				Kategorie,
				Kategorie_Multi,
				Artikelnummer,
				Preis,
				Preis_Liste,
				Preis_Liste_Gueltig,
				Erstellt,
				Klicks,
				Bild,
				Gewicht,
				Hersteller,
				EinheitCount,
				EinheitId,
				Startseite,
				Lagerbestand,
				Bestellt,
				Verfuegbar,
				Verkauft,
				EinzelBestellung,
				Verkauft,
				Lieferzeit,
			 	Titel_$Lc as Titel,
				Beschreibung_$Lc as Beschreibung,
				Titel_1 as TitelDef,
				Beschreibung_1 as BeschreibungDef  
			FROM 
				" . PREFIX . "_shop_produkte
			WHERE 
				$Manu_S 
				$Title_S 
				Aktiv=1 
				$Price_s 
				$db_cid 
				$db_ss 
			ORDER BY 
				$db_sort 
			LIMIT
				$db_lim";
		$sql_products = $GLOBALS['db']->Query($q_s);
		
		
		$Lc = $_SESSION['Langcode'];
		while($row_products = $sql_products->fetcharray())
		{
			$row_products['KategorieName'] = $this->getCategName($row_products['Kategorie']);
			
			if(!$row_products['Titel']) $row_products['Titel'] = $row_products['TitelDef'];
			if(!$row_products['Beschreibung']) $row_products['Beschreibung'] = $row_products['BeschreibungDef'];
			
			// Gueltigkeit eines Preises
			if(($row_products['Preis_Liste']>$row_products['Preis']) && ($row_products['Preis_Liste']>0) &&  ($row_products['Preis_Liste_Gueltig'] == 0) || ($row_products['Preis_Liste']>$row_products['Preis'] && $row_products['Preis_Liste_Gueltig'] != 0 && $row_products['Preis_Liste_Gueltig'] < stime()))
			{
				$row_products['Preis'] = $row_products['Preis_Liste'];
			} 
			
			// Gibt es Varianten?
			$r_varcheck = $GLOBALS['db']->RowQuery("SELECT DISTINCT(Id) FROM " . PREFIX . "_shop_varianten WHERE ArtId = '" . $row_products['Id'] . "'");
			if(is_object($r_varcheck) && $r_varcheck->Id >= 1) $row_products['Vars'] = 1;

			$row_products['Lieferzeit'] = $this->shippingTime($row_products['Lieferzeit']);
			$row_products['TaxValue'] = $this->getUstByCateg($row_products['Kategorie']);
			
			// Bild klein
			$row_products['Bild_Klein'] = (is_file(BASE_DIR . '/' . $this->_upload_path . 'small/' . $row_products['Bild'])) ? $this->_upload_path . 'small/' . $row_products['Bild'] : 'system/shopthumb.php?smode=small&amp;img=' . $row_products['Bild'];
			$row_products['Bild_Mittel'] = (is_file(BASE_DIR . '/' . $this->_upload_path . 'medium/' . $row_products['Bild'])) ? $this->_upload_path . 'medium/' . $row_products['Bild'] : 'system/shopthumb.php?smode=4&amp;img=' . $row_products['Bild'];
			
			// Normalpreise
			$row_products['netto_price_orig'] = $this->getPrice($row_products['Preis']);
			$row_products['Preis'] = $this->getPrice($row_products['Preis']);
			$row_products['Preis_Liste'] = $this->getPrice($row_products['Preis_Liste']);
			
			// Nettopreis
			$row_products['netto_price'] = $this->getNettoPrice($row_products['Preis'], $row_products['Kategorie'], $_SESSION['user_country']);
			$row_products['netto_price_liste'] = $this->getNettoPrice($row_products['Preis_Liste'], $row_products['Kategorie'], $_SESSION['user_country']);
			
			// Wenn nur Nettopreis angezeigt werden soll...
			$row_products['Preis'] = ($this->justNetto($_SESSION['user_country'])) ? $row_products['netto_price'] : $row_products['Preis'];
			$row_products['Preis_Liste'] = ($this->justNetto($_SESSION['user_country'])) ? $row_products['netto_price_liste'] : $row_products['Preis_Liste'];
			
			
			// Shop soll Netto ausgeben
			if(NETTO_SHOP==1 || $this->userNettoshop()==1)$row_products['price_ust_ex'] = $row_products['netto_price_orig'] - $row_products['netto_price'];
			
			// Welcher Prozentsatz ist enthalten?
			$row_products['product_ust'] = $this->getUst($row_products['Kategorie']);
			
			$row_products['PriceInf'] = $GLOBALS['config_vars']['Shop_icludes'] . " " . $row_products['product_ust'] . $GLOBALS['config_vars']['Shop_vat'];
			
			// Einheiten 
			if($row_products['EinheitId'] > 0)
			{
				$EinheitArray = $this->getUnits($row_products['EinheitId']);
				$row_products['Einheit'] = $EinheitArray['Einheit'];
				$row_products['EinheitMz'] = $EinheitArray['EinheitMz'];
				$row_products['EinheitOut'] = ($row_products['EinheitCount']>1) ? $EinheitArray['EinheitMz'] : $EinheitArray['Einheit'];
				
				if($row_products['EinheitCount'] != '0.00')
				{
					$row_products['EinheitPreisEinzel'] =  $row_products['Preis'] / $row_products['EinheitCount'];
					$row_products['EinheitPreisEinzelNetto'] =  $row_products['netto_price'] / $row_products['EinheitCount'];
				}
			}
			
			// Link
			$row_products['ProdLink'] = "index.php?p=shop&amp;action=showproduct&amp;id=" . $row_products['Id'] . "&amp;cid=" . $row_products['Kategorie'] . "&amp;pname=" . $this->get_clean_name($row_products['Titel']);
			
			// Verfuegbarkeit
			$row_products['VIcon'] = $this->getAvIcon($row_products['Bestellt'],$row_products['Lagerbestand'], $row_products['Verfuegbar']);
			$row_products['Beschreibung'] = strip_tags($row_products['Beschreibung'],'<br><br />');
			$row_products['man'] = $this->getManufacturerById($row_products['Hersteller']);
			
			array_push($Products, $row_products);
		}
		
		if($num > $limit && $shop_start != 1)
		{
			$shop_q = (isset($_REQUEST['shop_q']) && !empty($_REQUEST['shop_q'])) ? "shop_q=$_REQUEST[shop_q]&amp;" : "";
			if(isset($_REQUEST['shop_q']) && empty($_REQUEST['shop_q'])) $shop_q = "shop_q=empty&amp;";
			$shop_man = (isset($_REQUEST['man']) && $_REQUEST['man']!='') ? "man=$_REQUEST[man]&amp;" : "";

			$nav_limit = $this->_limit = (isset($_REQUEST['limit']) && !empty($_REQUEST['limit'])) ? '&amp;limit=' . $_REQUEST['limit'] : '&amp;limit=' . $this->_limit;
			$nav_s = (isset($_REQUEST['s']) && $_REQUEST['s']==1) ? 's=1&amp;' : '';
			$GLOBALS['tmpl']->assign('pages_inf', 'Seite ' . aktpage() . '/' . $seiten);
			$GLOBALS['tmpl']->assign('pages', pagenav($seiten, '', "<a class=\"page_navigation\" href=\"index.php?{$nav_s}{$shop_q}{$shop_man}p=shop&amp;action=showproducts&amp;cid=$_REQUEST[cid]&amp;page={s}{$nav_limit}{$Price_n}{$na_sort}{$is_offers}{$is_topseller}{$is_new}{$is_lowamount}\">{t}</a>"));
		}
		
		$this->_colums_offers = (!$this->_colums_offers) ? 3 : $this->_colums_offers;
		$this->_topseller_colums = (!$this->_topseller_colums) ? 3 : $this->_topseller_colums;
		$this->_newest_colums = (!$this->_newest_colums) ? 3 : $this->_newest_colums;
		
		$GLOBALS['tmpl']->assign('maxlength_prodtext', $this->_maxlength_prodtext);
		$GLOBALS['tmpl']->assign('colums_offers', $this->_colums_offers);
		$GLOBALS['tmpl']->assign('colums_width_offers', numround(100/$this->_colums_offers));
		$GLOBALS['tmpl']->assign('colums_topseller', $this->_topseller_colums);
		$GLOBALS['tmpl']->assign('colums_width_topseller', numround(100/$this->_topseller_colums));
		$GLOBALS['tmpl']->assign('colums', $this->_colums);
		$GLOBALS['tmpl']->assign('newest_colums', $this->_newest_colums);
		$GLOBALS['tmpl']->assign('colums_width', (($shop_start==1) ?  numround(100/$this->_newest_colums,4) : numround(100/$this->_colums,4)));
		$GLOBALS['tmpl']->assign('price_onlynetto', ($this->justNetto($_SESSION['user_country']) ? 1 : 0) );
		$GLOBALS['tmpl']->assign('no_nettodisplay', ($this->noNettoDisplay($_SESSION['user_country']) ? 1 : 0) );
		
		if(/*$no_colums==1 &&*/ isset($_REQUEST['cid']) && !empty($_REQUEST['cid']))
		{ 
			$GLOBALS['tmpl']->assign('sub_categs', $this->getSubCategs($_REQUEST['cid']));
		}
	 	return $Products;
	}
	
	function getCategName($categ)
	{
		$Lc = $_SESSION['Langcode'];
		$res = $GLOBALS['db']->RowQuery("SELECT Name_{$Lc} AS Name FROM " . PREFIX . "_shop_kategorie WHERE Id = '" . $categ . "'");
		return $res->Name;
	}
	
	function get_child_items($cid)
	{
		$subs = array();
		if(isset($cid) && !empty($cid))
		{	
			$r_subs = $GLOBALS['db']->Query("SELECT Id FROM " . PREFIX . "_shop_kategorie WHERE Parent_Id = '" . $cid . "'");
			if($r_subs->numrows())
			{
				while($row_subs = $r_subs->fetchrow())
				{
					array_push($subs,$row_subs);
					$r_subs2 = $GLOBALS['db']->Query("SELECT Id FROM " . PREFIX . "_shop_kategorie WHERE Parent_Id = '" . $row_subs->Id . "'");
					if($r_subs2->numrows())
					{
						while($row_subs2 = $r_subs2->fetchrow())
						{
							array_push($subs,$row_subs2);
							$r_subs3 = $GLOBALS['db']->Query("SELECT Id FROM " . PREFIX . "_shop_kategorie WHERE Parent_Id = '" . $row_subs2->Id . "'");
							if($r_subs3->numrows())
							{
								while($row_subs3 = $r_subs3->fetchrow())
								{
									array_push($subs,$row_subs3);
									$r_subs4 = $GLOBALS['db']->Query("SELECT Id FROM " . PREFIX . "_shop_kategorie WHERE Parent_Id = '" . $row_subs3->Id . "'");
									if($r_subs4->numrows())
									{
										while($row_subs4 = $r_subs4->fetchrow())
										{
											array_push($subs,$row_subs4);
										}
									}
								}
							}
						}
					}
				}
			}
		}
		
		foreach($subs as $sin)
		{
			$search_in[] = $sin->Id;
		}
		if(!empty($search_in))
		{
			return 'OR Kategorie = ' . implode(' OR Kategorie = ', $search_in);
		} else {
			return '';
		}
	}
	
	function get_clean_name($var)
	{
		$var = strtolower($var);
		$var = str_replace(array('ü','&uuml;'),'ue',$var);
		$var = str_replace(array('ö','&ouml;'),'oe',$var);
		$var = str_replace(array('ä','&auml;'),'ae',$var);
		$var = str_replace(array('ß','&szlig;'),'ss',$var);
		$var = eregi_replace('[^A-Za-zÀ-ÖØ-öø-ÿ0-9]', '-', $var);
		$var = str_replace(array('--','---'),'-',$var);
		return $var;
	}

	// Einheiten
	function getUnits($id)
	{
		$Units = $GLOBALS['db']->ArrQuery("SELECT Titel_" . $_SESSION['Langcode'] . " as Einheit, Mz_" . $_SESSION['Langcode'] . " as EinheitMz FROM " . PREFIX . "_shop_einheiten WHERE Id = '$id'");
		return $Units;
	}
	
	// Produktvergleich
	function mergeProduct($id, $red, $cid, $delc=0)
	{
		if(isset($_REQUEST['delproduct']) && $_REQUEST['delproduct'] != '')
		{
			unset($_SESSION['prod'][$_REQUEST['delproduct']]);
			$id = 0;
		} else {
			if($id!=0)
			{
				$_SESSION['cid'][$cid] = $cid;
				$_SESSION['prod'][$id] = $id . '_' . $cid;
			}
		}
		if(isset($_REQUEST['redir']) && $_REQUEST['redir'] == 1)
		{
			$redir = str_replace('http://','https://',redir());
			$redir = str_replace('redir=1', 'redir=0', redir());
			$redir = str_replace('&amp;', '&', $redir);
			header('Location:' . $redir . '&categ=' . $cid);
			#refer($redir . '&categ=' . $cid);
			exit;
		}
		
		$cats = array();
		if(isset($_SESSION['cid']))
		{
			foreach($_SESSION['cid'] as $category)
			{
				$sql = $GLOBALS['db']->Query("SELECT Id, Name_1 as KatDefault, Name_" . $_SESSION['Langcode'] . " as CatName FROM " . PREFIX . "_shop_kategorie WHERE Id = '$category'");
				while($row = $sql->fetchrow())
				{
					if(!$row->CatName) $row->CatName = $row->KatDefault;
					array_push($cats, $row);
				}
			}
			
			$productsC = array();
			$count = 1;
			foreach($_SESSION['prod'] as $prod)
			{
				$prod = explode('_', $prod);
				
				if($count==1)
				{
					$catid = $prod[1];
					
				}
				$count++;
	
				if(isset($_REQUEST['categ']) && $_REQUEST['categ'] != '')
				{
					$catid = $_REQUEST['categ'];
					
					// Ausfuehrliche Details
					$LC = $_SESSION['Langcode'];
					if($LC != 1)
					{
						$q_l = "
							Spez_1_$LC AS Spez_1,
							Spez_2_$LC AS Spez_2,
							Spez_3_$LC AS Spez_3,
							Spez_4_$LC AS Spez_4,
							Spez_5_$LC AS Spez_5,
							Spez_6_$LC AS Spez_6,
							Spez_7_$LC AS Spez_7,
							Spez_8_$LC AS Spez_8,
							Spez_9_$LC AS Spez_9,
							Spez_10_$LC AS Spez_10,
							Spez_11_$LC AS Spez_11,
							Spez_12_$LC AS Spez_12,
							Spez_13_$LC AS Spez_13,
							Spez_14_$LC AS Spez_14,
							Spez_15_$LC AS Spez_15 
							";
					} else {
						$q_l = "*";
					}
					$det_spez = $GLOBALS['db']->ArrQuery("SELECT $q_l FROM " . PREFIX . "_shop_kategorie_spezifikation WHERE Kategorie = '" . $catid . "'");
					$GLOBALS['tmpl']->assign('det_spez', $det_spez);
				
					if($catid==$prod[1])
					{
						
						$row = $this->displayProduct(1,$prod[0],1);
						array_push($productsC, $row);
					}
					
				} else {
					if($catid==$prod[1])
					{
						$row = $this->displayProduct(1,$prod[0],0);
						array_push($productsC, $row);
					}
				}
			}
			
		}
		if (empty($productsC) && $delc != 1)
		{
			
			unset($_SESSION['cid'][$_REQUEST['categ']]);
			unset($cats['CatName']);
			unset($cats['Id']);
			$this->mergeProduct(0,0,0,1);
		}
		
		$GLOBALS['tmpl']->assign('merged', @$productsC);
		$GLOBALS['tmpl']->assign('cats', @$cats);
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/product_merge_popup.tpl'));
	}
	
	
	//=================================================================
	// Verfuegbarkeiten-Fenster
	//=================================================================
	/*
	function availableWindow($id)
	{
		$icons = array();
		$sql = $GLOBALS['db']->Query("SELECT Id,Bild, Titel_" . $_SESSION['Langcode'] ." as Titel FROM " . PREFIX . "_shop_verfuegbarkeit ORDER BY Position ASC");
		while($row = $sql->fetcharray())
		{	
			array_push($icons, $row);
		}
		
		$GLOBALS['tmpl']->assign('pagetitle_html', $GLOBALS['config_vars']['Shop_availabilities']);
		$GLOBALS['tmpl']->assign('icons', $icons);
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/available_popup.tpl'));
	}
	*/
	
	//=================================================================
	// Detailbilder (Popup)
	//=================================================================
	function browseImages($id)
	{
		$Bilder_Klein = '';
		$row_products = $GLOBALS['db']->ArrQuery("SELECT Bild, Bilder, Titel_" . $_SESSION['Langcode'] ." as Titel FROM " . PREFIX . "_shop_produkte WHERE Id = '$id'");
		$prod_image= (is_file(BASE_DIR . '/' . $this->_upload_path . 'big/' . $row_products['Bild'])) ? $this->_upload_path . 'big/' . $row_products['Bild'] : 'system/shopthumb.php?smode=1&amp;img=' . $row_products['Bild'];
		
		if($row_products['Bilder'] != '')
		{ 
			$Bilder_Klein = array();
			$bilder = explode('|', $row_products['Bilder']);
			$bilder[] .= $row_products['Bild'];
			
			foreach($bilder as $bild)
			{
				
				$arr['Bild'] = (is_file(BASE_DIR . '/' . $this->_upload_path . 'medium/' . $bild)) ? $this->_upload_path . 'medium/' . $bild : 'system/shopthumb.php?smode=4&amp;img=' . $bild;
				$arr['Bild_Normal'] = (is_file(BASE_DIR . '/' . $this->_upload_path . 'big/' . $bild)) ? $this->_upload_path . 'big/' . $bild : 'system/shopthumb.php?smode=1&amp;img=' . $bild;
				array_push($Bilder_Klein, $arr);
			}
			$GLOBALS['tmpl']->assign('images', $Bilder_Klein);
		}
		
		$GLOBALS['tmpl']->assign('pagetitle_html', $row_products['Titel']);
		$GLOBALS['tmpl']->assign('prod_image', $prod_image);
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/product_images_popup.tpl'));
	}
	
	function ShippingCost()
	{
		$GLOBALS['tmpl']->assign('prod_image', $prod_image);
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/shipping_cost.tpl'));
	}
	
	function getRabatt($price,$val)
	{
		$rabatt = number_format($val,2,'.','');
		$price = $price - ($price / 100 * $rabatt);
		$price = number_format($price ,3, '.' ,'');
		return $price;
	}
	
	//=================================================================
	// Pruefen, ob fuer Land nur Netto angezeigt werden soll
	//=================================================================
	function justNetto($country)
	{
		// Neues Land (etwaiges Lieferland beruecksichtigen)
		if(isset($_SESSION['r_land']) && !empty($_SESSION['r_land'])) $country =  $_SESSION['r_land'];
		
		$row_st = $GLOBALS['db']->RowQuery("SELECT Ust FROM " . PREFIX . "_laender WHERE Code = '" . strtoupper($country) . "'");
		$row_ugst = $GLOBALS['db']->RowQuery("SELECT VatByCountry FROM " . PREFIX . "_benutzer_gruppen WHERE Id = '" . $_SESSION['user_group'] . "'");
		if(($row_st->Ust != 1 && $row_ugst->VatByCountry=='1') || (NETTO_SHOP==1 && $row_ugst->VatByCountry=='1')  || ($this->userNettoshop()==1)) return true;
		return false;
	}
	
	function noNettoDisplay($country)
	{
		// Neues Land (etwaiges Lieferland beruecksichtigen)
		if(isset($_SESSION['r_land']) && !empty($_SESSION['r_land'])) $country =  $_SESSION['r_land'];
		
		$row_st = $GLOBALS['db']->RowQuery("SELECT Ust FROM " . PREFIX . "_laender WHERE Code = '" . strtoupper($country) . "'");
		$row_ugst = $GLOBALS['db']->RowQuery("SELECT VatByCountry FROM " . PREFIX . "_benutzer_gruppen WHERE Id = '" . $_SESSION['user_group'] . "'");
		if($row_st->Ust != 1 && $row_ugst->VatByCountry=='1') return true;
		return false;
	}
	
	//=================================================================
	// Der Steuersatz fuer ein Produkt.
	// Hinweis: Steuersatz-Id wird aus der Kategorie ausgelesen!
	//=================================================================
	function getUst($category)
	{
		$row_zone = $GLOBALS['db']->RowQuery("SELECT UstId FROM " . PREFIX . "_shop_kategorie WHERE Id = '$category'");
		if(is_object($row_zone)) 
		{
			$row_zone = $GLOBALS['db']->RowQuery("SELECT Wert FROM " . PREFIX . "_shop_ustzone WHERE Id = '$row_zone->UstId'");
			return $row_zone->Wert;
		} else {
			$_REQUEST['id'] = '';
		}
		
	}
	
	//=================================================================
	// Nettopreis auslesen
	//=================================================================
	function getNettoPrice($price,$category='', $country='')
	{
		$ust_string_f = '';
		
		$row_zone = $GLOBALS['db']->RowQuery("SELECT UstId FROM " . PREFIX . "_shop_kategorie WHERE Id = '$category'");
		if(is_object($row_zone)) 
		{
			$row_zone = $GLOBALS['db']->RowQuery("SELECT Wert FROM " . PREFIX . "_shop_ustzone WHERE Id = '$row_zone->UstId'");
			$ust_val = $row_zone->Wert;
		} else {
			$_REQUEST['id'] = '';
		}
			$u_country = (empty($country)) ? $_SESSION['user_country'] : trim(strtolower($country));
		
		$row_st = $GLOBALS['db']->RowQuery("SELECT Ust FROM " . PREFIX . "_laender WHERE Code = '" . strtoupper($country) . "'");
		//$row_ugst = $GLOBALS['db']->RowQuery("SELECT Vat FROM " . PREFIX . "_benutzer_gruppen WHERE Id = '" . $_SESSION['user_group'] . "'");
		// MUSS STEUERN ZAHLEN
		if($row_st->Ust == 1)
		{
			if(!empty($ust_val))
			{
				$ust_string = number_format($ust_val,2,'.','');
				if($ust_string<10)
				{
					$ust_string = str_replace('.','',$ust_string);
					$ust_string_f = '1.0' . $ust_string;
				} else {
					$ust_string = str_replace('.','',$ust_string);
					$ust_string_f = '1.' . $ust_string;
					
				}
				$price = $price / $ust_string_f;
			}
			$price = number_format($price ,3, '.' ,'');
		} else {
			// KEINE STEUERN
			if(!empty($ust_val))
			{
				$ust_string = number_format($ust_val,2,'.','');
				if($ust_string<10)
				{
					$ust_string = str_replace('.','',$ust_string);
					$ust_string_f = '1.0' . $ust_string;
				} else {
					$ust_string = str_replace('.','',$ust_string);
					$ust_string_f = '1.' . $ust_string;
					
				}
				$price = $price / $ust_string_f;
			}
			$price = number_format($price ,3, '.' ,'');
		}
		return $price;
	}
	
	
	//=================================================================
	// Aus dem Warenkorb entfernen
	//=================================================================
	function deleteItem($item,$mylist=0)
	{
		$vars = '';
		$sess_where = ($mylist==1) ? 'products_mylist' : 'products';
		// Eventuelle Varianten
		if(isset($_POST['mod']) && !empty($_POST['mod']))
		{
			$mods = implode(',', $_POST['mod']);
			$delitem = $item . '||' . $mods;
			unset($_SESSION[$sess_where][$delitem]);
		} else {
			unset($_SESSION[$sess_where][$item]);
		}
		
		if($mylist == 1)
		{
			refer("index.php?p=shop&action=mylist");
		} else {
			if(isset($_SESSION['coupon_code']) && $_SESSION['coupon_code']!='' && isset($_SESSION['coupon_val']) && $_SESSION['coupon_val']!='')
			{
				$this->initBasket();
				
				$row_c = $GLOBALS['db']->RowQuery("SELECT * FROM " . PREFIX . "_shop_gutscheine WHERE Code = '". $_SESSION['coupon_code']."'");
				if(is_object($row_c))
				{
					if($row_c->MinBestellwert >= numf($_SESSION['price_netto']))
					{
						unset($_SESSION['coupon_code']);
						unset($_SESSION['coupon_id']);
						unset($_SESSION['coupon_val']);
						unset($_SESSION['coupon_typ']);
					}
				}			
			}
			refer("index.php?p=shop&action=showbasket");
		}
		exit;
	}
	
	function newList()
	{
		unset($_SESSION['products_mylist']);
		refer("index.php?p=shop&action=mylist");
		exit;
	}
	
	//=================================================================
	// In den Warenkorb legen
	//=================================================================
	function addToCart($mylist=0,$ajax=0)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==1) $ajax=1;
		
		$vars = '';
		$tovar = ($mylist==1 || (isset($_POST['mylist']) && $_POST['mylist']==1) ) ? 'products_mylist' : 'products';
		$_POST['amount'] = ( isset($_POST['amount']) && !empty($_POST['amount']) && is_numeric($_POST['amount']) ) ? cleanInt($_POST['amount']) : 1;
		$_POST['product_id'] = cleanInt($_POST['product_id']);
		
		// TODO: PRUEFEN OB ARTIKEL EXISIERT UND OB ER ABGELEGT WERDEN KANN!!!
		$check = $GLOBALS['db']->RowQuery("SELECT Fsk18,Verfuegbar,EinzelBestellung,Lagerbestand,MaxBestellung,MinBestellung FROM " . PREFIX . "_shop_produkte WHERE Id = '" . $_POST['product_id'] . "'");
		$fsk_ok = (@$check->Fsk18 == '1' && FSK_USER != '1') ? false : true;
		
		if((is_object($check) && $check->Lagerbestand >= 1 || ($check->Verfuegbar==4)) && ($fsk_ok))
		{
			$amount = $_POST['amount'];
				
			if($_POST['amount'] > $check->MaxBestellung && ($check->MaxBestellung!=0)) $_POST['amount'] = $check->MaxBestellung;
			if($_POST['amount'] < $check->MinBestellung && ($check->MinBestellung!=0)) $_POST['amount'] = $check->MinBestellung;
			if($_POST['amount'] > $check->Lagerbestand) $_POST['amount'] = $check->Lagerbestand;
			if($check->Verfuegbar == 4) $_POST['amount'] = $amount;
			if($check->EinzelBestellung == 1) $_POST['amount'] = 1;
			
			
			// Eventuelle Varianten
			if(isset($_POST['mod']) && !empty($_POST['mod']))
			{
				foreach($_POST['mod'] as $x)
				{
					if(!empty($x)) $vars[] = $x;
				}
				
				// Wenn Varianten nicht leer sind anhaengen
				if(!empty($vars)) 
				{
					$_SESSION[$tovar][$_POST['product_id'] . '||' . implode(',',$vars)] = $_POST['amount'];
				} else {
					$_SESSION[$tovar][$_POST['product_id']] = $_POST['amount'];
				}
			} else {
				// Keine Varianten
				$_SESSION[$tovar][$_POST['product_id']] = $_POST['amount'];
			}
		}
		
		if(isset($_REQUEST['mylist']) && $_REQUEST['mylist']==1) $mylist=1;
		
		if($ajax == 1/* && $mylist!=1*/)
		{
			$this->initBasket();
			$out = $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/basket_small_raw.tpl');
			echo $out;
			exit;
		} else {
			if(isset($_SESSION['coupon_code']) && $_SESSION['coupon_code']!='' && isset($_SESSION['coupon_val']) && $_SESSION['coupon_val']!='')
			{
				$this->initBasket();
				
				$row_c = $GLOBALS['db']->RowQuery("SELECT * FROM " . PREFIX . "_shop_gutscheine WHERE Code = '". $_SESSION['coupon_code']."'");
				if(is_object($row_c))
				{
					if($row_c->MinBestellwert >= numf($_SESSION['price_netto']))
					{
						unset($_SESSION['coupon_code']);
						unset($_SESSION['coupon_id']);
						unset($_SESSION['coupon_val']);
						unset($_SESSION['coupon_typ']);
					}
				}			
			}
			
			refer("index.php?p=shop&action=showbasket");
			exit;
		}
	}
	
	//=================================================================
	// Funktion Laender auslesen
	//=================================================================
	function getCountries()
	{
		$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_laender WHERE Aktiv=1 ORDER BY Name ASC");
		while($row = $sql->fetcharray())
		{
			$row['Code'] = strtolower($row['Code']);
			$laender[] = $row;
		}
		return $laender;		
	}
	
	
	function checkFormData($what)
	{
		$muster_email = "/^[ -._A-Za-zÀ-ÖØ-öø-ÿ0-9-]+(\.[_A-Za-zÀ-ÖØ-öø-ÿ0-9-]+)*@([a-zA-Z0-9-]+\.)+([a-zA-Z]{2,4})$/";
		$muster_standard = "/[^ \/._A-Za-zÀ-ÖØ-öø-ÿ0-9-]/";
		
		switch($what)
		{
			case 'guestorder':
			case 'user':
			
				$error = '';
				$prefix = $GLOBALS['config_vars']['Shop_billingPrefix'];
				if(empty($_POST['r_email'])) $error[] = $prefix . $GLOBALS['config_vars']['Shop_check_email'];
				if(@!preg_match($muster_email, $_POST['r_email']))  $error[] = $prefix . $GLOBALS['config_vars']['Shop_check_email'];		
				if(empty($_POST['r_vorname']) || @preg_match($muster_standard, $_POST['r_vorname']))  $error[] = $prefix . $GLOBALS['config_vars']['Shop_check_firstname'];
				if(empty($_POST['r_nachname']) || @preg_match($muster_standard, $_POST['r_nachname']))  $error[] = $prefix . $GLOBALS['config_vars']['Shop_check_lastname'];
				if(empty($_POST['r_strasse']) || @preg_match($muster_standard, $_POST['r_strasse']))  $error[] = $prefix . $GLOBALS['config_vars']['Shop_check_street'];
				if(empty($_POST['r_plz']) || @preg_match($muster_standard, $_POST['r_plz']))  $error[] = $prefix . $GLOBALS['config_vars']['Shop_check_zip'];
				if(empty($_POST['r_ort']) || @preg_match($muster_standard, $_POST['r_ort']))  $error[] = $prefix . $GLOBALS['config_vars']['Shop_check_town'];
				if(!empty($_POST['r_firma']) && @preg_match($muster_standard, $_POST['r_firma']))  $error[] = $prefix . $GLOBALS['config_vars']['Shop_check_company'];
				if(!empty($_POST['r_ustid']) && @preg_match($muster_standard, $_POST['r_ustid']))  $error[] = $prefix . $GLOBALS['config_vars']['Shop_check_ustid'];
				if(!empty($_POST['r_telefon']) && @preg_match($muster_standard, $_POST['r_telefon']))  $error[] = $prefix . $GLOBALS['config_vars']['Shop_check_fon'];
				if(!empty($_POST['r_fax']) && @preg_match($muster_standard, $_POST['r_fax']))  $error[] = $prefix . $GLOBALS['config_vars']['Shop_check_fax'];
				
				
				
				switch($_REQUEST['r_land'])
				{	
					case 'DE':
						if(!empty($_POST['r_plz']) && !preg_match ("/^[0-9]{".$this->deZip."}$/",$_POST['r_plz'])) $error[] = $prefix . $GLOBALS['config_vars']['Profile_WrongZip'];
					break;
					
					case 'FR':
						if(!empty($_POST['r_plz']) && !preg_match ("/^[0-9]{".$this->frZip."}$/",$_POST['r_plz'])) $error[] = $prefix . $GLOBALS['config_vars']['Profile_WrongZip'];
					break;
					
					case 'CH':
						if(!empty($_POST['r_plz']) && !preg_match ("/^[0-9]{".$this->chZip."}$/",$_POST['r_plz'])) $error[] = $prefix . $GLOBALS['config_vars']['Profile_WrongZip'];
					break;
					
					case 'AT':
						if(!empty($_POST['r_plz']) && !preg_match ("/^[0-9]{".$this->atZip."}$/",$_POST['r_plz'])) $error[] = $prefix . $GLOBALS['config_vars']['Profile_WrongZip'];
					break;
					
					case 'IT':
						if(!empty($_POST['r_plz']) && !preg_match ("/^[0-9]{".$this->itZip."}$/",$_POST['r_plz'])) $error[] = $prefix . $GLOBALS['config_vars']['Profile_WrongZip'];
					break;
				}
			
				if(isset($_POST['diff_rl']) && !empty($_POST['diff_rl']))
				{
					$_SESSION['diff_rl'] = $_POST['diff_rl'];
					
					if($_POST['diff_rl'] == 'liefer_andere')
					{
						$prefix = $GLOBALS['config_vars']['Shop_shippingPrefix'];
						if(empty($_POST['l_vorname']) || @preg_match($muster_standard, $_POST['l_vorname']))  $error[] = $prefix . $GLOBALS['config_vars']['Shop_check_firstname'];
						if(empty($_POST['l_nachname']) || @preg_match($muster_standard, $_POST['l_nachname']))  $error[] = $prefix . $GLOBALS['config_vars']['Shop_check_lastname'];
						if(empty($_POST['l_strasse']) || @preg_match($muster_standard, $_POST['l_strasse']))  $error[] = $prefix . $GLOBALS['config_vars']['Shop_check_street'];
						if(empty($_POST['l_plz']) || @preg_match($muster_standard, $_POST['l_plz']))  $error[] = $prefix . $GLOBALS['config_vars']['Shop_check_zip'];
						if(empty($_POST['l_ort']) || @preg_match($muster_standard, $_POST['l_ort']))  $error[] = $prefix . $GLOBALS['config_vars']['Shop_check_town'];
						if(!empty($_POST['l_telefon']) && @preg_match($muster_standard, $_POST['l_telefon']))  $error[] = $prefix . $GLOBALS['config_vars']['Shop_check_fon'];
						if(!empty($_POST['l_fax']) && @preg_match($muster_standard, $_POST['l_fax']))  $error[] = $prefix . $GLOBALS['config_vars']['Shop_check_fax'];
					}
				}
				
				if(!empty($error))
				{
					$GLOBALS['tmpl']->assign('r_errors', $error);
					
				} else {
					
					$_SESSION['step2_ok'] = 1;
					$_SESSION['r_anrede'] = @$_POST['r_anrede'];
					$_SESSION['r_email'] = $_POST['r_email'];
					$_SESSION['r_vorname'] = $_POST['r_vorname'];
					$_SESSION['r_nachname'] = $_POST['r_nachname'];
					$_SESSION['r_strasse'] = $_POST['r_strasse'];
					$_SESSION['r_plz'] = $_POST['r_plz'];
					$_SESSION['r_ort'] = $_POST['r_ort'];
					$_SESSION['r_land'] = $_POST['r_land'];
					$_SESSION['r_firma'] = @$_POST['r_firma'];
					$_SESSION['r_ustid'] = @$_POST['r_ustid'];
					$_SESSION['r_telefon'] = @$_POST['r_telefon'];
					$_SESSION['r_fax'] = @$_POST['r_fax'];
					@$_SESSION['r_nachricht'] = @htmlentities(@$_POST['r_nachricht']);
					
					if(isset($_POST['diff_rl']) && !empty($_POST['diff_rl']))
					{
						$_SESSION['l_land'] = $_POST['l_land'];
						$_SESSION['l_anrede'] = @$_POST['l_anrede'];
						$_SESSION['l_vorname'] = @$_POST['l_vorname'];
						$_SESSION['l_nachname'] = @$_POST['l_nachname'];
						$_SESSION['l_strasse'] = $_POST['l_strasse'];
						$_SESSION['l_plz'] = @$_POST['l_plz'];
						$_SESSION['l_ort'] = @$_POST['l_ort'];
						$_SESSION['l_firma'] = @$_POST['l_firma'];
						$_SESSION['l_telefon'] = @$_POST['l_telefon'];
						$_SESSION['l_fax'] = @$_POST['l_fax'];
					}
					$h2 = ($what=="guestorder") ? "&order=guest" : "";
					refer("index.php?sendform=1&p=shop&action=shoporder&subaction=step3" . $h2);
				}
			break;
		}
	}
	

	
	function orderNumber($length)
	{
		mt_srand((double)microtime()*1000000);
		$chars = "123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		$str_lng = strlen($chars)-1;
		$rand= "";
		for($i=0;$i<$length;$i++) $rand .= $chars{mt_rand(0, $str_lng)};
		return $rand;
	} 
	
	function getCountryName($id)
	{
		$rl = $GLOBALS['db']->RowQuery("SELECT Name FROM " . PREFIX . "_laender WHERE Code = '{$id}'");
		return $rl->Name;
	}
	
	function getShipperName($id)
	{
		$rl = $GLOBALS['db']->RowQuery("SELECT Name_" . $_SESSION['Langcode'] . " AS Name FROM " . PREFIX . "_shop_versandarten WHERE Id = '{$id}'");
		return $rl->Name;
	}
	
	function getPaymentName($id)
	{
		$rl = $GLOBALS['db']->RowQuery("SELECT Name_" . $_SESSION['Langcode'] . " AS Name FROM " . PREFIX . "_shop_zahlungsmethoden WHERE Id = '{$id}'");
		return $rl->Name;
	}
	
	function listPayments($shipper_id)
	{
		$country_check = (isset($_SESSION['diff_rl']) &&  $_SESSION['diff_rl']=='liefer_andere') ? $_SESSION['l_land'] : $_SESSION['r_land'];
		$payments = array();
		$sql = $GLOBALS['db']->Query("SELECT *, Beschreibung_" . $_SESSION['Langcode'] . " AS Beschreibung, Name_" . $_SESSION['Langcode'] . " AS Name FROM " . PREFIX . "_shop_zahlungsmethoden WHERE Aktiv = 1 ORDER BY Position ASC");
		while($row = $sql->fetchrow())
		{
			$Versandarten = explode(',', $row->Versandarten);
			$Laender = explode(',', strtoupper($row->Laender));
			$Gruppen = explode(',', strtoupper($row->Gruppen));
			if(in_array($shipper_id,$Versandarten) && in_array($country_check,$Laender) && in_array($_SESSION['user_group'],$Gruppen))
			{
				#$row->Kosten = ($row->KostenTyp=='pro') ? $row->Kosten : $this->GetPrice($row->Kosten);
				array_push($payments, $row);
			}
		}
		return $payments;
	}
	
	//=================================================================
	// Funktionen zur Pruefung, ob es ein Versandmethode fuer das 
	// angegebene Land gibt
	//=================================================================
	function checkShipper()
	{
		$error = true;
		$country_check = (isset($_SESSION['diff_rl']) &&  $_SESSION['diff_rl']=='liefer_andere') ? @$_SESSION['l_land'] : @$_SESSION['r_land'];
		$sql = $GLOBALS['db']->Query("SELECT Laender FROM " . PREFIX . "_shop_versandarten");
		while($row = $sql->fetchrow())
		{
			$laender =  explode(',', $row->Laender);
			if(in_array($country_check, $laender))$error = false;
		}
		if($error==false) return true;
		return false;
	}
	
	// Versandmethoden listen
	function getShipper($id=0,$free=0,$weightnull=0)
	{
		$shipper = array();
		$nullsh = ($weightnull==1) ? 'WHERE GewichtNull = 1 AND Aktiv = 1' : 'WHERE GewichtNull != 1 AND Aktiv = 1';
		$country_check = (isset($_SESSION['diff_rl']) &&  $_SESSION['diff_rl']=='liefer_andere') ? @$_SESSION['l_land'] : @$_SESSION['r_land'];
		$sql = $GLOBALS['db']->Query("SELECT Icon, Gruppen, Laender, Id, Name_" . $_SESSION['Langcode'] . " as Name, Beschreibung_" . $_SESSION['Langcode'] . " as Beschreibung  FROM " . PREFIX . "_shop_versandarten $nullsh ORDER BY Position ASC");
		$count = 0;
		while($row = $sql->fetchrow())
		{
			
			$laender = explode(',', $row->Laender);
			$groups  = explode(',', $row->Gruppen);
			if(in_array($country_check, $laender) && in_array($_SESSION['user_group'], $groups))
			{
				$count++;
				if($this->getShipperInf($row->Id,$free,$weightnull) != 'false') array_push($shipper,$row);
			}
		}
		
		if($count < 1) $GLOBALS['tmpl']->assign('shipper_found', '0');
		return $shipper;
	}
	
	// Versandmethoden-Eigenschaften
	function getShipperInf($id=0,$free=0,$weightnull=0)
	{
		if($id==0)
		{
			return 'false';
		} else {
			$weight = numf(@$_SESSION['gewicht'] / 1000);
			
			$where = ($id != 0) ? "WHERE Id = '{$id}' AND Aktiv = 1 LIMIT 1" : "WHER Aktiv = 1 ORDER BY Position ASC LIMIT 1";
			$row = $GLOBALS['db']->RowQuery("SELECT Icon, Gebuehr_Pauschal, Gruppen, Laender, Id, Name_" . $_SESSION['Langcode'] . " as Name, Beschreibung_" . $_SESSION['Langcode'] . " as Beschreibung FROM " . PREFIX . "_shop_versandarten $where");
			if(is_object($row))
			{
				$row_gebuehr = $GLOBALS['db']->RowQuery("SELECT * FROM " . PREFIX . "_shop_versandarten_volumen WHERE Von <= '{$weight}' AND Bis >= '{$weight}' AND VersandId = '{$row->Id}'");
				if(VERSAND_FREIBETRAG > '0.00' && $_SESSION['price'] >= VERSAND_FREIBETRAG)
				{
					$row_gebuehr->Gebuehr = '0.00';
					$row->Gebuehr_Pauschal = '0.00';
					unset($_SESSION['shipping_summ']);
				}
			}
			if(is_object($row) && is_object($row_gebuehr))
			{ 
				if($row->Gebuehr_Pauschal >= '0.01' || $weight < '0.01')
				{
					$row->Gebuehr = ($weight < '0.01') ? '0.00' : $row->Gebuehr_Pauschal;
					return $row;
				} else {
					if($free==1)
					{
						return true;
					} else {
						if(is_object($row_gebuehr))
						{
							$row->Gebuehr = $row_gebuehr->Gebuehr;
							return $row;
						} else {
						
							return 'false';
						}
					}
				}
			} elseif(is_object($row) && !is_object($row_gebuehr)) {
				if($weight > '0.00') return 'false';
				return $row;
			} else {
				return 'false';
			}
		}
	}
	//
	
	//=================================================================
	// Setzt den Nettoshop (B2B, wenn Usergruppe das zulaesst)
	//=================================================================
	function userNettoshop()
	{
		$row_uns = $GLOBALS['db']->RowQuery("SELECT ShopAnzeige FROM " . PREFIX . "_benutzer_gruppen WHERE Id = '" . $_SESSION['user_group'] . "'");
		if($row_uns->ShopAnzeige=='b2b') return 1;
	}
	
	//=================================================================
	// Warenkorb aufrufen
	//=================================================================
	function showBasket()
	{
		unset($_SESSION['no_shipping']);
		$_SESSION['shopstep'] = '';
		$_SESSION['step2_ok'] = '';
		$_SESSION['step3_ok'] = '';
		$_SESSION['step4_ok'] = '';
		
		if(isset($_REQUEST['del']) && $_REQUEST['del'] == 'coupon')
		{
			unset($_SESSION['coupon_code']);
    		unset($_SESSION['coupon_id']);
    		unset($_SESSION['coupon_val']);
    		unset($_SESSION['coupon_typ']);
			refer("index.php?p=shop&action=showbasket");
			exit;
		}
		
		$GLOBALS['tmpl']->assign('headernav', "<a href=\"index.php?p=shop\">" . $GLOBALS['config_vars']['Shop'] . "</a>" . @$GLOBALS['config_vars']['PageSep'] . @$GLOBALS['config_vars']['Shop_step_1']);
		$GLOBALS['tmpl']->assign('pagetitle_html', $GLOBALS['config_vars']['Shop'] . @$GLOBALS['config_vars']['PageSep'] . @$GLOBALS['config_vars']['Shop_step_1']);
		
		$GLOBALS['tmpl']->assign('product_array', $this->initBasket(1));
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/basket.tpl'));
	}
	
	
	function loadMyLists()
	{
		$lists = array();
		$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_merkzettel WHERE Benutzer = '" . $_SESSION['benutzer_id'] . "' ORDER BY Name ASC");
		while($row = $sql->fetchrow())
		{
			array_push($lists,$row);
		}
		return $lists;
	}
	//=================================================================
	// Merkzettel
	//=================================================================
	function showMyList()
	{
		// Speichern
		
		if($_SESSION['user_group'] != 2 && isset($_REQUEST['subaction']) && $_REQUEST['subaction'] == 'save_list' && isset($_SESSION['products_mylist']) && !empty($_SESSION['products_mylist']))
		{
			$Zettel = serialize($_SESSION['products_mylist']);
			$_POST['Name_Merkzettel'] = (isset($_POST['Name_Merkzettel']) && !empty($_POST['Name_Merkzettel'])) ? $_POST['Name_Merkzettel'] : 'Undefined';
			$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_shop_merkzettel (Id,Benutzer,Name,Datum,Inhalt) VALUES ('','" . $_SESSION['benutzer_id'] . "', '" . escs($_POST['Name_Merkzettel']). "','" . time() . "', '$Zettel')");
		}
		
		if($_SESSION['user_group'] != 2)
		{
			if(isset($_REQUEST['subaction']) && $_REQUEST['subaction'] == 'load_list' && isset($_REQUEST['id']) && !empty($_REQUEST['id']))
			{
				$load_id = cleanInt($_REQUEST['id']);
				$row_mz = $GLOBALS['db']->RowQuery("SELECT Inhalt FROM " . PREFIX . "_shop_merkzettel WHERE Id = '$load_id' AND Benutzer = '" . $_SESSION['benutzer_id'] . "'");
				if(is_object($row_mz)) $_SESSION['products_mylist'] = unserialize($row_mz->Inhalt);
			}
			
			if(isset($_REQUEST['subaction']) && $_REQUEST['subaction'] == 'del_list' && isset($_REQUEST['id']) && !empty($_REQUEST['id']))
			{
				$del_id = cleanInt($_REQUEST['id']);
				$GLOBALS['db']->RowQuery("DELETE FROM " . PREFIX . "_shop_merkzettel WHERE Id = '$del_id' AND Benutzer = '" . $_SESSION['benutzer_id'] . "'");
			}
			
			$GLOBALS['tmpl']->assign('myLists', $this->loadMyLists());
		}
		
		$GLOBALS['tmpl']->assign('headernav', '<a href="index.php?p=shop">' . $GLOBALS['config_vars']['Shop'] . '</a>' .  $GLOBALS['config_vars']['PageSep'] . $GLOBALS['config_vars']['Shop_mylist']);
		$GLOBALS['tmpl']->assign('pagetitle_html', $GLOBALS['config_vars']['Shop'] . $GLOBALS['config_vars']['PageSep'] . $GLOBALS['config_vars']['Shop_mylist']);
		
		$GLOBALS['tmpl']->assign('product_array', $this->initBasket(1,'wishlist'));
		
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/mylist.tpl'));
	}
	
	//=================================================================
	// Warenkorb
	//=================================================================
	function initBasket($page=0,$mylist='',$ajax_out=0)
	{
		$_SESSION['shipping_summ'] = '';
		$_SESSION['payment_summ_extra'] = '';
		if(!isset($_SESSION['price_netto_coupon'])) $_SESSION['price_netto_coupon'] = '';
		if(isset($_REQUEST['action']) && $_REQUEST['action']=='showbasket')
		{
			if(isset($_SESSION['payment_id'])) unset($_SESSION['payment_id']);
			if(isset($_SESSION['shipper_id'])) unset($_SESSION['shipper_id']);
		}
		
		#print_r($_SESSION);
		#exit;
		
		$GLOBALS['tmpl']->assign('show_vat_table', 0);
		
		if(!$this->noNettoDisplay($_SESSION['user_country']))
		{
			$GLOBALS['tmpl']->assign('show_vat_table', 1);
		}
		
		$weight_parts = '';
		$weight = '';
		$All = '';
		$Price = '';
		$NettoPrice = '';
		$price_end = '';
		$var_array = null;
		$sup_price_end = '';
		$dip = 'netto';
		$Price_brutto = '';
		
		// Eventuelle USt-Sessions loeschen
		$sql = $GLOBALS['db']->Query("SELECT Wert FROM " . PREFIX . "_shop_ustzone ORDER BY Wert ASC");
		while($row = $sql->fetchrow()) if(isset($_SESSION[$row->Wert])) unset($_SESSION[$row->Wert]);
		
		
		// Produkte listen
		$sess_what = ($mylist=='wishlist') ? 'products_mylist' : 'products';
		if(isset($_SESSION[$sess_what]) && !empty($_SESSION[$sess_what]))
		{
			$arr = $_SESSION[$sess_what];
			reset ($arr);
			
			$product_array = array();
			while (list($key, $value) = each ($arr))
			{
				$var_array = null;
				$Select = ($page==1) ? "*,Preis_Liste_Gueltig,Preis_Liste,Gewicht, Titel_" . $_SESSION['Langcode'] ." as Titel, Beschreibung_" . $_SESSION['Langcode'] ." as Beschreibung" : "Preis_Liste_Gueltig,Titel_" . $_SESSION['Langcode'] ." as Titel,Preis_Liste,Gewicht, Kategorie, Bild, Id, Preis, Kategorie";
				$part = explode('||',$key);
				$row_p = $GLOBALS['db']->RowQuery("SELECT {$Select} FROM " . PREFIX . "_shop_produkte WHERE Id = '$part[0]'");
				
				if(is_object($row_p))
				{
					// Gueltigkeit eines Preises
					if(is_object($row_p) && (($row_p->Preis_Liste>$row_p->Preis) && ($row_p->Preis_Liste>0) &&  ($row_p->Preis_Liste_Gueltig == 0) || (($row_p->Preis_Liste>$row_p->Preis) && $row_p->Preis_Liste_Gueltig != 0 && $row_p->Preis_Liste_Gueltig < stime())))
					{
						$row_p->Preis = $row_p->Preis_Liste;
					} 
					
					// Neuer Preis (Preisstaffelung)
					if($value>1)
					{
						$row_psta = $GLOBALS['db']->RowQuery("SELECT Prozent FROM " . PREFIX . "_shop_staffelpreise WHERE ArtikelId = '$part[0]' AND Von <= $value AND Bis >= $value");
						if(is_object($row_psta) && !empty($row_psta))
						{
							$row_p->Preis = $row_p->Preis - ($row_p->Preis / 100 * $row_psta->Prozent); //$row_psta->PreisNeu;
						} else {
						
							$row_psta = $GLOBALS['db']->RowQuery("SELECT Prozent,Bis FROM " . PREFIX . "_shop_staffelpreise WHERE ArtikelId = '$part[0]' ORDER BY Bis DESC LIMIT 1");
							if(is_object($row_psta) && !empty($row_psta) && $value>=$row_psta->Bis) $row_p->Preis = $row_p->Preis - ($row_p->Preis / 100 * $row_psta->Prozent); //$row_psta->PreisNeu;
						}
					}
					
					// Nettopreise (Egal ob Nettoshop - Dient nur der Orientierung im Korb)
					$row_p->NPreis = $this->getPrice($row_p->Preis);
					$row_p->NPreisNetto = $this->getNettoPrice($row_p->NPreis, $row_p->Kategorie, $_SESSION['user_country']);
					$row_p->Preis = $this->getNettoPrice($this->getPrice($row_p->Preis), $row_p->Kategorie, $_SESSION['user_country']);
					
					
					if(!empty($part[1])) 
					{
						$var_search =  explode(',', $part[1]);
						// Anzahl des Artikel
						$row_p->Anzahl = $_SESSION[$sess_what][$part[0] . '||' . $part[1]];
						
						// Varianten
						$row_p->Varianten = $var_search;
						
						$var_array = array();
						foreach($var_search as $var)
						{
							$row_v = $GLOBALS['db']->RowQuery("SELECT 
								a.Wert AS Wert_B,
								a.Gewicht,
								a.Name_" . $_SESSION['Langcode'] . " as Name,
								a.Wert,
								a.Operant,
								b.Name_" . $_SESSION['Langcode'] . " as KatName 
							FROM 
								" . PREFIX . "_shop_varianten as a,
								" . PREFIX . "_shop_varianten_kategorien as b 
							WHERE 
								b.Id = a.KatId AND 
								a.Id = '$var'");
							
							if(is_object($row_v))
							{
								$weight_parts += $row_v->Gewicht;
								
								// Varianten Einztelpreise (Nettoshop)
								$row_v->Wert = $row_v->Operant . $this->getNettoPrice($this->getPrice($row_v->Wert), $row_p->Kategorie, $_SESSION['user_country']);
								$row_p->NPreis = $row_p->NPreis + ($row_v->Operant . $this->getPrice($row_v->Wert_B)); // $row_v->Wert
								
								$row_p->NPreisNetto += $row_v->Wert;//$row_v->WertNetto;
								$row_p->Preis += $row_v->Wert;
		
								array_push($var_array,$row_v);
							}
							
						}
						
					} else {
						// Anzahl des Artikel
						$row_p->Anzahl = $_SESSION[$sess_what][$row_p->Id];               
					}
					
					//=================================================================
					// Endpreis
					//=================================================================
					
					$row_p->Endpreis = ($row_p->Preis * $row_p->Anzahl);
					$row_p->Bild = (is_file(BASE_DIR . '/' . $this->_upload_path . 'small/' . $row_p->Bild)) ? $this->_upload_path . 'small/' . $row_p->Bild : 'system/shopthumb.php?smode=small&amp;img=' . $row_p->Bild;
					$row_p->ProdLink = (is_array($var_array)) ? "index.php?p=shop&amp;action=showproduct&amp;id=" . $row_p->Id . "&amp;cid=" . $row_p->Kategorie . "&amp;pname=" . $this->get_clean_name($row_p->Titel) : "index.php?p=shop&amp;action=showproduct&amp;id=" . $row_p->Id . "&amp;cid=" . $row_p->Kategorie . "&amp;pname=" . $this->get_clean_name($row_p->Titel);
					
					$ustVat = $this->getUst($row_p->Kategorie);
					$IncVat = $row_p->NPreis - $row_p->NPreisNetto;
					$IncVat = $IncVat - ($this->getCouponPrice($IncVat));
					#$IncVat = numf($IncVat);
					
					if(!$this->noNettoDisplay($_SESSION['user_country']))
					{
						$GLOBALS['tmpl']->assign('show_vat_table', 1);
						@$_SESSION[$ustVat] += $IncVat * $value;	
					}
					
					$row_p->UstZone = $this->getUst($row_p->Kategorie);
					
					// Brutto-Endpreis
					$Price_brutto += ($row_p->Preis + ($row_p->Preis/100*$row_p->UstZone)) * $value;
					
					$row_p->Vars = $var_array;
					$row_p->Preis_b  = $row_p->Preis + ($row_p->Preis/100*$row_p->UstZone);
					$row_p->Preis_bs = ($row_p->Preis + ($row_p->Preis/100*$row_p->UstZone)) * $value;
					array_push($product_array, $row_p);
					$NettoPrice += ($row_p->NPreisNetto * $value);
					
					//=================================================================
					// Endpreis
					//=================================================================
					if($this->noNettoDisplay($_SESSION['user_country'])) $IncVat = '';
					$Price += (($row_p->Preis+$IncVat) * $value);
					$All += $value;
					$weight += ($row_p->Gewicht * $value);
				}
				
				//=================================================================
				// Steuerzonen einbinden
				//=================================================================
				$ust_vals = array();
				$sql = $GLOBALS['db']->Query("SELECT Wert FROM " . PREFIX . "_shop_ustzone ORDER BY Wert ASC");
				while($row = $sql->fetchrow()) array_push($ust_vals, $row);
				$GLOBALS['tmpl']->assign('ust_vals', $ust_vals);
				
				$_SESSION['gewicht'] = $weight + $weight_parts;
				$_SESSION['gewicht_detail'] = ($weight + $weight_parts) / 1000;
				$_SESSION['price_netto'] = $NettoPrice; //numf($NettoPrice);
			}
			
			//=================================================================
			// Kosten Zahlungsmethode
			//=================================================================
			$_REQUEST['payment_id'] = (isset($_SESSION['payment_id']) && @$_REQUEST['payment_id']=='') ? @$_SESSION['payment_id'] : @$_REQUEST['payment_id'];
			if(!empty($_REQUEST['payment_id']))
			{
				$row_ps = $GLOBALS['db']->RowQuery("SELECT KostenOperant,Kosten,KostenTyp FROM " . PREFIX . "_shop_zahlungsmethoden WHERE Id = '" . $_REQUEST['payment_id'] . "' AND Aktiv = 1");
				if($row_ps->Kosten != '0.00')
				{
					if($row_ps->KostenTyp == 'pro')
					{
						if($row_ps->KostenOperant == '-')
						{
							$_SESSION['payment_summ_mipu'] = 'abzgl';
							$_SESSION['payment_summ_extra_symbol'] = '-';
							$_SESSION['payment_summ_extra'] = ($Price / 100 * $row_ps->Kosten);
							$Price =  $Price - ($Price / 100 * $row_ps->Kosten);
						} else {
							$_SESSION['payment_summ_mipu'] = 'zzgl';
							$_SESSION['payment_summ_extra_symbol'] = '';
							$_SESSION['payment_summ_extra'] = ($Price / 100 * $row_ps->Kosten);
							$Price =  $Price + ($Price / 100 * $row_ps->Kosten);
						}
					} else {
						if($row_ps->KostenOperant == '-')
						{
							$_SESSION['payment_summ_mipu'] = 'abzgl';
							$_SESSION['payment_summ_extra_symbol'] = '-';
							$_SESSION['payment_summ_extra'] = $row_ps->Kosten;
							$Price =  $Price - $row_ps->Kosten;
						} else {
							$_SESSION['payment_summ_mipu'] = 'zzgl';
							$_SESSION['payment_summ_extra_symbol'] = '';
							$_SESSION['payment_summ_extra'] = $row_ps->Kosten;
							$Price =  $Price + $row_ps->Kosten;
						}
					}
				}
			}
			
			//=================================================================
			// Gutscheinwert (-Betrag)
			//=================================================================
			$_SESSION['price_netto_coupon'] = $this->getCouponPrice($_SESSION['price_netto']);
			
			//=================================================================
			// Zwischensumme mit Gutschein
			//=================================================================
			$_SESSION['price_netto_zwi'] = $_SESSION['price_netto'] - $_SESSION['price_netto_coupon'];
				
			//=================================================================
			// Versandkosten
			//=================================================================
			if(!isset($_SESSION['no_shipping'])) $this->getShippingSum();
			
			if(isset($_SESSION['price']) && VERSAND_FREIBETRAG > '0.00' && $_SESSION['price'] >= VERSAND_FREIBETRAG)
			{
				$_SESSION['shipping_summ'] = '';
				$_SESSION['shipping_is_free'] = 1;
				$_SESSION['no_shipping'] = 1;
			}
				
			if(isset($_SESSION['shipping_summ']))
			{
				$Price = $Price + $_SESSION['shipping_summ'] - $_SESSION['price_netto_coupon'];
			}
			
			$_SESSION['price'] = $Price;
			//=================================================================
			//=================================================================
			$GLOBALS['tmpl']->assign('basket_products_brutto', $Price_brutto);
			$GLOBALS['tmpl']->assign('basket_products_weight', $weight);
			$GLOBALS['tmpl']->assign('basket_products_all', $All);
			$GLOBALS['tmpl']->assign('basket_products_price', $_SESSION['price']);
			$GLOBALS['tmpl']->assign('basket_products_price_netto', $NettoPrice);
			$GLOBALS['tmpl']->assign('basket_products', @count($_SESSION['products']));
		}
		if($page==1)
		{
			if(isset($product_array) && is_array($product_array)) return $product_array;
		} else {
			if($ajax_out!=1)
			{
				$tpl_out = $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/basket_small.tpl');
				return $tpl_out;
			}
		}	
	}
	
	
	//=================================================================
	// Gutscheincode
	//=================================================================
	function getCouponPrice($price)
	{
		// Gutschein
		#print_r($_SESSION);
		$price = numf($price);
		$_SESSION['print_coupon_price'] = 1;
		if(isset($_SESSION['coupon_code']) && isset($_SESSION['coupon_id']) && isset($_SESSION['coupon_val']) && !empty($_SESSION['coupon_val']) )
		{
			if($_SESSION['coupon_typ'] == 'pro')
			{
				$price = ((numf($price)/100) * $_SESSION['coupon_val']);
				return $price;
			} else {
				if($price > $_SESSION['coupon_val'])
				{
					$price = $_SESSION['coupon_val'];
					return numf($price);
				} else {
					return 0;
				}
			}
		}
		return 0;
	}
	
	function getShippingSum()
	{
		$weight = numf(@$_SESSION['gewicht'] / 1000);
		$shipper = (isset($_SESSION['shipper_id'])) ? $_SESSION['shipper_id'] : '';
		
		$row = $GLOBALS['db']->RowQuery("SELECT Gebuehr_Pauschal FROM " . PREFIX . "_shop_versandarten WHERE Id = '{$shipper}'");
		if(is_object($row) && $row->Gebuehr_Pauschal >= '0.01')
		{
			if(is_object($row)) $_SESSION['shipping_summ'] = $row->Gebuehr_Pauschal;
		} else {
			$row = $GLOBALS['db']->RowQuery("SELECT Gebuehr FROM " . PREFIX . "_shop_versandarten_volumen WHERE Von <= '{$weight}' AND Bis >= '{$weight}' AND VersandId = '{$shipper}'");
			if(is_object($row)) $_SESSION['shipping_summ'] = $row->Gebuehr;
		}
	}
	
	function showSearchSmall($Source)
	{
		$tpl_out = $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/search_small.tpl');
		return $tpl_out;
	}
	
	
	function getAvIcon($bestellt=0,$anz,$avail=0)
	{
		$Lc = $_SESSION['Langcode'];
		$lief = 1;                                //'ist_lieferbar';
		if($anz < 1 && $bestellt == 1) $lief = 2; //'ist_bestellt';
		if($anz < 1 && $bestellt == 0) $lief = 3; //'nicht_lieferbar';
		if($anz < 1 && $avail == 4) $lief = 4;    //'wird_bestellt';
	
		$row_l = $GLOBALS['db']->RowQuery("SELECT Titel_{$Lc} AS Titel, Text_{$Lc} AS Text FROM " . PREFIX . "_shop_verfuegbarkeit WHERE Id='$lief'");
		
		$GLOBALS['tmpl']->assign('status', '<span class="shop_available_'.$lief.'">'.@koobispecialchars($row_l->Titel).'</span>');
		$GLOBALS['tmpl']->assign('inf', '<span class="shop_available_'.$lief.'">'.@koobispecialchars($row_l->Text).'</span>');
		 
		$tpl_out = $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/available.tpl');
		return $tpl_out;
		//return "<img class=\"absmiddle\" src=\"theme/" . $GLOBALS['theme'] . "/images/shop/{$lief}.png\" alt=\"{$lief}\" border=\"0\" />";
	}
	
	function getAvMsg($bestellt=0,$anz,$avail=0)
	{
		$lief = 0;
		if($anz < 1 && $bestellt == 1) $lief = 1;
		if($anz < 1 && $bestellt == 0) $lief = 2;
		if($anz < 1 && $avail == 4) $lief = 3;
		return $GLOBALS['vailmsg'][$lief]->Name;
	}
	
	//=================================================================
	// Shopeinstellungen
	//=================================================================
	function getShopSettings($field)
	{
		$Lc = $_SESSION['Langcode'];
		$row_shopsettings = $GLOBALS['db']->RowQuery("SELECT $field FROM " . PREFIX . "_shop_einstellungen");
		return $row_shopsettings->$field;
	}
	
	function getShopNavi($id=0,$cid=0,$items)
	{
		$_REQUEST['cid'] = ($cid != '0') ? $cid : ((isset($_REQUEST['cid']) ? $_REQUEST['cid'] : 0));
		$q = "
			SELECT 
				a.Parent_Id as Parent 
			FROM 
				" . PREFIX . "_shop_kategorie as a,
				" . PREFIX . "_shop_produkte as b
			WHERE 
				a.Id = '" . $_REQUEST['cid'] . "' 
			";
		$row_nav_opt = $GLOBALS['db']->ArrQuery($q);
		$Lc = $_SESSION['Langcode'];
		$query = $GLOBALS['db']->Query("SELECT *,Id as catid, Name_1 as DefCatName, Name_{$Lc} as catname, Name_{$Lc} as Name FROM " . PREFIX . "_shop_kategorie WHERE Parent_Id = '$id' order by posi ASC");
		if (!$query->numrows())
		{
			return;
		} 
		
		while ($item = $query->fetchrow())
		{
			if(!$item->catname) $item->catname = $item->DefCatName;
			array_push($items, $item);
			$this->getShopNavi($item->catid,$_REQUEST['cid'],$items);
		}
		return $items;
	}
	
	

	
	function get_parent_shopcateg($param)
	{
		if(VERSION == 'PRO')
		{
			$id = (is_array($param)) ? $param['id'] : $param ;
			
			$Parent_Id = $id;
			$id = 0;
			if($Parent_Id != 0)
			{
				$sql = $GLOBALS['db']->Query("SELECT Parent_Id,Id as catid FROM ".PREFIX."_shop_kategorie WHERE Id = '".$Parent_Id."'");
				$row = $sql->fetchrow();
				$Parent_Id = $row->Parent_Id;
				$id = $Parent_Id;
				#$id = $row->catid;	
			}
			return($id);
		}
	}
	
	//=================================================================
	/// Shopnavigation
	//=================================================================
	function MyShopNavi($id,&$categs_shop,$categ='',$inarray='')
	{
		$Lc = $_SESSION['Langcode'];
		$GLOBALS['tmpl']->assign('plim', $this->_limit);
		
		//if($_REQUEST['p'] != 'misc') $_REQUEST['categ'] = $_REQUEST['cid'];
		
		$query = $GLOBALS['db']->Query("SELECT Bild_Navi,Parent_Id, Id, Name_1 as DefCatName, Name_{$Lc} as Name FROM " . PREFIX . "_shop_kategorie WHERE Parent_Id = '0' ORDER BY posi ASC");
		while ($item = $query->fetchrow())
		{
			$item->navop = ($this->get_parent_shopcateg($item->Parent_Id)==0) ? $item->Parent_Id : $this->get_parent_shopcateg($item->Parent_Id);
			$categs_2 = array();
			
			// 1. Ebene
			if(!$item->Name) $item->Name = $item->DefCatName; 
			$item->Icon = (!empty($item->Bild_Navi) && is_file(BASE_DIR . '/uploads/shop/navi_categs/' . $item->Bild_Navi)) ? '<img class="absmiddle" border="0" src="uploads/shop/navi_categs/' . $item->Bild_Navi . '" alt="" />' : '<img class="absmiddle" src="theme/'.$GLOBALS['theme'].'/images/shop/navi_no_img.png" border="0" alt=""  />';
			$item->Entry = $item->Name;
			
			// 2.Ebene
			$query_2 = $GLOBALS['db']->Query("SELECT Bild_Navi,Parent_Id, Id, Name_1 as DefCatName, Name_{$Lc} as Name FROM " . PREFIX . "_shop_kategorie WHERE Parent_Id = '$item->Id' ORDER BY posi ASC");
			if ($query_2->numrows())
			{
				while ($items_2 = $query_2->fetchrow())
				{
					$items_2->Icon = (!empty($items_2->Bild_Navi) && is_file(BASE_DIR . '/uploads/shop/navi_categs/' . $items_2->Bild_Navi)) ? '<img class="absmiddle" border="0" src="uploads/shop/navi_categs/' . $items_2->Bild_Navi . '" alt="" />' : '<img class="absmiddle" src="theme/'.$GLOBALS['theme'].'/images/shop/navi_no_img.png" border="0" alt=""  />';
					if(!$items_2->Name) $items_2->Name = $items_2->DefCatName; 
					$categs_3 = array();
					$items_2->Entry = $items_2->Name;
					
					// 3. Ebene
					$query_3 = $GLOBALS['db']->Query("SELECT Bild_Navi,Parent_Id, Id, Name_1 as DefCatName, Name_{$Lc} as Name FROM " . PREFIX . "_shop_kategorie WHERE Parent_Id = '$items_2->Id' ORDER BY posi ASC");
					if ($query_3->numrows())
					{
						while ($items_3 = $query_3->fetchrow())
						{
							$items_3->Icon = (!empty($items_3->Bild_Navi) && is_file(BASE_DIR . '/uploads/shop/navi_categs/' . $items_3->Bild_Navi)) ? '<img class="absmiddle" border="0" src="uploads/shop/navi_categs/' . $items_3->Bild_Navi . '" alt="" />' : '<img class="absmiddle" src="theme/'.$GLOBALS['theme'].'/images/shop/navi_no_img.png" border="0" alt=""  />';
							if(!$items_3->Name) $items_3->Name = $items_3->DefCatName; 
							// 4.Ebene
							$categs_4 = array();
							$query_4 = $GLOBALS['db']->Query("SELECT Bild_Navi, Parent_Id, Id, Name_1 as DefCatName,Name_{$Lc} as Name FROM " . PREFIX . "_shop_kategorie WHERE Parent_Id = '$items_3->Id' ORDER BY posi ASC");
							if ($query_4->numrows())
							{
								while ($items_4 = $query_4->fetchrow())
								{
									$items_4->Icon = (!empty($items_4->Bild_Navi) && is_file(BASE_DIR . '/uploads/shop/navi_categs/' . $items_4->Bild_Navi)) ? '<img class="absmiddle" border="0" src="uploads/shop/navi_categs/' . $items_4->Bild_Navi . '" alt="" />' : '<img class="absmiddle" src="theme/'.$GLOBALS['theme'].'/images/shop/navi_no_img.png" border="0" alt=""  />';
									if(!$items_4->Name) $items_4->Name = $items_4->DefCatName; 
									// 5.Ebene
									$categs_5 = array();
									$query_5 = $GLOBALS['db']->Query("SELECT Bild_Navi,Parent_Id, Id, Name_1 as DefCatName, Name_{$Lc} as Name FROM " . PREFIX . "_shop_kategorie WHERE Parent_Id = '$items_4->Id' ORDER BY posi ASC");
									if ($query_5->numrows())
									{
										while ($items_5 = $query_5->fetchrow())
										{
											$items_5->Icon = (!empty($items_5->Bild_Navi) && is_file(BASE_DIR . '/uploads/shop/navi_categs/' . $items_5->Bild_Navi)) ? '<img class="absmiddle" border="0" src="uploads/shop/navi_categs/' . $items_5->Bild_Navi . '" alt="" />' : '<img class="absmiddle" src="theme/'.$GLOBALS['theme'].'/images/shop/navi_no_img.png" border="0" alt=""  />';
											if(!$items_5->Name) $items_5->Name = $items_5->DefCatName; 
											array_push($categs_5,$items_5);
										}
									}
									
									$items_4->Sub4 = $categs_5;
									array_push($categs_4,$items_4);
								}
							}
							$items_3->Sub3 = $categs_4;
							array_push($categs_3,$items_3);
						}
					}
					
					$items_2->Sub2 = $categs_3;
					array_push($categs_2,$items_2);
				}
			}
			$item->Sub1 = $categs_2;
			array_push($categs_shop,$item);
		}
		return $categs_shop;
	}
	
	//=================================================================
	// Aktueller Navibereich
	//=================================================================
	function get_starter_shopcateg($categ,$cc,$c)
	{
		$sql = $GLOBALS['db']->Query("SELECT Parent_Id,Id FROM ".PREFIX."_shop_kategorie WHERE Id = '" . $categ. "'");
		if($sql->numrows())
		{
			$row = $sql->fetchrow();
			array_push($c,$row->Parent_Id);
			$sql = $GLOBALS['db']->Query("SELECT Parent_Id,Id FROM ".PREFIX."_shop_kategorie WHERE Id = '" . $row->Parent_Id. "'");
			if($sql->numrows())
			{
				$row = $sql->fetchrow();
				if($row->Parent_Id!=0) array_push($c,$row->Parent_Id);
				$sql = $GLOBALS['db']->Query("SELECT Parent_Id,Id FROM ".PREFIX."_shop_kategorie WHERE Id = '" . $row->Parent_Id. "'");
				if($sql->numrows())
				{
					$row = $sql->fetchrow();
					if($row->Parent_Id!=0) array_push($c,$row->Parent_Id);
					$sql = $GLOBALS['db']->Query("SELECT Parent_Id,Id FROM ".PREFIX."_shop_kategorie WHERE Id = '" . $row->Parent_Id. "'");
					if($sql->numrows())
					{
						$row = $sql->fetchrow();
						if($row->Parent_Id!=0)
						{
							array_push($c,$row->Parent_Id);
							$sql = $GLOBALS['db']->Query("SELECT Parent_Id,Id FROM ".PREFIX."_shop_kategorie WHERE Id = '" . $row->Parent_Id. "'");
							if($sql->numrows())
							{
								$row = $sql->fetchrow();
								array_push($c,$row->Parent_Id);
							}
						}
					}
				}
			}
		}
		return $c;
	}
	
	//=================================================================
	// Funktion zum Auslesen der Artikelanzahl in einer Kategorie
	//=================================================================
	function getArticleCount($cid)
	{
		$db_cid = (isset($cid) && !empty($cid)) ? " AND (Kategorie = '" . (int)$cid . "' OR Kategorie_Multi like '%," . (int)$cid . ",%' OR Kategorie_Multi like '%," . (int)$cid . "' OR Kategorie_Multi like '" . (int)$cid . ",%')" : "";
		$num = $GLOBALS['db']->RowQuery("SELECT COUNT(Id) AS num_count FROM " . PREFIX . "_shop_produkte WHERE Aktiv = 1 $db_cid");
		return $num->num_count;
	}
	
	function getManufacturer()
	{	
		$m = array();
		$sql = $GLOBALS['db']->Query("SELECT Id,Name FROM " . PREFIX . "_shop_hersteller ORDER BY Name ASC");
		while($row = $sql->fetcharray())
		{
			array_push($m, $row);
		}
		return $m;
	}
	
	function getManufacturerById($mid)
	{	
		$manu = $GLOBALS['db']->RowQuery("SELECT Id,Name FROM " . PREFIX . "_shop_hersteller WHERE Id = '$mid'");
		return $manu;
	}
	
	function get_data_clean($var)
	{
		return trim(eregi_replace('[^ A-Za-zÀ-ÖØ-öø-ÿ0-9_-]', '', $var));
	}


	//=================================================================
	// Funktion Bezahlvorgang
	//=================================================================
	function step4($accept_id=0,$mail=0)
	{
		$_SESSION['shopstep'] = 4;
		$_SESSION['bank_transfer'] = 0;
		
		
		// Pruefen ob nicht erlaubte Methode(n)
		$row = $GLOBALS['db']->RowQuery("SELECT * FROM " . PREFIX . "_shop_zahlungsmethoden WHERE Aktiv = 1 AND Id = '" . $_REQUEST['payment_id'] . "'");
		$Versandarten = explode(',', $row->Versandarten);
		$Laender = explode(',', strtoupper($row->Laender));
		$Gruppen = explode(',', strtoupper($row->Gruppen));
		if(in_array($_SESSION['shipper_id'],$Versandarten) && in_array($_SESSION['user_group'],$Gruppen))
			$error = false;
		else
			$error = true;
		
		if($error==true) refer("index.php?p=shop&action=shoporder&subaction=step3");
		
		// Wenn Banktransfer gewaehlt
		if(isset($_REQUEST['payment_id']) && $_REQUEST['payment_id'] == 4)
		{
			$error = false;
			if(empty($_POST['bank_name']) || strlen($_POST['bank_name']) < 5 || @preg_match('/[^ A-Za-zÀ-ÖØ-öø-ÿ0-9_-]/',$_POST['bank_name'])) $error = true;
			if(empty($_POST['bank_num'])  || strlen($_POST['bank_num']) < 6 || @preg_match('/[^ 0-9]/',$_POST['bank_num'])) $error = true;
			if(empty($_POST['knt_num'])   || strlen($_POST['knt_num']) < 6 || @preg_match('/[^ 0-9]/',$_POST['knt_num'])) $error = true;
			if(empty($_POST['knt_inh'])   || strlen($_POST['knt_inh']) < 5 || @preg_match('/[^ A-Za-zÀ-ÖØ-öø-ÿ0-9_-]/',$_POST['knt_inh'])) $error = true;
			
			$_SESSION['bank_name'] = $this->get_data_clean($_POST['bank_name']);
			$_SESSION['bank_num'] = $this->get_data_clean($_POST['bank_num']);
			$_SESSION['knt_num'] = $this->get_data_clean($_POST['knt_num']);
			$_SESSION['knt_inh'] = $this->get_data_clean($_POST['knt_inh']);
			
			if($error==true) 
				refer("index.php?p=shop&action=shoporder&subaction=step3&pim=4&e=1#vid4");
			else
				$_SESSION['bank_transfer'] = 1;
		}
		
		if($_SESSION['step3_ok'] != 1){refer("index.php?p=shop&action=showbasket");exit;}
		if(!isset($_SESSION['products']) || empty($_SESSION['products'])){refer("index.php?p=shop&action=showbasket");exit;}
		if((!isset($_REQUEST['payment_id']) || empty($_REQUEST['payment_id'])) || (@$_SESSION['step3_ok']!=1) || (GUEST_ORDER!=1 && $_SESSION['user_group']==2) || ($_SESSION['user_group']==2 && @$_REQUEST['order']!='guest'))  { refer("index.php?p=shop&action=shoporder&subaction=step3"); exit; }
		
		if(isset($_REQUEST['payment_id']) && !empty($_REQUEST['payment_id']))
		{
			$_SESSION['payment_id'] = $_REQUEST['payment_id'];
		}
		
		
		
		if(!isset($_SESSION['shipper_id']))
		{
			$guest_wl = (isset($_REQUEST['order']) && $_REQUEST['order'] == 'guest') ? '&order=guest' : '';
			refer("index.php?sendform=1&p=shop&action=shoporder&subaction=step3" . $guest_wl);
			exit;
		}
		
		if(!isset($_SESSION['r_land']))
		{
			refer('index.php?sendform=1&p=shop&action=shoporder&step=2');
			exit;
		}
		
		$_SESSION['r_land_lang'] = $this->getCountryName($_SESSION['r_land']);
		$_SESSION['l_land_lang'] = $this->getCountryName($_SESSION['l_land']);
		$_SESSION['shipper_name'] = $this->getShipperName($_SESSION['shipper_id']);
		$_SESSION['paymenForums_Username'] = $this->getPaymentName($_SESSION['payment_id']);
		$_SESSION['step4_ok'] = 1;
		
		if($accept_id==1) 
		{
			$GLOBALS['tmpl']->assign('agb_error', 1) ;
			if(empty($_REQUEST['dataprotection_ok'])) $GLOBALS['tmpl']->assign('data_error', 1);
			if(empty($_REQUEST['fraudinf_ok'])) $GLOBALS['tmpl']->assign('fraudinf_error', 1);
		} elseif (!empty($_REQUEST['agb_ok'])) {
			$GLOBALS['tmpl']->assign('agb_accept_checked', 1) ;
		}
		
		if($accept_id==2) 
		{
			$GLOBALS['tmpl']->assign('data_error', 1);
			if(empty($_REQUEST['agb_ok'])) $GLOBALS['tmpl']->assign('agb_error', 1);
			if(empty($_REQUEST['fraudinf_ok'])) $GLOBALS['tmpl']->assign('fraudinf_error', 1);
		} elseif (!empty($_REQUEST['dataprotection_ok'])) {
			$GLOBALS['tmpl']->assign('dataprotection_checked', 1) ;
		}
		
		if($accept_id==3) 
		{
			$GLOBALS['tmpl']->assign('fraudinf_error', 1);
		} elseif (!empty($_REQUEST['fraudinf_ok'])) {
			$GLOBALS['tmpl']->assign('fraudinf_checked', 1) ;
		}
		
		$info_msg = str_replace('--IP--',$_SERVER['REMOTE_ADDR'],$GLOBALS['config_vars']['Shop_agb_accept']);
		$GLOBALS['tmpl']->assign('INF_MSG', $info_msg);
		$GLOBALS['tmpl']->assign('basket_display', 'step4');
		$GLOBALS['tmpl']->assign('product_array', $this->initBasket(1));
		if($mail==1)
		{
			//
		} else {
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/order_step4.tpl'));
		}
	}

	//=================================================================
	//=================================================================
	// Bestellungs-Schritte
	//=================================================================
	function shopOrder()
	{
		$GLOBALS['tmpl']->assign('shop_country', $GLOBALS['shopsettings']->ShopLand);
		$GLOBALS['tmpl']->assign('disable_curreny_selector', 1);
		$_REQUEST['subaction'] = (isset($_REQUEST['subaction']) && !empty($_REQUEST['subaction'])) ? $_REQUEST['subaction'] : 'step2';
		
		switch($_REQUEST['subaction'])
		{
			//=================================================================
			// Schritt 2 (Versenden nach Warenkorb)
			//=================================================================
			case 'step2':
				$_SESSION['shopstep'] = 2;
				$_SESSION['step2_ok'] = 0;
				$_SESSION['step3_ok'] = 0;
				$_SESSION['step4_ok'] = 0;
				unset($_SESSION['bank_name']);
				unset($_SESSION['bank_num']);
				unset($_SESSION['knt_num']);
				unset($_SESSION['knt_inh']);
				unset($_SESSION['shipper_id']);
				//unset($_SESSION['coupon_code']);
				if(isset($_POST['coupon']) && !empty($_POST['coupon']) && SHOP_COUPONS == 1 && !isset($_SESSION['coupon_code']))
				{
					$coupon = get_clean($_POST['coupon']);
					$where = (isset($_SESSION['user_group']) && $_SESSION['user_group']==2) ? ' AND Gastbestellung=1 ' : '';
					$row_c = $GLOBALS['db']->RowQuery("SELECT * FROM " . PREFIX . "_shop_gutscheine WHERE Code = '{$coupon}' $where");
					if(is_object($row_c))
					{
						$c_users = explode(',', $row_c->BenutzerMulti);
						if((($row_c-> Eingeloest == '0') && ($row_c->GueltigBis >= stime()) && !in_array($_SESSION['benutzer_id'],$c_users)) || (($row_c->Endlos==1 && !in_array($_SESSION['benutzer_id'],$c_users)) && ($row_c->GueltigBis >= stime())))
						{
							if($row_c->MinBestellwert <= $_SESSION['price_netto'] || $row_c->MinBestellwert < '0.01')
							{
								
								$_SESSION['coupon_code'] = $coupon;
								$_SESSION['coupon_id'] = $row_c->Id;
								$_SESSION['coupon_val'] = $row_c->Wert;
								$_SESSION['coupon_typ'] = $row_c->Typ;
								refer("index.php?sendform=1&p=shop&action=showbasket");
							} else {
								refer("index.php?sendform=1&p=shop&action=showbasket&couponerror=2");
							}
						} else {
							refer("index.php?sendform=1&p=shop&action=showbasket&couponerror=1");
						}
					} else {
						refer("index.php?sendform=1&p=shop&action=showbasket&couponerror=1");
					}
				}
				if(isset($_REQUEST['register']) && $_REQUEST['register'] == 'new' && !isset($_SESSION['loggedin']))
				{
					
					$GLOBALS['tmpl']->assign('shop', 1);
					$Login = new Login;
					$Login->registerNew(1);
				} else {
					
					//=================================================================
					// Login (Ich bin bereits Kunde)
					//=================================================================
					if(isset($_REQUEST['s_login']) && $_REQUEST['s_login'] == 1 && isset($_REQUEST['s_login_email']) && !empty($_REQUEST['s_login_email']) && isset($_REQUEST['s_login_pass']) && !empty($_REQUEST['s_login_pass']))
					{
						$login_email = eregi_replace('[^@.A-Za-zÀ-ÖØ-öø-ÿ0-9]', '', $_REQUEST['s_login_email']);
						$login_pass  = md5(md5(eregi_replace('[^A-Za-zÀ-ÖØ-öø-ÿ0-9]', '', $_REQUEST['s_login_pass'])));
						
						$sql = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_benutzer WHERE Email = '{$login_email}' AND Kennwort = '{$login_pass}' AND Aktiv = '1' LIMIT 1");
						$num = $sql->numrows();
						$row = $sql->fetchrow();
						
						if($num != 1)
						{
							Logger('User ' . $login_email . ' wrong login.', '', '');
							$GLOBALS['tmpl']->assign('login_false', 1);
						} else {
							
							$_SESSION['loggedin'] = 1;
							$_SESSION['benutzer_id'] = $row->Id;
							$_SESSION['login_email'] = $login_email;
							$_SESSION['login_pass'] = $login_pass;
							$_SESSION['user_name'] = $row->Benutzername;
							$_SESSION['user_group'] = $row->Gruppe;
							$_SESSION['user_group_misc'] = @explode(';', $row->GruppeMisc);
							
							if(!empty($row->Vorname)) $_SESSION['benutzer_vorname'] = $row->Vorname;
							if(!empty($row->Nachname)) $_SESSION['benutzer_nachname'] = $row->Nachname;
							if(!empty($row->Strasse_Nr)) $_SESSION['benutzer_strasse'] = $row->Strasse_Nr;
							if(!empty($row->Postleitzahl)) $_SESSION['benutzer_plz'] = $row->Postleitzahl;
							if(!empty($row->Ort)) $_SESSION['benutzer_ort'] = $row->Ort;
							if(!empty($row->Firma)) $_SESSION['benutzer_firma'] = $row->Firma;
							if(!empty($row->UStId)) $_SESSION['benutzer_ustid'] = $row->UStId;
							if(!empty($row->Telefon)) $_SESSION['benutzer_fon'] = $row->Telefon;
							if(!empty($row->Telefax)) $_SESSION['benutzer_fax'] = $row->Telefax;
							
							if(isset($_REQUEST['s_staylogged']) && $_REQUEST['s_staylogged'] == 1)
							{
								setcookie("koobi_login_email", $login_email, time() + (3600 * 31 * 6));
								setcookie("koobi_login_pass", $login_pass, time() + (3600 * 31 * 6));
							}
							
							$GLOBALS['db']->Query("UPDATE " . PREFIX . "_benutzer SET Logins=Logins+1 WHERE Email = '{$login_email}' AND Kennwort = '{$login_pass}' AND Aktiv = '1' LIMIT 1");
							$GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_benutzer_logins (Id,Benutzer,Datum,Datum_dt,Ip,Email) VALUES ('', '$row->Id', '".time()."', NOW(), '".$_SERVER['REMOTE_ADDR']."', '$login_email')");
							Logger('User ' . $_SESSION['user_name'] . ' logged in.', '', $_SESSION['benutzer_id']);
						}
					}
					
					$GLOBALS['tmpl']->assign('headernav', "<a href=\"index.php?p=shop\">" . $GLOBALS['config_vars']['Shop'] . "</a>" . $GLOBALS['config_vars']['PageSep'] . $GLOBALS['config_vars']['Shop_step_2']);
					$GLOBALS['tmpl']->assign('pagetitle_html', $GLOBALS['config_vars']['Shop']);
				
					if(!isset($_SESSION['products']) || empty($_SESSION['products'])) { refer("index.php?p=shop&action=showbasket"); exit; }
					if($_SESSION['user_group']==2)
					{
						//=================================================================
						// Darf nicht eingeloggter Benutzer bestellen?
						//=================================================================
						if(GUEST_ORDER==1) $GLOBALS['tmpl']->assign('guest_order', 1);
						if(isset($_REQUEST['order']) && $_REQUEST['order']=='guest')
						{
							if(GUEST_ORDER!=1)  { refer("index.php?sendorder=1&p=shop&action=shoporder&subaction=step2"); exit; }
							
							//=================================================================
							// Daten speichern (Gastbestellung)
							//=================================================================
							if(isset($_REQUEST['save']) && $_REQUEST['save']==1)
							{
								$this->checkFormData('guestorder');
							}
							$GLOBALS['tmpl']->assign('countries', $this->getCountries());
							$GLOBALS['tmpl']->assign('logged_options', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/order_step2_dataform.tpl'));
						} else {
							//=================================================================
							// Benutzer ist nicht eingeloggt
							//=================================================================
							$GLOBALS['tmpl']->assign('logged_options', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/order_step2_notloggedin.tpl'));
						}
					} else {
						//=================================================================
						// Benutzer ist eingeloggt
						//=================================================================
						
						$user = $GLOBALS['db']->RowQuery("SELECT * FROM " . PREFIX . "_benutzer WHERE Id = '" . $_SESSION['benutzer_id'] . "' AND Kennwort = '" . $_SESSION['login_pass'] . "'");
						if(isset($_REQUEST['save']) && $_REQUEST['save']==1)
						{
							$this->checkFormData('user');
						} else {
							if(empty($_SESSION['r_email'])) $_SESSION['r_email'] = $user->Email;
							if(empty($_SESSION['r_vorname'])) $_SESSION['r_vorname'] = $user->Vorname;
							if(empty($_SESSION['r_nachname'])) $_SESSION['r_nachname'] = $user->Nachname;
							if(empty($_SESSION['r_strasse'])) $_SESSION['r_strasse'] = $user->Strasse_Nr;
							if(empty($_SESSION['r_plz'])) $_SESSION['r_plz'] = $user->Postleitzahl;
							if(empty($_SESSION['r_ort'])) $_SESSION['r_ort'] = $user->Ort;
							if(empty($_SESSION['r_telefon'])) $_SESSION['r_telefon'] = $user->Telefon;
							if(empty($_SESSION['r_fax'])) $_SESSION['r_fax'] = $user->Telefax;
							if(empty($_SESSION['r_firma'])) $_SESSION['r_firma'] = $user->Firma;
							if(empty($_SESSION['r_ustid'])) $_SESSION['r_ustid'] = $user->UStId;
							if(empty($_SESSION['user_country'])) $_SESSION['user_country'] = $user->LandCode;
							
							$GLOBALS['tmpl']->assign('user', $user);
							
							$_SESSION['r_land'] = strtoupper($user->LandCode);
						}
						$GLOBALS['tmpl']->assign('countries', $this->getCountries());
						$GLOBALS['tmpl']->assign('logged_options', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/order_step2_dataform.tpl'));
					}
					$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/order_step2.tpl'));
				}
				
			break;
			
			//=================================================================
			// Schritt 3 (Bezahlen nach Versenden)
			//=================================================================
			case 'step3':
				
				$error = '';
				$_SESSION['step3_ok'] = 0;
				$_SESSION['step4_ok'] = 0;
				$_SESSION['shipping_sum'] = '';
				
				if(BEST_MAX != '0.00' && (isset($_SESSION['price_netto']) && $_SESSION['price_netto'] > BEST_MAX))
				{
					$_SESSION['shopstep'] = 3;
					$error = 'to_much';
					$GLOBALS['tmpl']->assign('koobi_error', $error);
				}
				
				if(BEST_MIN != '0.00' && (isset($_SESSION['price_netto']) && $_SESSION['price_netto'] < BEST_MIN))
				{
					$_SESSION['shopstep'] = 3;
					$error = 'not_reached';
					$GLOBALS['tmpl']->assign('koobi_error', $error);
				}
					
				if(empty($error))
				{
					$GLOBALS['tmpl']->assign('headernav', "<a href=\"index.php?p=shop\">" . $GLOBALS['config_vars']['Shop'] . "</a>" . $GLOBALS['config_vars']['PageSep'] . $GLOBALS['config_vars']['Shop_step_3']);
					$GLOBALS['tmpl']->assign('pagetitle_html', $GLOBALS['config_vars']['Shop']);
					
					$error = true;
					$shipper_id = '';
					
					if((@$_SESSION['step2_ok']!=1) || (GUEST_ORDER!=1 && $_SESSION['user_group']==2) || ($_SESSION['user_group']==2 && @$_REQUEST['order']!='guest')) 
					{
						echo $_REQUEST['order'];
					}
					
					if(!isset($_SESSION['products']) || empty($_SESSION['products'])) { refer("index.php?p=shop&action=showbasket"); exit; }
					if((@$_SESSION['step2_ok']!=1) || (GUEST_ORDER!=1 && $_SESSION['user_group']==2) || ($_SESSION['user_group']==2 && @$_REQUEST['order']!='guest'))  { refer("index.php?p=shop&action=shoporder&subaction=step2"); exit; }
					
					$_SESSION['shopstep'] = 3;
					
					$weight = (@$_SESSION['gewicht'] / 1000);
					$nullShipper = @$_SESSION['gewicht'] <= '1' ? 1 : 0;
				
					if($this->checkShipper())
					{
						$error = false;
						$GLOBALS['tmpl']->assign('shipper_found', 1);
					}
					
					if($error == false) $_SESSION['step3_ok'] = 1;
					
					$inf_id = (isset($_POST['versand_id']) && !empty($_POST['versand_id']) && is_numeric($_POST['versand_id'])) ? $_POST['versand_id'] : '';
					
					//=================================================================
					// Moegliche Zahlungsoptionen
					// Zuerst wird die voreingestellte Versandmethode beruecksichtigt
					//=================================================================
					$check_s = $this->getShipper(0,0,$nullShipper);
					if(!empty($check_s))
					{
						$current_shipper = $this->getShipperInf($inf_id);
						if(!is_object($current_shipper))
						{
							$start = 1;
							foreach($check_s as $x)
							{
								if ($start == 1)
								{
									$shipper_id = $x->Id;
									$inf_id = $x->Id;
								}
								$start++;
							}
						} else {
							$shipper_id = $current_shipper->Id;
						}
						
						$GLOBALS['tmpl']->assign('Payments', $this->listPayments($shipper_id));
					}
					
					if(!empty($shipper_id))
					{
						$_SESSION['shipper_id'] = $shipper_id;
					}
					
					$sInf = $this->getShipperInf($inf_id);
					$allowed_shipper = array();
					$control = $this->getShipper(0,0,$nullShipper);
					foreach($control as $c => $key) 
					{
						array_push($allowed_shipper,$key->Id);
					}
					
					if(!in_array(@$_SESSION['shipper_id'], $allowed_shipper))
					{
						$GLOBALS['tmpl']->assign('error', '1');
						unset($_SESSION['shipper_id']);
					}
					
					if(is_object($sInf)) $sInf->Gebuehr_PauschalS = $this->GetPrice($sInf->Gebuehr_Pauschal);
					$GLOBALS['tmpl']->assign('shipping_summ', (is_object($sInf) ? $this->GetPrice($sInf->Gebuehr_Pauschal) : ''));
					$GLOBALS['tmpl']->assign('shipperInf', $sInf);
					$GLOBALS['tmpl']->assign('shipper', $this->getShipper(0,0,$nullShipper));
					$GLOBALS['tmpl']->assign('def_knt_inh', $_SESSION['r_vorname'] . ' ' . $_SESSION['r_nachname']);
				}
				$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/order_step3.tpl'));
			break;
			
			//=================================================================
			// Ueberpruefung aller Angaben
			//=================================================================
			case 'step4':
				$this->step4();
				$GLOBALS['tmpl']->assign('headernav', "<a href=\"index.php?p=shop\">" . $GLOBALS['config_vars']['Shop'] . "</a>" . $GLOBALS['config_vars']['PageSep'] . $GLOBALS['config_vars']['Shop_step_4']);
				$GLOBALS['tmpl']->assign('pagetitle_html', $GLOBALS['config_vars']['Shop']);
			break;
			
			//=================================================================
			// Bestellung absenden
			//=================================================================
			case 'final':
				$att_ext = '';
				if(empty($_REQUEST['agb_ok']))
				{
					$_SESSION['step3_ok'] = 1;
					$_REQUEST['payment_id'] = $_SESSION['payment_id'];
					$this->step4(1);
				} elseif (empty($_REQUEST['dataprotection_ok'])) 
				{
					$_SESSION['step3_ok'] = 1;
					$_REQUEST['payment_id'] = $_SESSION['payment_id'];
					$this->step4(2);
				} elseif (empty($_REQUEST['fraudinf_ok'])) 
				{
					$_SESSION['step3_ok'] = 1;
					$_REQUEST['payment_id'] = $_SESSION['payment_id'];
					$this->step4(3);
				} else {
					if($_SESSION['step4_ok'] != 1){refer("index.php?p=shop&action=showbasket");exit;}
					if(!isset($_SESSION['products']) || empty($_SESSION['products'])){refer("index.php?p=shop&action=showbasket");exit;}
					if((!isset($_SESSION['payment_id']) || empty($_SESSION['payment_id'])) || (@$_SESSION['step4_ok']!=1) || (GUEST_ORDER!=1 && $_SESSION['user_group']==2) || ($_SESSION['user_group']==2 && @$_REQUEST['order']!='guest'))  { refer("index.php?p=shop&action=shoporder&subaction=step3"); exit; }
				
					$payment_data  = $GLOBALS['db']->ArrQuery("SELECT DetailInfo, Beschreibung_" . $_SESSION['Langcode'] . " AS Beschreibung FROM " . PREFIX . "_shop_zahlungsmethoden WHERE Id = '" . $_SESSION['payment_id'] . "'");
					$shipping_data = $GLOBALS['db']->ArrQuery("SELECT Beschreibung_" . $_SESSION['Langcode'] . " AS Beschreibung FROM " . PREFIX . "_shop_versandarten WHERE Id = '" . $_SESSION['shipper_id'] . "'");
							
					$ref_url = str_replace('index.php','',redir());
					$logo = $GLOBALS['shopsettings']->RechnungsLogo;
					$order_num = $this->orderNumber(10);
					$order_time = date('d-m-Y, H:i', stime());
					
					if(!empty($payment_data['DetailInfo']))
					{
						$DetInfo = str_replace('%%ORDER%%', $order_num, $payment_data['DetailInfo']);
						$_SESSION['DetailInfo'] = stripslashes($DetInfo);
					}
					
					$GLOBALS['tmpl']->assign('product_array', $this->initBasket(1));
					$GLOBALS['tmpl']->assign('link_prefix', $ref_url);
					$GLOBALS['tmpl']->assign('order_num', $order_num);
					$GLOBALS['tmpl']->assign('order_time', $order_time);
					$GLOBALS['tmpl']->assign('billing_logo', (!empty($logo) ? '<img src="' . $logo . '" alt="" alt="" />' : ''));
					$GLOBALS['tmpl']->assign('shop_adress_html', $GLOBALS['shopsettings']->ShopAdresse);
					
					//=================================================================
					// Mail vorbereiten
					// Details Zahlungsart und  Details Versandmethode
					//=================================================================
					$_SESSION['payment_details'] = $payment_data['Beschreibung'];
					$_SESSION['shipping_details'] = $shipping_data['Beschreibung'];
					
					
					foreach($_SESSION['products'] as $product => $pid_count)
					{
						$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_produkte SET Verkauft=Verkauft+{$pid_count} WHERE Id='{$product}'");
					}
							
					//=================================================================
					// Bestand verringern
					//=================================================================
					if($GLOBALS['shopsettings']->Bestand_Zaehlen == 1) 
					{
						foreach($_SESSION['products'] as $product => $pid_count)
						{
							$cc = $GLOBALS['db']->RowQuery("SELECT Lagerbestand FROM " . PREFIX . "_shop_produkte WHERE Id='{$product}'");
							if($cc->Lagerbestand>=1)
							{
								$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_produkte SET Lagerbestand=Lagerbestand-{$pid_count} WHERE Id='{$product}'");
							}
						}
					}
										
					//=================================================================
					// Bestellung eintragen
					//=================================================================
					$q = "INSERT INTO " . PREFIX . "_shop_bestellungen 
					(
						Id,
						Datum,
						Ip,
						Benutzer,
						Email,
						Betrag,
						Artikel,
						TransaktionsNummer,
						USt,
						ZahlungsId,
						VersandId,
						Rng_Firma,   	
						Rng_Anrede,  	
						Rng_Vorname,  	
						Rng_Nachname,  	
						Rng_Strasse,  	
						Rng_Plz,  	
						Rng_Ort,  	
						Rng_Land,  
						Rng_Fon, 	
						Rng_Fax,  	
						Rng_Email,
						Lief_Anrede,
						Lief_Vorname,
						Lief_Nachname,
						Lief_Strasse,
						Lief_Plz,
						Lief_Ort,
						Lief_Fon,
						Lief_Fax,
						Lief_Land,
						Lief_Firma,
						Gewicht,
						GutscheinWert,
						GutscheinId,
						KundenNachricht
					) VALUES (
						'',
						'" . stime() . "',
						'" . $_SERVER['REMOTE_ADDR'] . "',
						'" . $_SESSION['benutzer_id'] . "',
						'" . $_SESSION['r_email'] . "',
						'" . numf($_SESSION['price']) . "',
						'" . serialize($_SESSION['products']) . "',
						'$order_num',
						'',
						'" . $_SESSION['payment_id'] . "',
						'" . $_SESSION['shipper_id'] . "',
						'" . $_SESSION['r_firma'] . "',
						'" . $_SESSION['r_anrede'] . "',
						'" . $_SESSION['r_vorname'] . "',
						'" . $_SESSION['r_nachname'] . "',
						'" . $_SESSION['r_strasse'] . "',
						'" . $_SESSION['r_plz'] . "',
						'" . $_SESSION['r_ort'] . "',
						'" . $_SESSION['r_land_lang'] . "',
						'" . $_SESSION['r_telefon'] . "',
						'" . $_SESSION['r_fax'] . "',
						'" . $_SESSION['r_email'] . "',
						'" . @$_SESSION['l_anrede'] . "',
						'" . @$_SESSION['l_vorname'] . "',
						'" . @$_SESSION['l_nachname'] . "',
						'" . @$_SESSION['l_strasse'] . "',
						'" . @$_SESSION['l_plz'] . "',
						'" . @$_SESSION['l_ort'] . "',
						'" . @$_SESSION['l_telefon'] . "',
						'" . @$_SESSION['l_fax'] . "',
						'" . @$_SESSION['l_land_lang'] . "',
						'" . @$_SESSION['l_firma'] . "',
						'" . @$_SESSION['gewicht'] ."',
						'" . @$_SESSION['coupon_val'] ."',
						'" . @$_SESSION['coupon_id'] ."',
						'" . addslashes( @$_SESSION['r_nachricht']) ."'
					)";
					
					$sql = $GLOBALS['db']->Query($q);
					$iid = $GLOBALS['db']->InsertId();
					
					$GLOBALS['tmpl']->assign('iid', $iid);
					$mail_content = $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/email_order_html.tpl');
					$mail_content = str_replace('"uploads/', '"' . thisHome() . '/uploads/', $mail_content);
					
					// Gutschein einloesen
					if(isset($_SESSION['coupon_id']) && !empty($_SESSION['coupon_id']))
					{
						$Update_Eingeloest = '';
						$GutscheinId = $_SESSION['coupon_id'];
						
					
						$row_c = $GLOBALS['db']->RowQuery("SELECT * FROM " . PREFIX . "_shop_gutscheine WHERE Id = '{$GutscheinId}'");
						if($row_c->Endlos != 1)
						{
							$Update_Benutzer = "Benutzer = '" . $_SESSION['benutzer_id'] . "'";
							$Update_Eingeloest = ",Eingeloest='" . stime() . "'";
							$Update_Bestellnummern = ",Bestellnummer = '" . $iid . "'";
						} else {
							$Update_Benutzer = "BenutzerMulti = CONCAT(BenutzerMulti, ',', '" . $_SESSION['benutzer_id'] . "') ";
							$Update_Bestellnummern = ",Bestellnummern = CONCAT(Bestellnummern, ',', '" . $iid . "') ";
						}
						
						$q_gs = "UPDATE " . PREFIX . "_shop_gutscheine SET {$Update_Benutzer}{$Update_Eingeloest}{$Update_Bestellnummern} WHERE Id = '{$GutscheinId}'";
						$GLOBALS['db']->RowQuery($q_gs);
						
					}
					$GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_bestellungen SET  Bestellung = '". base64_encode($mail_content) ."' WHERE Id = '$iid'");
					
					$Koobi = new Koobi;
					$shop_settings = $GLOBALS['db']->RowQuery("SELECT Subjekt_Best_Kopie,Email_Bestellung,Email_Abs,Name_Abs,Subjekt_Bestellung FROM " . PREFIX . "_shop_einstellungen");
					
					//=================================================================
					// Emails senden
					//=================================================================
					// Mail an Besteller
					$Koobi->koobi_mail($_SESSION['r_email'], $mail_content, $shop_settings->Subjekt_Bestellung, $shop_settings->Email_Abs, stripslashes($shop_settings->Name_Abs), "text", $att_ext, 1);		
					// Mail an Admin (Kopie)
					$Koobi->koobi_mail($shop_settings->Email_Bestellung, $mail_content, $shop_settings->Subjekt_Best_Kopie, $shop_settings->Email_Abs, stripslashes($shop_settings->Name_Abs), "text", $att_ext, 1);		
					// Mailanhang loeschen
					@unlink(BASE_DIR . '/attachments/' . $opref . $iid . '.pdf');
					
					// Details fuer Zahlungen
					$_SESSION['price_final'] = numf($_SESSION['price']);
					$_SESSION['order_number'] = $order_num;
					$_SESSION['shopstep'] = 'final';
					
					// Zahlung durchfuehren
					$ShopPayment = new ShopPayment;
					$ShopPayment->payment($ref_url);
					
				}
			break;
		}
	}
	
	function paymentInfo($id)
	{
		$Inf = $GLOBALS['db']->RowQuery("SELECT Icon,Beschreibung_" .  $_SESSION['Langcode'] . " AS Beschreibung, BeschreibungLang_" .  $_SESSION['Langcode'] . " AS BeschreibungLang, Name_" .  $_SESSION['Langcode'] . " AS Name FROM " . PREFIX . "_shop_zahlungsmethoden WHERE Id = '{$id}' AND Aktiv = 1");
		if(is_object($Inf)) 
		{
			$header = "<a href=\"index.php?p=shop\">" . $GLOBALS['config_vars']['Shop'] . "</a>" . $GLOBALS['config_vars']['PageSep'] . @$GLOBALS['config_vars']['Shop_payment_global_inf']  . ': ' . $Inf->Name;
			$GLOBALS['tmpl']->assign('payment_inf',$Inf);
			$GLOBALS['tmpl']->assign('headernav', $header);
			$GLOBALS['tmpl']->assign('pagetitle_html', clean_page_title($header));
			$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/payment_info.tpl'));
		}
	}
	
	function shopInfpage($where)
	{
		$Inf = $GLOBALS['db']->RowQuery("SELECT Widerruf,ShopAGB,ShopDatenschutz  FROM " . PREFIX . "_shop_einstellungen");
		$shop_settings_detail = $GLOBALS['db']->RowQuery("SELECT ShopAdresse FROM " . PREFIX . "_shop_einstellungen");
		
		switch($where)
		{	
			case 'agb':
				$text = $Inf->ShopAGB;
				$headerinf = $GLOBALS['config_vars']['Shop_agb'];
			break;
			
			case 'dataprotect':
				$text = '<h3>' . $GLOBALS['config_vars']['Shop_f_rcall_inf'] . '</h3><br /><br />' 
				. $Inf->Widerruf . '<hr noshade="noshade" size="1" /><h3>' 
				. $GLOBALS['config_vars']['Shop_infopageDataInf'] 
				. '</h3><br /><br />' . $Inf->ShopDatenschutz;
				
				$text = str_replace('%%SHOPADRESSE%%', $shop_settings_detail->ShopAdresse,$text);
				$headerinf = $GLOBALS['config_vars']['Shop_infopageRights'];
			break;
		}
		
		$header = "<a href=\"index.php?p=shop\">" . $GLOBALS['config_vars']['Shop'] . "</a>";
		$GLOBALS['tmpl']->assign('Text',$text);
		$GLOBALS['tmpl']->assign('headernav', $header);
		$GLOBALS['tmpl']->assign('InfHeader', $headerinf);
		$GLOBALS['tmpl']->assign('pagetitle_html', clean_page_title($GLOBALS['config_vars']['Shop']. ' - ' . $headerinf));
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/personal_inf.tpl'));
		
	}
	
	function unsetShopSessions()
	{
		unset($_SESSION['products']);
		unset($_SESSION['gewicht']);
		unset($_SESSION['price']);
		unset($_SESSION['price_netto']);
		unset($_SESSION['shopstep']);
		unset($_SESSION['payment_summ_extra']);
		unset($_SESSION['shipping_summ']);
		unset($_SESSION['step4_ok']);
		unset($_SESSION['step3_ok']);
		unset($_SESSION['step2_ok']);
		unset($_SESSION['step1_ok']);
		unset($_SESSION['shipper_id']);
		unset($_SESSION['payment_id']);
		unset($_SESSION['payment_summ_mipu']);
		unset($_SESSION['r_land_lang']);
		unset($_SESSION['diff_rl']);
		unset($_SESSION['l_land_lang']);
		unset($_SESSION['shipper_name']);
		unset($_SESSION['paymenForums_Username']);
		unset($_SESSION['payment_details']);
		unset($_SESSION['price_final']);
		unset($_SESSION['order_number']);
		unset($_SESSION['payment_summ_extra_symbol']);
		unset($_SESSION['shipping_details']);
		unset($_SESSION['order_number']);
		unset($_SESSION['print_coupon_price']);
		unset($_SESSION['coupon_code']);
		unset($_SESSION['coupon_id']);
		unset($_SESSION['coupon_val']);
		unset($_SESSION['coupon_typ']);
		unset($_SESSION['price_netto_coupon']);
		unset($_SESSION['price_netto_zwi']);
		unset($_SESSION['bank_name']);
		unset($_SESSION['bank_num']);
		unset($_SESSION['knt_num']);
		unset($_SESSION['knt_inh']);
		unset($_SESSION['DetailInfo']);
		unset($_SESSION['shipping_is_free']);
	}

	
	function shippingCosts($popup=0)
	{
		$Lc = $_SESSION['Langcode'];
		$shipper = array();
		$sql_shipper = $GLOBALS['db']->Query("SELECT *, Name_{$Lc} AS Name, Beschreibung_{$Lc} AS Beschreibung FROM " . PREFIX . "_shop_versandarten WHERE  Aktiv = '1' ORDER BY POSITION ASC");
		while($row_shipper = $sql_shipper->fetchrow())
		{
			$volumes = array();
			$sql_ft = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_versandarten_volumen WHERE VersandId = '" . $row_shipper->Id . "' ORDER BY VON ASC");
			while($row_ft = $sql_ft->fetchrow())
			{
				$row_ft->Von = explode(".",$row_ft->Von);
				$row_ft->Bis = explode(".",$row_ft->Bis);
				$row_ft->Von = $row_ft->Von[0];
				$row_ft->Bis = $row_ft->Bis[0];
				if($row_ft->Von=='0') $row_ft->Von = '';
				$row_ft->Gebuehr = $this->getPrice($row_ft->Gebuehr);
				array_push($volumes, $row_ft);
			}
			$row_shipper->Gebuehr_Pauschal = $this->getPrice($row_shipper->Gebuehr_Pauschal);
			$row_shipper->Volumes = $volumes;
			
			$Laender = explode(',', strtolower($row_shipper->Laender));
			foreach($Laender as $Land)
			{
				$row_shipper->Laenders .= $this->landCode($Land) . ' ';
			}
			
			array_push($shipper, $row_shipper);
		}
		
		$fs = $GLOBALS['shopsettings']->Versandfreibetrag;
		$shipping_free_inf = $GLOBALS['config_vars']['Shop_shipping_cost_inf2'];
		$shipping_free_inf = str_replace('%%FREESHIPPING%%', numformat($this->getPrice($fs)) . ' ' . KOOBI_CURRENCY_SYMBOL, $shipping_free_inf);

		$header = "<a href=\"index.php?p=shop\">" . $GLOBALS['config_vars']['Shop'] . "</a>" . $GLOBALS['config_vars']['PageSep'] . @$GLOBALS['config_vars']['Shop_shipping_cost'];
		$GLOBALS['tmpl']->assign('pagetitle_html', clean_page_title($header));
		$GLOBALS['tmpl']->assign('headernav', $header);
		$GLOBALS['tmpl']->assign('shipper', $shipper);
		$GLOBALS['tmpl']->assign('freeshipping', $fs);
		$GLOBALS['tmpl']->assign('popup', $popup);
		$GLOBALS['tmpl']->assign('freeshipping_inf2', $shipping_free_inf);
		$GLOBALS['tmpl']->assign('Inf_Footer',$GLOBALS['shopsettings']->VersandInfo_Footer);
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/shipping_cost.tpl'));
	}
	
	
	function KoobiReadFile($filename,$retbytes=true)
	{
	   $chunksize = 1*(1024*1024); 
	   $buffer = '';
	   $cnt =0;
	
	   $handle = fopen($filename, 'rb');
	   if ($handle === false)
	   {
		   return false;
	   }
	   while (!feof($handle))
	   {
		   $buffer = fread($handle, $chunksize);
		   echo $buffer;
		   flush();
		   if ($retbytes) {
			   $cnt += strlen($buffer);
		   }
	   }
		   $status = fclose($handle);
	   if ($retbytes && $status)
	   {
		   return $cnt; 
	   }
	   return $status;
	} 
	
	
	function myDownloads()
	{
		if($_SESSION['user_group'] == 2 || !get_active('shop_downloads')) :
			refer('index.php?p=shop');
			exit;
		endif;
		
		if(isset($_REQUEST['sub']) && $_REQUEST['sub'] != '')
		{
			switch($_REQUEST['sub']) 
			{
				case 'showfile':
					$download = false;
					$sql = $GLOBALS['db']->Query("SELECT 
								a.*, 
								b.Datei,
								b.Titel,
								b.Beschreibung 
							FROM 
								" . PREFIX . "_shop_downloads_user as a,
								" . PREFIX . "_shop_downloads as b  
							WHERE 
								a.ArtikelId = '" . @addslashes($_REQUEST['FileId']) . "' AND 
								a.Benutzer = '" . $_SESSION['benutzer_id'] . "' AND 
								((a.DownloadBis >= '" . time(). "') OR (b.DateiTyp='other') OR (b.DateiTyp='bugfix')) AND 
								(
									b.Id = '" . @addslashes($_REQUEST['getId']) . "' AND 
									b.ArtId = a.ArtikelId
								)
							");
					$row = $sql->fetchrow();
					
					if(!is_object($row))
					{
						refer("index.php?p=shop&action=mydownloads");
					}
					
					$num = $sql->numrows();
					if($num >= 1) $row->can_download = 1;
					$GLOBALS['tmpl']->assign('file', $row);
				break;
				
				case 'getfile':
				$error = '';
				$download = false;
				
				$q = "SELECT 
							a.*, 
							a.Id AS FileLogId,
							b.Datei 
						FROM 
							" . PREFIX . "_shop_downloads_user as a,
							" . PREFIX . "_shop_downloads as b  
						WHERE 
							a.ArtikelId = '" . @addslashes($_REQUEST['FileId']) . "' AND 
							a.Benutzer = '" . $_SESSION['benutzer_id'] . "' AND 
							((a.DownloadBis >= '" . time(). "') OR (b.DateiTyp='other') OR (b.DateiTyp='bugfix')) AND 
							a.Gesperrt != '1' AND 
							(
								b.Id = '" . @addslashes($_REQUEST['getId']) . "' AND
								b.ArtId = a.ArtikelId
							)";
				$sql = $GLOBALS['db']->Query($q);
				$row = $sql->fetchrow();
				$num = $sql->numrows();
				if($num >= 1) $download = true;
				
				if($download == true && (isset($_POST['agb_ok']) && $_POST['agb_ok']==1) )
				{
					$query_dl = $GLOBALS['db']->Query("UPDATE " . PREFIX . "_shop_downloads_user SET UrlLizenz = '" . @$_POST['UrlLizenz']. "', KommentarBenutzer = '" . @$_POST['KommentarBenutzer']. "' WHERE Benutzer = '" . $_SESSION['benutzer_id'] . "' AND ArtikelId = '" . $_POST['FileId'] . "' AND Id = '$row->FileLogId'");
					$query_dl = $GLOBALS['db']->Query("INSERT INTO " . PREFIX . "_shop_download_log 
					(
						Id, 
						Benutzer,
						Produkt,
						ProduktId,
						Datum,
						Ip,
						UrlLizenz,
						KommentarBenutzer
					) VALUES (
						'',
						'" . $_SESSION['benutzer_id'] . "',
						'" . $_POST['FileName'] . "',
						'" . @addslashes($_REQUEST['FileId']) . "',
						'" . time() . "',
						'" . $_SERVER['REMOTE_ADDR'] . "',
						'" . @$_POST['UrlLizenz'] . "',
						'" . @$_POST['KommentarBenutzer'] . "'
					)");
					
					#ob_start();
					header("Cache-control: private");
					header("Content-type: application/octet-stream"); 
					header("Content-disposition:attachment; filename=" . str_replace(array(' '), '', $row->Datei));
					@$this->KoobiReadFile(BASE_DIR . '/uploads/shop/files/' . $row->Datei);
					exit;
				} else {
					if(@$_POST['agb_ok']!=1) $error[] = $GLOBALS['config_vars']['Shop_DownloaAGBError'];
					if($row->UrlLizenz=='' && $row->UrlLizenz_Pflicht==1 && (empty($_POST['UrlLizenz']))) $error[] = $GLOBALS['config_vars']['Shop_DownloadURLError'];
					$GLOBALS['tmpl']->assign('error', $error);
				}
				break;
			}
			// Ende Download
		}
		
		
		$Lc = $_SESSION['Langcode'];
		//=================================================================
		// Anfrage Download
		//=================================================================
		
		
		//=================================================================
		// Downloads listen
		//=================================================================
		$downloads = array();
		$sql = $GLOBALS['db']->Query("SELECT 	
				a.*,
				b.Id as ARTIKELNUMMER, 
				b.Titel_{$Lc} AS ArtName 
			FROM 
				" . PREFIX . "_shop_downloads_user as a,
				" . PREFIX . "_shop_produkte as b 
			WHERE 
				a.Benutzer = '" . $_SESSION['benutzer_id'] . "' AND 
				a.Benutzer != '0' AND 
				b.Id = a.ArtikelId 
			ORDER BY
				a.Position ASC");
			
			while($row = $sql->fetchrow())
			{
				if(is_object($row))
				{
					// Vollversionen
					$DataFiles = array();
					$sql_df = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_downloads WHERE ArtId = '$row->ARTIKELNUMMER' AND DateiTyp='full' ORDER BY Position ASC,Id DESC");
					while($row_df = $sql_df->fetchrow())
					{
						if($row->DownloadBis < time())
						{
							$row_df->Abgelaufen = 1;
							
						}
						$row_df->Beschreibung = str_replace('"','&quot;',$row_df->Beschreibung);
						$row_df->size = (file_exists(BASE_DIR . '/uploads/shop/files/' . $row_df->Datei) ) ? round(@filesize(BASE_DIR . '/uploads/shop/files/'.$row_df->Datei)/1024,2) : '';
						array_push($DataFiles, $row_df);
					}
					$row->DataFiles = $DataFiles;
					
					// Updates
					$DataFilesUpdates = array();
					$sql_df = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_downloads WHERE ArtId = '$row->ARTIKELNUMMER' AND DateiTyp='update' ORDER BY Position ASC");
					while($row_df = $sql_df->fetchrow())
					{
						if($row->DownloadBis < time())
						{
							$row_df->Abgelaufen = 1;
						}
						
						$row_df->Beschreibung = str_replace('"','&quot;',$row_df->Beschreibung);
						$row_df->size = (file_exists(BASE_DIR . '/uploads/shop/files/' . $row_df->Datei) ) ? round(@filesize(BASE_DIR . '/uploads/shop/files/'.$row_df->Datei)/1024,2) : '';
						array_push($DataFilesUpdates, $row_df);
					}
					$row->DataFilesUpdates = $DataFilesUpdates;
					
					// Sonstiges
					$DataFilesOther = array();
					$sql_df = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_downloads WHERE ArtId = '$row->ARTIKELNUMMER' AND DateiTyp='other' ORDER BY Position ASC");
					while($row_df = $sql_df->fetchrow())
					{
						$row_df->Beschreibung = str_replace('"','&quot;',$row_df->Beschreibung);
						$row_df->size = (file_exists(BASE_DIR . '/uploads/shop/files/' . $row_df->Datei) ) ? round(@filesize(BASE_DIR . '/uploads/shop/files/'.$row_df->Datei)/1024,2) : '';
						array_push($DataFilesOther, $row_df);
					}
					$row->DataFilesOther = $DataFilesOther;
					
					// Bugfixes
					$DataFilesBugfixes = array();
					$sql_df = $GLOBALS['db']->Query("SELECT * FROM " . PREFIX . "_shop_downloads WHERE ArtId = '$row->ARTIKELNUMMER' AND DateiTyp='bugfix' ORDER BY Position ASC");
					while($row_df = $sql_df->fetchrow()) 
					{
						$row_df->Beschreibung = str_replace('"','&quot;',$row_df->Beschreibung);
						$row_df->size = (file_exists(BASE_DIR . '/uploads/shop/files/' . $row_df->Datei) ) ? round(@filesize(BASE_DIR . '/uploads/shop/files/'.$row_df->Datei)/1024,2) : '';
						array_push($DataFilesBugfixes, $row_df);
					}
					$row->DataFilesBugfixes = $DataFilesBugfixes;
				}
				
				
				array_push($downloads, $row);
			}
			
			$GLOBALS['tmpl']->assign('downloads', $downloads);
		
		//=================================================================
		// Seite ausgeben
		//=================================================================
		$GLOBALS['tmpl']->assign('headernav', '<a href="index.php?p=shop">' . $GLOBALS['config_vars']['Shop'] . '</a>' .  $GLOBALS['config_vars']['PageSep'] . '<a href="index.php?p=shop&action=mydownloads">' . $GLOBALS['config_vars']['Shop_go_mydownloads'] . '</a>');
		$GLOBALS['tmpl']->assign('pagetitle_html', $GLOBALS['config_vars']['Shop'] . $GLOBALS['config_vars']['PageSep'] . $GLOBALS['config_vars']['Shop_go_mydownloads']);
		$GLOBALS['tmpl']->assign('content', $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/my_downloads.tpl'));
	}
	
	function getInfoPanel()
	{
		$out = $GLOBALS['tmpl']->fetch($GLOBALS['config']['source'] . '/shop/infopanel.tpl');
		return $out;
	}
	
	function landCode($code)
	{
		$land = (!@empty($GLOBALS['config_vars']['Country_' . $code])) ? $GLOBALS['config_vars']['Country_' . $code] : strtoupper($code);
		return $land;
	}
}
?>