<?php

	/**
	 * Dieses Modul erlaubt verschiedene Produktvariationen
	 */
	class wpsg_mod_varianten extends wpsg_mod_basic
	{
		
		var $cache_variData;
		
		var $lizenz = 1;
		var $id = 98;
		var $hilfeURL = 'http://wpshopgermany.de/?p=1057';
						
		/**
		 * Costructor
		 */
		public function __construct()
		{
			
			parent::__construct();
			
			$this->name = __('Varianten', 'wpsg');
			$this->group = __('Produkte', 'wpsg');
			$this->desc = __('Ermöglicht verschiedene Produktvariationen.', 'wpsg');

			$this->cache_variData = array();
			
		} // public function __construct()
		
		public function install()
		{
			
			require_once(WPSG_PATH_WP.'/wp-admin/includes/upgrade.php');

			/**
			 * Produkttabelle erweitern
			 */
			$sql = "CREATE TABLE ".WPSG_TBL_PRODUCTS." (
			  	mod_varianten mediumtext NOT NULL
			) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;";
			
			dbDelta($sql);
			
			$this->shop->checkDefault('wpsg_vp_imageselect_width', 25);
			$this->shop->checkDefault('wpsg_vp_imageselect_height', 25);
			$this->shop->checkDefault('wpsg_vp_imageselect_mode', 'cz');
			
		} // public function install()
		
		public function wp_loaded()
		{
			
			if (wpsg_isSizedString($_REQUEST['action'], 'wpsg_varianten_switch'))
			{
				
				if (wpsg_isSizedInt($_REQUEST['wpsg_post_id']))
				{
					
					global $post;
					$post = get_post($_REQUEST['wpsg_post_id']);
										
				}
				
				$product_key = $_REQUEST['product_key'];
				$product_id = $this->shop->getProduktId($product_key);
				
				$product_data = $this->shop->loadProduktArray($product_id, array(
					'id' => $product_key, 
					'menge' => $_REQUEST['quantity'],
					'referer' => $_REQUEST['referer']
				));				
				 
				// Damit das Div die gleiche Index Id bekommt
				$GLOBALS['wpsg_produkt_index'] = $_REQUEST['product_index'] - 1;
				
				$this->shop->noReleatedProducts = true;
								
				if (wpsg_isSizedString($_REQUEST['template'])) $template = $_REQUEST['template'];
				else $template = false;
				
				die($this->shop->renderProdukt($product_data, $template));
								
			}
			
		} // public function wp_loaded()
		
		public function loadProduktArray(&$produkt_data) 
		{
	 
			if (!$this->isVariantsProductKey($produkt_data['id'])) return;
			 
			$arVari = $this->loadVarianten($this->shop->getProduktId($produkt_data['id']));
			$product_id = $this->shop->getProduktId($produkt_data['id']);
			
			$produkt_data['preis_original'] = $produkt_data['preis'];
			
			$mwst_value = $this->shop->getCalcTaxValue($produkt_data['mwst_key']); 
			 
			/* Gesamtpreis */
			if ($this->shop->get_option('wpsg_preisangaben') == WPSG_NETTO) $preis = $produkt_data['preis_defaultLand_netto'];
			else $preis = $produkt_data['preis_defaultLand_brutto']; 
				
			$arVarSelected = $this->getSetVariArray($produkt_data['id']);
			$arVarDatabase = $this->loadVarianten($this->shop->getProduktId($produkt_data['id']), true);
					
			foreach ($arVarSelected as $var => $vari)
			{
					
				
				if ($arVarDatabase[$var]['typ'] == 'checkbox' && $vari == '1')
				{
		
					// Aktivierte Checkbox
					$preis += wpsg_tf($arVarDatabase[$var]['preis']);
								
				}
				else
				{
		 
					// Select, Radio
					$preis += wpsg_tf($arVarDatabase[$var]['vari'][$vari]['preis']);
		
				}
					
			}
			
			// Preis umrechnen für Standardland
			if ($this->shop->get_option('wpsg_preisangaben') == WPSG_NETTO)
			{
				
				// Preisangaben im Backend in Netto -> Brutto berechnen
				$produkt_data['preis_brutto'] = wpsg_calculatePreis($preis, WPSG_BRUTTO, $mwst_value);
				$produkt_data['preis_netto'] = $preis;
				
			}
			else
			{
				
				// Preis im Backend ist in Brutto
				$produkt_data['preis_brutto'] = $preis;
				$produkt_data['preis_netto'] = wpsg_calculatePreis($preis, WPSG_NETTO, $mwst_value);
				
			}

			$produkt_data['preis_defaultLand_brutto'] = $produkt_data['preis_brutto'];
			$produkt_data['preis_defaultLand_netto'] = $produkt_data['preis_netto'];
			
			// Jetzt habe ich Netto/Brutto Werte im Standardland
			// Wenn es jetzt ein Leistungsort Produkt ist, dann muss ich die Steuer des Ziellandes bestimmen
			if (wpsg_isSizedInt($produkt_data['euleistungsortregel']) && $this->shop->getDefaultCountry(true) != $this->shop->getFrontendCountry(true))
			{
			
				$oFrontendCountry = $this->shop->getFrontendCountry();
			
				$produkt_data['mwst_value'] = $oFrontendCountry->getTax($produkt_data['mwst_key']);
				$produkt_data['preis_brutto'] = wpsg_calculatePreis($produkt_data['preis_netto'], WPSG_BRUTTO, $produkt_data['mwst_value']);
			
			}
			 
			if ($this->shop->getFrontendTaxview() == WPSG_BRUTTO) $produkt_data['preis'] = $produkt_data['preis_brutto'];
			else $produkt_data['preis'] = $produkt_data['preis_netto'];
						
			// Mindest- und Maximalpreis hinzufügen			
			$bMinPrice = wpsg_tf($produkt_data['preis_original']);
			$bMaxPrice = wpsg_tf($produkt_data['preis_original']);
			 
			if ($this->shop->hasMod('wpsg_mod_weight'))
			{
				
				$bMinWeight = wpsg_tf($produkt_data['weight']);
				$bMaxWeight = wpsg_tf($produkt_data['weight']);
				
			}
			
			foreach ($arVari as $k => $v)
			{

				if ($v['aktiv'] == '1')
				{
				 
					if ($v['typ'] == 'checkbox')
					{
						
						// Hier muss ich beim Min Preis nix tun, wenn nicht angehakt dann wird nix addiert
						$bMaxPrice += wpsg_tf($v['preis']);
						
						if ($this->shop->hasMod('wpsg_mod_weight'))
						{
							
							!isset ($v['weight']) or $bMaxWeight += wpsg_tf($v['weight']);
							
						}
						
						// Preis der Variante an die Ausgabe im Frontend anpassen
						// if ($this->shop->getFrontendTaxview() == WPSG_NETTO && $this->shop->getBackendTaxview() == WPSG_BRUTTO) $arVari[$k]['preis'] = wpsg_calculatePreis($v['preis'], WPSG_NETTO, $mwst_value);
						
					}
					else
					{	
							
						$bMinPriceVari = false;
						$bMaxPriceVari = false;
						
						if ($this->shop->hasMod('wpsg_mod_weight'))
						{
							
							$bMinWeightVari = false;
							$bMaxWeightVari = false;
							
						}
						
						foreach ($v['vari'] as $k2 => $v2)
						{
							
							if ($v2['aktiv'] == '1')
							{
								
								if ($bMinPriceVari === false || wpsg_tf($v2['preis']) < $bMinPriceVari) $bMinPriceVari = wpsg_tf($v2['preis']);
								if ($bMaxPriceVari === false || wpsg_tf($v2['preis']) > $bMaxPriceVari) $bMaxPriceVari = wpsg_tf($v2['preis']);
								
								if ($this->shop->hasMod('wpsg_mod_weight'))
								{
									
									if ($bMinWeightVari === false || !isset ($v['weight']) or wpsg_tf($v2['weight']) < $bMinWeightVari) $bMinWeightVari = !isset ($v['weight']) or wpsg_tf($v2['weight']);
									if ($bMaxWeightVari === false || !isset ($v['weight']) or wpsg_tf($v2['weight']) > $bMaxWeightVari) $bMaxWeightVari = !isset ($v['weight']) or wpsg_tf($v2['weight']);
									
								}
								
							}
							
							// Preis der Variante an die Ausgabe im Frontend anpassen
							// if ($this->shop->getFrontendTaxview() == WPSG_NETTO && $this->shop->getBackendTaxview() == WPSG_BRUTTO) $arVari[$k]['vari'][$k2]['preis'] = wpsg_calculatePreis($v2['preis'], WPSG_NETTO, $mwst_value);
														
						}

						if ($bMinPriceVari !== false) $bMinPrice += $bMinPriceVari;
						if ($bMaxPriceVari !== false) $bMaxPrice += $bMaxPriceVari;
						
						if ($this->shop->hasMod('wpsg_mod_weight'))
						{
							
							if ($bMinWeightVari !== false) $bMinWeight += $bMinWeightVari;
							if ($bMaxWeightVari !== false) $bMaxWeight += $bMaxWeightVari;
							
						}						
						
					}
					
				}
				
			}
			 
			$produkt_data['min_preis'] = wpsg_tf($bMinPrice);
			$produkt_data['max_preis'] = wpsg_tf($bMaxPrice);
			
			if ($this->shop->hasMod('wpsg_mod_weight'))
			{
				
				$produkt_data['min_weight'] = wpsg_tf($bMinWeight);
				$produkt_data['max_weight'] = wpsg_tf($bMaxWeight);
				
			}
			
			/* Eventuell Variantenbild */
			if ($this->shop->hasMod('wpsg_mod_produktbilder'))
			{
				
				$arImages = $this->getKombiVariImages($produkt_data['id']);
				
				if (wpsg_isSizedArray($arImages))
				{
					
					$image = $arImages[array_rand($arImages)];
					
					$produkt_data['varianten_image'] = $image;
					
				}
				
			}
			
		} // public function loadProduktArray(&$produkt_data) 
		
		public function produkt_ajax()
		{
			
			//error_reporting(E_ALL);
			
			if (isset($_REQUEST['cmd']) && $_REQUEST['cmd'] == 'wpsg_vp_add')
			{
				 
				$vp_data = $this->loadVarianten($_REQUEST['edit_id']);
				
				$data = array(
					"name" => $_REQUEST['name'],
					"typ" => $_REQUEST['typ'],
					"aktiv" => "1"
				);
				
				if ($_REQUEST['typ'] == "checkbox")
				{
					$data['preis'] = "0";
				}
				else
				{
					$data['vari'] = array();
				}
				
				$vp_data[] = $data;
				
				$this->saveVarianten($_REQUEST['edit_id'], $vp_data);
				
				$this->shop->view['message'] = array(0, __("Variante erfolgreich angelegt.", "wpsg"));
				
				die($this->drawVarianten($_REQUEST['edit_id']));
				
			}
			else if ($_REQUEST['cmd'] == 'wpsg_var_reorder')
			{
				
				parse_str($_REQUEST['wpsg_reorder'], $wpsg_reorder);
				
				$vp_data = $this->loadVarianten($_REQUEST['edit_id']);
				$vp_data_neu = array();
				 				
				foreach ($wpsg_reorder['variante'] as $order)
				{
					
					if (array_key_exists($order, $vp_data))
					{
						
						$vp_data_neu[] = $vp_data[$order];
						unset($vp_data[$order]);
						
					}
					else
					{
						
						$this->shop->throwErrorCode('98_1');
						
					}
					
				}
				
				if (wpsg_isSizedArray($vp_data))
				{
						
					$this->shop->throwErrorCode('98_2');
						
				}
				
				$this->saveVarianten($_REQUEST['edit_id'], $vp_data_neu);
												
				$this->shop->view['message'] = array(0, __('Variantenreihenfolge gespeichert.', 'wpsg'));
				
				die($this->drawVarianten($_REQUEST['edit_id']));
				
			}
			else if ($_REQUEST['cmd'] == 'wpsg_vari_reorder')
			{
				
				parse_str($_REQUEST['wpsg_reorder'], $wpsg_reorder);
				
				$vp_data = $this->loadVarianten($_REQUEST['edit_id']);
				 
				foreach ($wpsg_reorder as $var_key => $order)
				{
					
					$var_id = preg_replace('/^variorder\_/', '', $var_key);
					   
					wpsg_array_reorder($vp_data[$var_id]['vari'], $order);
					
					if (wpsg_isSizedArray($vp_data[$var_id]['lang']))
					{
						
						foreach ($vp_data[$var_id]['lang'] as $lang_key => $lang_vari)
						{
							
							wpsg_array_reorder($vp_data[$var_id]['lang'][$lang_key]['vari'], $order);
							
						}
						
					}
					
				}

				$this->saveVarianten($_REQUEST['edit_id'], $vp_data);
				
				$this->shop->view['message'] = array(0, __("Variationenreihenfolge gespeichert.", "wpsg"));
				
				die($this->drawVarianten($_REQUEST['edit_id']));
				
			}
			else if ($_REQUEST['cmd'] == 'wpsg_vp_refreh')
			{
				
				die($this->drawVarianten($_REQUEST['edit_id']));
				
			}
			else if ($_REQUEST['cmd'] == "wpsg_vp_del")
			{
				
				$vp_data = $this->loadVarianten($_REQUEST['edit_id']);
				
				unset($vp_data[$_REQUEST['var_id']]);
				
				$this->saveVarianten($_REQUEST['edit_id'], $vp_data);
				
				$this->shop->view['message'] = array(0, __("Variante wurde erfolgreich gelöscht.", "wpsg"));				
				die($this->drawVarianten($_REQUEST['edit_id']));
				
			}
			else if ($_REQUEST['cmd'] == "wpsg_vp_deaktiv")
			{
 	
				$vp_data = $this->loadVarianten($_REQUEST['edit_id']);
				
				if ($_REQUEST['status'] == "1")
				{
					
					$vp_data[$_REQUEST['var_id']]['aktiv'] = 1;
					$this->shop->view['message'] = array(0, __("Variante wurde erfolgreich aktiviert.", "wpsg"));
						
				}
				else
				{
					
					$vp_data[$_REQUEST['var_id']]['aktiv'] = 0;
					$this->shop->view['message'] = array(0, __("Variante wurde erfolgreich deaktiviert.", "wpsg"));
					
				}
				
				$this->saveVarianten($_REQUEST['edit_id'], $vp_data); 				
				die($this->drawVarianten($_REQUEST['edit_id']));				
				
			}
			else if ($_REQUEST['cmd'] == "wpsg_vp_addVariation")
			{
				
				$vp_data = $this->loadVarianten($_REQUEST['edit_id']);
				
				$vp_data[$_REQUEST['var_id']]['vari'][] = array(
					"name" => $_REQUEST['vari_name'],
					"preis" => wpsg_tf($_REQUEST['vari_preis']),
					"aktiv" => "1"
				);
				
				$this->shop->view['message'] = array(0, __("Variation wurde erfolgreich angelegt.", "wpsg"));
				
				$this->saveVarianten($_REQUEST['edit_id'], $vp_data);
				die($this->drawVarianten($_REQUEST['edit_id']));
				
			}
			else if ($_REQUEST['cmd'] == "wpsg_vp_vari_del")
			{
				
				$vp_data = $this->loadVarianten($_REQUEST['edit_id']);
				
				unset($vp_data[$_REQUEST['var_id']]['vari'][$_REQUEST['vari_id']]);				
				
				if (wpsg_isSizedArray($vp_data[$_REQUEST['var_id']]['lang']))
				{
						
					foreach ($vp_data[$_REQUEST['var_id']]['lang'] as $lang_key => $lang_vari)						
					{
						
						unset($vp_data[$_REQUEST['var_id']]['lang'][$lang_key]['vari'][$_REQUEST['vari_id']]);
						
					}
			
				}
				
				$this->shop->view['message'] = array(0, __("Variation wurde erfolgreich gelöscht.", "wpsg"));
				
				$this->saveVarianten($_REQUEST['edit_id'], $vp_data);
				die($this->drawVarianten($_REQUEST['edit_id']));
				
			}
			else if ($_REQUEST['cmd'] == "wpsg_vp_vari_deaktiv")
			{
				
				$vp_data = $this->loadVarianten($_REQUEST['edit_id']);
				
				if ($_REQUEST['status'] == "1")
				{
					
					$vp_data[$_REQUEST['var_id']]['vari'][$_REQUEST['vari_id']]['aktiv'] = 1;
					$this->shop->view['message'] = array(0, __("Variation wurde erfolgreich aktiviert.", "wpsg"));
						
				}
				else
				{
					
					$vp_data[$_REQUEST['var_id']]['vari'][$_REQUEST['vari_id']]['aktiv'] = 0;
					$this->shop->view['message'] = array(0, __("Variation wurde erfolgreich deaktiviert.", "wpsg"));
					
				}
				
				$this->saveVarianten($_REQUEST['edit_id'], $vp_data);
				die($this->drawVarianten($_REQUEST['edit_id']));
				
			}
			else if ($_REQUEST['cmd'] == 'wpsg_var_setImageOrder')
			{
				
				$vp_data = $this->loadVarianten($_REQUEST['edit_id']);
				
				if ($_REQUEST['vari_id'] == -1)
				{
					
					$vp_data[$_REQUEST['var_id']]['picOrder'] = $_REQUEST['wpsg_reorder'];
					
				}
				else 
				{
				
					$vp_data[$_REQUEST['var_id']]['vari'][$_REQUEST['vari_id']]['picOrder'] = $_REQUEST['wpsg_reorder'];
					
				}
				 
				$this->saveVarianten($_REQUEST['edit_id'], $vp_data);
				
				die("1");
				
			}
			else if ($_REQUEST['cmd'] == 'wpsg_vp_vari_setPic')
			{
								
				$vp_data = $this->loadVarianten($_REQUEST['edit_id']);
				
				if ($_REQUEST['vari_id'] >= 0)
				{
					
					$arPic = explode(",", $vp_data[$_REQUEST['var_id']]['vari'][$_REQUEST['vari_id']]['pic']);
					
					if (in_array($_REQUEST['pic'], $arPic))
					{
						unset($arPic[array_search($_REQUEST['pic'], $arPic)]);
					}
					else
					{
						$arPic[] = $_REQUEST['pic'];
					}
					
					$vp_data[$_REQUEST['var_id']]['vari'][$_REQUEST['vari_id']]['pic'] = implode(",", $arPic);
					
				}
				else
				{
					
					$arPic = explode(",", $vp_data[$_REQUEST['var_id']]['pic']);
					
					if (in_array($_REQUEST['pic'], $arPic))
					{
						unset($arPic[array_search($_REQUEST['pic'], $arPic)]);
					}
					else
					{
						$arPic[] = $_REQUEST['pic'];
					}
					
					$vp_data[$_REQUEST['var_id']]['pic'] = implode(",", $arPic);
						
				}
				
				$this->saveVarianten($_REQUEST['edit_id'], $vp_data);
				
				die("1");
				
			}
			else if ($_REQUEST['cmd'] == 'wpsg_vp_vari_inlineEdit')
			{
				
								
				$vp_data = $this->loadVarianten($_REQUEST['edit_id']);
				$product_data = $this->shop->cache->loadProduct($_REQUEST['edit_id']);
				 
				if ($_REQUEST['typ'] == "vari_name") 
				{
					
					if (wpsg_isSizedString($_REQUEST['wpsg_lang']))
					{
						$vp_data[$_REQUEST['var_id']]['lang'][$_REQUEST['wpsg_lang']]['vari'][$_REQUEST['vari_id']]['name'] = wpsg_q($_REQUEST['value']);	
					}
					else
					{					
						$vp_data[$_REQUEST['var_id']]['vari'][$_REQUEST['vari_id']]['name'] = wpsg_q($_REQUEST['value']);
					}
					
				}				
				else if ($_REQUEST['typ'] == "vari_artnr") 
				{
					
					if (wpsg_isSizedString($_REQUEST['wpsg_lang']))
					{
						$vp_data[$_REQUEST['var_id']]['lang'][$_REQUEST['wpsg_lang']]['vari'][$_REQUEST['vari_id']]['artnr'] = wpsg_q($_REQUEST['value']);	
					}
					else
					{
						$vp_data[$_REQUEST['var_id']]['vari'][$_REQUEST['vari_id']]['artnr'] = wpsg_q($_REQUEST['value']);
					}
					
				}
				else if ($_REQUEST['typ'] == "vari_preis")
				{
					
					$_REQUEST['value'] = wpsg_tf($_REQUEST['value']);
					$vp_data[$_REQUEST['var_id']]['vari'][$_REQUEST['vari_id']]['preis'] = $_REQUEST['value'];
					$_REQUEST['value'] = wpsg_ff($_REQUEST['value'], $this->shop->get_option('wpsg_currency'));
					
				}
				else if ($_REQUEST['typ'] == "vari_fmenge")
				{
						
					$arFeinheiten = explode(',', $this->shop->get_option('wpsg_mod_fuellmenge_einheit'));
					
					$_REQUEST['value'] = wpsg_ff(wpsg_tf($_REQUEST['value']), $arFeinheiten[$product_data['feinheit']]);
					$vp_data[$_REQUEST['var_id']]['vari'][$_REQUEST['vari_id']]['fmenge'] = wpsg_tf($_REQUEST['value']);
						
				}
				else if ($_REQUEST['typ'] == "vari_weight")
				{
					
					$_REQUEST['value'] = wpsg_tf($_REQUEST['value']);
					$vp_data[$_REQUEST['var_id']]['vari'][$_REQUEST['vari_id']]['weight'] = $_REQUEST['value'];
										
				}
				else if ($_REQUEST['typ'] == "vari_stock")
				{
		 
					$_REQUEST['value'] = intval($_REQUEST['value']);
					$vp_data[$_REQUEST['var_id']]['vari'][$_REQUEST['vari_id']]['stock'] = $_REQUEST['value'];
		 			
				}
				else if ($_REQUEST['typ'] == "var_name")
				{
					
					if (wpsg_isSizedString($_REQUEST['wpsg_lang']))
					{
						$vp_data[$_REQUEST['var_id']]['lang'][$_REQUEST['wpsg_lang']]['name'] = $_REQUEST['value'];	
					}
					else
					{
						$vp_data[$_REQUEST['var_id']]['name'] = $_REQUEST['value'];
					}
						
				}
				else if ($_REQUEST['typ'] == "var_preis")
				{
					
					$_REQUEST['value'] = wpsg_tf($_REQUEST['value']);
					$vp_data[$_REQUEST['var_id']]['preis'] = $_REQUEST['value'];
					$_REQUEST['value'] = wpsg_ff($_REQUEST['value'], $this->shop->get_option('wpsg_currency'));
					
				}
				else if ($_REQUEST['typ'] == "var_weight")
				{
					 
					$_REQUEST['value'] = wpsg_tf($_REQUEST['value']);
					$vp_data[$_REQUEST['var_id']]['weight'] = $_REQUEST['value'];
					
				}
				else if ($_REQUEST['typ'] == "var_fmenge")
				{
					
					$arFeinheiten = explode(',', $this->shop->get_option('wpsg_mod_fuellmenge_einheit'));
						
					$_REQUEST['value'] = wpsg_ff(wpsg_tf($_REQUEST['value']), $arFeinheiten[$product_data['feinheit']]);
					$vp_data[$_REQUEST['var_id']]['fmenge'] = wpsg_tf($_REQUEST['value']);
					
				}
				else if ($_REQUEST['typ'] == "var_artnr")
				{
					
					if (wpsg_isSizedString($_REQUEST['wpsg_lang']))
					{
						$vp_data[$_REQUEST['var_id']]['lang'][$_REQUEST['wpsg_lang']]['artnr'] = wpsg_q($_REQUEST['value']);	
					}
					else
					{
						$vp_data[$_REQUEST['var_id']]['artnr'] = wpsg_q($_REQUEST['value']);
					}
					
				}
				else if ($_REQUEST['typ'] == "var_stock")
				{
	 
					$_REQUEST['value'] = intval($_REQUEST['value']);
					$vp_data[$_REQUEST['var_id']]['stock'] = $_REQUEST['value'];
					
				}
				
				$this->saveVarianten($_REQUEST['edit_id'], $vp_data);
				
				die(strval($_REQUEST['value']));
				
			}
			
		} // public function produkt_ajax()
		
		public function settings_save()
		{
			
			$this->shop->update_option('wpsg_vp_showpic', $_REQUEST['wpsg_vp_showpic']);
			$this->shop->update_option('wpsg_vp_detailview', $_REQUEST['wpsg_vp_detailview']);
			$this->shop->update_option('wpsg_vp_showpic_width', $_REQUEST['wpsg_vp_showpic_width']);
			$this->shop->update_option('wpsg_vp_showpic_height', $_REQUEST['wpsg_vp_showpic_height']);
			$this->shop->update_option('wpsg_vp_replaceanr', $_REQUEST['wpsg_vp_replaceanr']);
			$this->shop->update_option('wpsg_vp_imageselect_width', $_REQUEST['wpsg_vp_imageselect_width']);
			$this->shop->update_option('wpsg_vp_imageselect_height', $_REQUEST['wpsg_vp_imageselect_height']);
			$this->shop->update_option('wpsg_vp_imageselect_mode', $_REQUEST['wpsg_vp_imageselect_mode']);
			
		} // public function settings_save()
		
		public function settings_edit()
		{
			
			return $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_varianten/settings_edit.phtml');
			
		} // public function settings_edit()
				
		public function produkt_edit_content(&$produkt_data) 
		{ 
			
			if (wpsg_isSizedString($_REQUEST['wpsg_lang']))
			{
				
				// Für die Varianten brauche ich immer das original Array ...
				$produkt_data['id'] = $this->db->fetchOne("SELECT `lang_parent` FROM `".WPSG_TBL_PRODUCTS."` WHERE `id` = '".wpsg_q($produkt_data['id'])."'");				
				
			}
			
			$this->shop->view['wpsg_mod_varianten']['data'] = $produkt_data;
			 			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_varianten/produkt_edit_content.phtml');	
			
		} // public function produkt_edit_content(&$produkt_data)
		
		public function produkt_edit_afterForm(&$product_id) { }
		
		public function wpsg_enqueue_scripts()
		{
			
			if (!is_admin())
			{
							
				wp_enqueue_script('wpsg_mod_varianten_js', $this->shop->getRessourceURL('mods/mod_varianten/varianten.js'));
				
				wp_localize_script('wpsg_mod_varianten_js', 'wpsg_vp_showpic', array('wpsg_vp_showpic' => $this->shop->get_option('wpsg_vp_showpic')));
				
			}
			
		} // public function wpsg_enqueue_scripts()
		
		public function basket_preInsert()
		{

			if (is_array($_REQUEST['wpsg_vp']) && sizeof($_REQUEST['wpsg_vp']) > 0)
			{
								
				$var_key = 'vp_'.$_REQUEST['wpsg']['produkt_id'].'/';
				
				foreach ($_REQUEST['wpsg_vp'] as $var => $var_value)
				{
					
					$var_key .= $var."_".$var_value.":";
					
				}
				
				$var_key = substr($var_key, 0, -1);

				$_REQUEST['wpsg']['produkt_id'] = $var_key;
				
			}
			
		} // public function basket_preInsert()
				 		
		public function getProductAnr($product_key, &$anr) 
		{ 

			if ($this->isVariantsProductKey($product_key) && wpsg_isSizedInt($this->shop->get_option('wpsg_vp_replaceanr')))
			{

				$arVariantenInfo = $this->getVariantenInfoArray($product_key);
				
				$anr = $arVariantenInfo['akey'];
				
				// Artikelnummer gebildet, keine weiteren Module betrachten
				return -2;
				
			}
			
		} // public function getProductAnr($product_key, &$anr)
				
		public function basket_row(&$p, $i) 
		{ 
			
			if (!preg_match('/vp_(.*)/', $p['id'])) return;
			
			$this->shop->view['variante'] = $this->getVariantenInfoArray($p['id']);
			
			$this->shop->view['i'] = $i;
			
			$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_varianten/basket_row.phtml');
			
		} // public function basket_row(&$p)
		
		public function overview_row(&$p, $i)
		{
			
			if (!preg_match('/vp_(.*)/', $p['id'])) return;
			
			$this->shop->view['variante'] = $this->getVariantenInfoArray($p['id']);
			$this->shop->view['i'] = $i;
			
			return $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_varianten/overview_row.phtml');
			
		} // public function overview_row(&$p, $i)
		
		public function order_view_row(&$p, $i) 
		{ 
			
			if (!preg_match('/vp_(.*)/', $p['id'])) return;
			
			$this->shop->view['variante'] = $this->getVariantenInfoArray($p['id']);
			$this->shop->view['i'] = $i;
			
			return $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_varianten/order_view_row.phtml');
			
		} // public function order_view_row(&$p)
				
		public function mail_row($index, $produkt)
		{
			
			if (preg_match('/vp_(.*)/', $produkt['id']))
			{
			
				$this->shop->view['produkt'] = $produkt;
				$this->shop->view['variante'] = $this->getVariantenInfoArray($produkt['id']);
			
				if ($this->shop->htmlMail === true)
				{
				
					$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_varianten/mail_row_html.phtml');
					
				}
				else
				{
					
					$this->shop->render(WPSG_PATH_VIEW.'/mods/mod_varianten/mail_row.phtml');
				
				}
			
			}
			
		} // public function mail_row($index, $produkt)
		
		public function admin_presentation() 
		{ 
			
			echo wpsg_drawForm_Select('wpsg_mod_varianten_showvariprice', __('Variantenpreis im Produkttemplate anzeigen', 'wpsg'), array(
				'0' => __('immer anzeigen', 'wpsg'),
				'1' => __('nur wenn größer 0', 'wpsg'),
				'2' => __('nie anzeigen', 'wpsg')
			), $this->shop->get_option('wpsg_mod_varianten_showvariprice'));
			
		} // public function admin_presentation()
		
		public function admin_presentation_submit() 
		{ 
			
			$this->shop->update_option('wpsg_mod_varianten_showvariprice', $_REQUEST['wpsg_mod_varianten_showvariprice']);	
			
		} // public function admin_presentation_submit()
		
		public function wpsg_mod_export_loadFields(&$arFields) 
		{ 

			$arFields[20]['fields']['product_vname'] = __('Name der Variante', 'wpsg');
			$arFields[20]['fields']['product_vanr'] = __('Artikelnummer der Variante', 'wpsg');
			
		} // public function wpsg_mod_export_loadFields(&$arFields) 
		
		public function wpsg_mod_export_getValue(&$return, $field_value, $o_id, $p_id, $productkey, $product_index, $profil_separator) 
		{ 

			if ($this->isVariantsProductKey($productkey))
			{

				$var_info = $this->getVariantenInfoArray($productkey);
				
				$var_vname = $var_info['key'];
				$var_vanr = $var_info['akey'];
				
			}
			else
			{
				
				// Damit das nicht definiert nicht im Export erscheint, für Produkte die keine Variante sind 
				
				$var_vname = '';
				$var_vanr = '';
				
			}
			
			switch ($field_value)
			{
			
				case 'product_vname': $return = $var_vname; break;
				case 'product_vanr': $return = $var_vanr; break;
			
			}
			
		} // public function wpsg_mod_export_getValue(&$return, $field_value, $o_id, $p_id, $productkey, $product_index, $profil_separator) 
		
		/* Modulfunktionen */ 
		
		/**
		 * Gibt die Möglichken Bilder einer Variantenkombination zurück
		 */
		public function getKombiVariImages($var_key, $var_id = false)
		{
			
			if (!$this->shop->hasMod('wpsg_mod_produktbilder')) return false;
					
			$arVarSelected = $this->getSetVariArray($var_key);			
			$product_id = $this->shop->getProduktID($var_key);
			$arVari = $this->loadVarianten($product_id);
		
			$handle = opendir($this->shop->callMod('wpsg_mod_produktbilder', 'getPicPath', array($product_id)));
				
			// Bilder des Produktes laden
			$arBilder = array(); $i = 1;
			while($filename = readdir($handle))
			{
		
				$file = $this->shop->callMod('wpsg_mod_produktbilder', 'getPicPath', array($product_id)).'/'.$filename;
		
				if (is_file($file) && $file != "." && $file != "..") $arBilder[] = $filename; $i ++;
		
			}
		
			// Schauen ob ein Bild nach dem Dateinamen dabei ist
			foreach ($arBilder as $bild)
			{
				
				$image = false;
				$filename = preg_replace("/\.([^\.]*)/", "", $bild);
				if ($filename == "vp_".str_replace(":", "-", $var_key)) $image = $bild;
					
				if ($image !== false) return array($image);
				
			}
		
			foreach ($arVari as $var_key => $var)
			{
	
				if (array_key_exists($var_key, $arVarSelected))
				{

					if ($var_id === $var_key) continue;
					
					if ($var['typ'] == "checkbox")
					{
							
						if ($arVarSelected[$var_key] == "1")
						{
							$arBilder = array_intersect($arBilder, explode(",", $var['pic']));
						}
						else
						{
							$arBilder = array_diff($arBilder, explode(",", $var['pic']));
						}
							
					}
					else
					{
												
						$arBilder = array_intersect($arBilder, explode(",", wpsg_getStr($var['vari'][$arVarSelected[$var_key]]['pic'])));
							
					}
						
				}
					
			}
				
			$arBilder = $this->checkPics($arBilder, $product_id);
				
			if (wpsg_isSizedArray($arBilder))
			{
	
				return $arBilder;
					
			}
			else
			{
				
				return array();
				
			}
		
		}
				
		/**
		 * Gibt das Bild für die Grafikauswahl zurück
		 * @param int $product_id
		 * @param int $var_id
		 * @param int $vari_id
		 */
		public function getImageSelectImage($product_id, $var_id, $vari_id, $vari_key)
		{

			$arVariBilder = $this->getVariImages($product_id, $var_id, $vari_id);			
			$arVariPossibleBilder = $this->getKombiVariImages($vari_key, $var_id);
			
			$arBilderIntersect = array_intersect($arVariBilder, $arVariPossibleBilder);			
			if (wpsg_isSizedArray($arBilderIntersect)) $arVariBilder = $arBilderIntersect;
			
			return array_shift($arVariBilder);
			
		} // public function getImageSelectImage($product_id, $var_id, $vari_id)
		
		/**
		 * Gibt die Bilder als Array für die Variation zurück
		 * Beachtet die Reihenfolge die im Backend über Drag&Drop definiert ist
		 * @param int $var_id Key der Variante
		 * @param int $vari_id Key der Variation
		 */
		public function getVariImages($product_id, $var_id, $vari_id)
		{
			
			$vp_data = $this->loadVarianten($product_id);
			
			$arProductBilder = $this->shop->callMod('wpsg_mod_produktbilder', 'getProduktBilder', array($product_id));
			 
			$arReturn = array();
			 
			// Bilder in Reihenfolge
			if ($vp_data[$var_id]['typ'] == 'checkbox' && wpsg_isSizedArray($vp_data[$var_id]['picOrder'])) $arReturn = $vp_data[$var_id]['picOrder']; 
			else if (wpsg_isSizedArray($vp_data[$var_id]['vari'][$vari_id]['picOrder'])) $arReturn = $vp_data[$var_id]['vari'][$vari_id]['picOrder'];
			
			// Prüfen ob die Bilder noch in Produktbilder Array drin sind
			foreach ($arReturn as $k => $v)
			{
				
				if (!in_array($v, $arProductBilder)) unset($arReturn[$k]);
				else unset($arProductBilder[array_search($v, $arProductBilder)]);
				
			}
			
			// Bilder aus dem ProduktArray noch hinzufügen, die eventuell nicht im sortierten Array enthalten sind
			foreach ($arProductBilder as $k => $v)
			{
				
				$arReturn[] = $v;
				
			}
			
			$arImageSelect = array();
			
			// Sind die Bilder in der Variante ausgewählt?
			if (!is_admin())
			{
			
				if ($vp_data[$var_id]['typ'] == 'checkbox' && wpsg_isSizedString($vp_data[$var_id]['pic'])) $arImageSelect = explode(',', $vp_data[$var_id]['pic']);
				else if (wpsg_isSizedString($vp_data[$var_id]['vari'][$vari_id]['pic'])) $arImageSelect = explode(',', $vp_data[$var_id]['vari'][$vari_id]['pic']);
			
				foreach ($arReturn as $k => $v)
				{
				
					if (!in_array($v, $arImageSelect)) unset($arReturn[$k]);
				
				}
				
			}
						
			return $arReturn;
									
		} // public function getVariImages($product_id, $var_id, $vari_id)
				
		/**
		 * Gibt einen Array zurück, bei denen die Schlüssel die Varianten sind und die Werte die gewählten Variationen
		 */
		private function getSetVariArray($product_key)
		{

			if (!$this->isVariantsProductKey($product_key)) return array();
			
			$arVariSet = explode(':', preg_replace('/^vp_\d*\//', '', $product_key));
			$arReturn = array();
			
			foreach ($arVariSet as $var_combi)
			{
				
				$var_combi = explode('_', $var_combi);
				$var = $var_combi[0];
				$vari = $var_combi[1];
				
				$arReturn[$var] = $vari;
				
			}
			
			return $arReturn;
			
		}
		
		/**
		 * Gibt true zurück, wenn der übergebene Produktkey ein Varianten Produktkey ist. Sonst false.
		 * @param \String $productkey
		 */
		public function isVariantsProductKey($productkey)
		{
			
			if (preg_match('/^vp_\d+/', $productkey))
			{
				
				return true;
				
			}
			else 
			{

				return false;
				
			}
			
		} // public function isVariantsProductKey($productkey)
		
		/**
		 * Übernimmt die Auswahl der Variante im Produkttemplate
		 */
		public function renderTemplate($product_key)
		{
			 
			$produkt_id = $this->shop->getProduktId($product_key);
			$produkt_data = $this->shop->cache->loadProduct($produkt_id);
			$tax_value = $this->shop->getCalcTaxValue($produkt_data['mwst_key']);
												
			if ($this->shop->isOtherLang())
			{
			
				$produkt_trans_id = $this->db->fetchOne("SELECT `id` FROM `".WPSG_TBL_PRODUCTS."` WHERE `lang_parent` = '".wpsg_q($produkt_id)."' AND `lang_locale` = '".wpsg_q($this->shop->getCurrentLanguage())."'");
					
				if (wpsg_isSizedInt($produkt_trans_id)) $produkt_id = $produkt_trans_id;
				
			}
	 
			$vp_data = $this->loadVarianten($produkt_id);
									
			if (is_array($vp_data) && sizeof($vp_data) > 0)
			{
				
				$this->shop->view['data']['vp_data'] = $vp_data;
				$this->shop->view['wpsg_mod_varianten']['set'] = $this->getSetVariArray($product_key);
				
				// Rabattpreise vorkalkulieren
				//$this->shop->callMod('wpsg_mod_discount', 'addDiscountToVari', array(&$produkt_id, &$this->shop->view['data']['vp_data']));
				 
				foreach ($this->shop->view['data']['vp_data'] as $k => $v)
				{
					
					if ($v['typ'] == "checkbox")
					{
						
						if (get_option("wpsg_vp_showpic") == "1" && wpsg_isSizedString($v['pic']))
						{
							
							$this->shop->view['data']['vp_data'][$k]['showpic'] = $this->getImageSelectImage($produkt_id, $k, $k2, $product_key);
						 							
						}
						
						// Preis an Ausgabe im Frontend anpassen
						if ($this->shop->getFrontendTaxview() == WPSG_NETTO && $this->shop->getBackendTaxview() == WPSG_BRUTTO) $this->shop->view['data']['vp_data'][$k]['preis'] = wpsg_calculatePreis($v['preis'], WPSG_NETTO, $tax_value);
						 
					}
					else
					{ 
						
						foreach ($v['vari'] as $k2 => $v2)
						{

							if (get_option("wpsg_vp_showpic") == "1" && wpsg_isSizedString($v2['pic']))
							{
							 								
								$this->shop->view['data']['vp_data'][$k]['vari'][$k2]['showpic'] = $this->getImageSelectImage($produkt_id, $k, $k2, $product_key);
								
							}
							
							// Preis an Ausgabe im Frontend anpassen
							if ($this->shop->getFrontendTaxview() == WPSG_NETTO && $this->shop->getBackendTaxview() == WPSG_BRUTTO) $this->shop->view['data']['vp_data'][$k]['vari'][$k2]['preis'] = wpsg_calculatePreis($v2['preis'], WPSG_NETTO, $tax_value);
							
						}
						
					}
					
				}
					 
								
				return $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_varianten/produkt.phtml', false);
				
			}
			
		} // public function renderTemplate($produkt_id)

		/**
		 * Zeichnet das Interface für die Bearbeitung der Varianten
		 */
		public function drawVarianten($produkt_id)
		{
					    			
			$this->shop->view['vp_data'] = $this->loadVarianten($produkt_id);
			 
			if ($this->shop->hasMod('wpsg_mod_fuellmenge'))
			{
				
				$this->shop->view['vp_productdata'] = $this->shop->cache->loadProduct($produkt_id);
				$this->shop->view['vp_arFeinheiten'] = explode(',', $this->shop->get_option('wpsg_mod_fuellmenge_einheit'));
				
			}

			// Wenn es über Ajax aufgerufen wird fehlt hier die ProduktID !
			if (!isset($this->shop->view['data']['id'])) $this->shop->view['data']['id'] = $produkt_id;
									 
			return $this->shop->render(WPSG_PATH_VIEW.'/mods/mod_varianten/drawVarianten.phtml');
						
		} // public function drawVarianten($produkt_id)
		
		/**
		 * Gibt den Namen der Variante zurück
		 */
		public function getVariantenName($vp_data, $var_id)
		{
			
			$name = $vp_data[$var_id]['name'];
			 
			if (wpsg_isSizedString($_REQUEST['wpsg_lang']))
			{
				if ($vp_data[$var_id]['lang'][$_REQUEST['wpsg_lang']]['name'] != "")
				{
					$name = $vp_data[$var_id]['lang'][$_REQUEST['wpsg_lang']]['name'];
				}
			} 
			
			return ((trim($name) == "")?"----":$name);
			
		} // public function getVariantenName($vp_data, $v_id)
		
		/**
		 * Gibt den Namen der Variation zurück
		 */
		public function getVariName($vp_data, $var_id, $vari_id)
		{
			
			$name = $vp_data[$var_id]['vari'][$vari_id]['name'];	
								
			if (wpsg_isSizedString($_REQUEST['wpsg_lang']))
			{
				if ($vp_data[$var_id]['lang'][$_REQUEST['wpsg_lang']]['vari'][$vari_id]['name'] != "")
				{
					$name = $vp_data[$var_id]['lang'][$_REQUEST['wpsg_lang']]['vari'][$vari_id]['name'];
				}
			}
		
			return ((trim($name) == "")?"----":$name);
			
		} // public function getVariName($vp_data, $var_id, $vari_id)
		
		/**
		 * Gibt true zurück, wenn der Preis im Produkttemplate angezeigt werden soll
		 * Andersrum programmiert, da die Default Einstellung anzeigen ist
		 */
		public function showVariPrice($vari_price)
		{
			
			switch ($this->shop->get_option('wpsg_mod_varianten_showvariprice'))
			{
				
				case '1': // nur wenn größer 0
					
					if ($vari_price <= 0) return false;
					
					break;
					
				case '2': // nie anzeigen
					
					return false;
					
					break;
				
			}
			
			return true;
			
		} // public function showVariPrice($vari_price)
		
		/**
		 * Lädt die Varianteninformationen aus dem serialisierten Array
		 * @param $noTrans Wird diese Variable auf true gesetzt, so wird die Übersetzung nicht geladen (Wie Backend) Wichtig wenn die Varianten wieder gespeichert werden sollen!
		 */
		public function loadVarianten($produkt_id, $noTrans = false, $noCache = false)
		{
			
			if (is_admin()) $noCache = true;
			
			if (!$noCache && array_key_exists($produkt_id.$noTrans, $this->cache_variData)) return $this->cache_variData[$produkt_id.$noTrans];
						 
			// Übersetzung verarbeiten
			if (is_admin() || $noTrans === true)
			{
				
				$vp_data = @unserialize($this->db->fetchOne("SELECT `mod_varianten` FROM `".WPSG_TBL_PRODUCTS."` WHERE `id` = '".wpsg_q($produkt_id)."'"));
				if (!is_array($vp_data)) $vp_data = array();
				
			} 
			else
			{
			
				// Im Frontend geht es nach der Sprache auf der der Shop aktuell läuft	
				if ($this->shop->isOtherLang())			
				{
										
					$parent_lang_id = $this->db->fetchOne("SELECT `lang_parent` FROM `".WPSG_TBL_PRODUCTS."` WHERE `id` = '".wpsg_q($produkt_id)."'");					
					if (!wpsg_isSizedInt($parent_lang_id)) $parent_lang_id = $produkt_id;				
					
					$vp_data = @unserialize($this->db->fetchOne("SELECT `mod_varianten` FROM `".WPSG_TBL_PRODUCTS."` WHERE `id` = '".wpsg_q($parent_lang_id)."'"));
					if (!is_array($vp_data)) $vp_data = array();
					
					foreach ($vp_data as $k => $v)
					{
	
						// Den Namen der Variante auf die aktuelle Sprache stellen
						if (wpsg_isSizedString($vp_data[$k]['lang'][$this->shop->getCurrentLanguage()]['name'])) $vp_data[$k]['name'] = $vp_data[$k]['lang'][$this->shop->getCurrentLanguage()]['name'];
						
						if (wpsg_isSizedArray($vp_data[$k]['vari']))
						{
							
							foreach ($vp_data[$k]['vari'] as $k2 => $vari)
							{
								
								// Den Namen der Variation auf die aktuelle Sprache korrigieren
								if (wpsg_isSizedString($vp_data[$k]['lang'][$this->shop->getCurrentLanguage()]['vari'][$k2]['name'])) $vp_data[$k]['vari'][$k2]['name'] = $vp_data[$k]['lang'][$this->shop->getCurrentLanguage()]['vari'][$k2]['name'];
								
							}
							
						}
						
					}
					
				}
				else
				{
					
					$vp_data = @unserialize($this->db->fetchOne("SELECT `mod_varianten` FROM `".WPSG_TBL_PRODUCTS."` WHERE `id` = '".wpsg_q($produkt_id)."'"));
					if (!is_array($vp_data)) $vp_data = array();
					
				}
				
			}
			 						
			$this->cache_variData[$produkt_id.$noTrans] = $vp_data; 
			
			return $vp_data;
			
		} // public function loadVarianten($produkt_id)
		
		/**
		 * Lädt einen Array mit den für das Frontend möglichen Varianten/Variationen
		 */
		public function laodPossibleVarianten($produkt_id, $noTrans = false)
		{
			
			$arVariData = $this->loadVarianten($produkt_id, $noTrans);
			
			foreach ($arVariData as $var_key => $var)
			{
				
				if ($var['typ'] == 'checkbox')
				{
					
					if ($var['aktiv'] != '1') unset($arVariData[$var_key]);
					
				}
				else 
				{
					 
					if ($var['aktiv'] != '1')
					{
							
						unset($arVariData[$var_key]);
							
					}
					else
					{
						
						$akt_vari = false;
						
						foreach ($var['vari'] as $vari_key => $vari)
						{
							
							if ($vari['aktiv'] != '1' || ($this->shop->hasMod('wpsg_mod_stock') && !wpsg_isSizedInt($vari['stock'])))
							{
								
								unset($arVariData[$var_key]['vari'][$vari_key]);
								
							}
							else
							{
								
								$akt_vari = true;
								
							}
							
						}
						
						if ($akt_vari === false)
						{
							
							unset($arVariData[$var_key]);
							
						}
						
					}
					
				}
				
			}
			
			return $arVariData;
			
		} // public function laodPossibleVarianten($produkt_id, $noTrans)
		
		/**
		 * Gibt den Warenbestand für ein Produkt anhand seiner Variantenkonfiguration zurück
		 */
		public function getStockForVarianten($vari_key)
		{
			
			
			$produkt_id = preg_replace('/(^vp_)|(\/(.*)$)/', '', $vari_key);
			$vari_teil = preg_replace('/(.*)\//', '', $vari_key);
			
			$vari_data = $this->loadVarianten($produkt_id);			 
			$arVarianten = explode(":", $vari_teil);
			 
			$arStock = array();
			
			foreach ((array)$arVarianten as $variante)
			{
				
				$arVariante = explode("_", $variante);
				
				$variante_id = $arVariante[0];
				$vari_id = $arVariante[1];
				
				if ($vari_data[$variante_id]['typ'] == 'checkbox')
				{
					
					// Checkbox betrachte ich gar nicht mehr
					// Nur betrachten Wenn Checkbox aktiviert ist
					//if ($vari_id == '1') $arStock[] = $vari_data[$variante_id]['stock'];
						
				}
				else
				{
					
					$arStock[] = $vari_data[$variante_id]['vari'][$vari_id]['stock'];
					
				}
				
			}
 
			if (!wpsg_isSizedArray($arStock))
			{
				
				// Hier greife ich jetzt auf den Produktbestand zurück
				// Tritt auf, wenn z.B. nur die Checkboxvariante definiert ist
				
				$product_data = $this->shop->cache->loadProduct($produkt_id);				
				return $product_data['stock'];
				
			}
			
			return min($arStock);
			 
		} // public function getStockForVarianten($vari_key)
		
		/**
		 * Reduziert den Bestand der Variationen in dem Array
		 */
		public function reduceStock($produkt_key, $menge, $reduce = true)
		{
	
			$produkt_id = preg_replace('/(^vp_)|(\/(.*)$)/', '', $produkt_key);
			$vari_teil = preg_replace('/(.*)\//', '', $produkt_key);			
			$arVarianten = explode(':', $vari_teil);
			
			$vari_data = $this->loadVarianten($produkt_id, true, true);
  
			foreach ($arVarianten as $variante)
			{
				
				$arVariante = explode('_', $variante);
				$variante_id = $arVariante[0];
				$vari_id = $arVariante[1];
				
				if ($reduce === true)
				{
				
					$vari_data[$variante_id]['vari'][$vari_id]['stock'] -= $menge;
					
				}
				else
				{
				
					$vari_data[$variante_id]['vari'][$vari_id]['stock'] += $menge;

				}
								
			}
			
			// Array zurückspeichern
			$this->saveVarianten($produkt_id, $vari_data);
						
		} // public function reduceStock($produkt_id, $menge)
		
		/**
		 * Gibt einen Variantenschlüssel für die Standard Variantenauswahl zurück
		 */
		public function getDefaultVariKey($product_key)
		{
			 
			if (is_numeric($product_key))
			{

				$arVariData = $this->laodPossibleVarianten($product_key, true);
				
				if (!wpsg_isSizedArray($arVariData)) return $product_key;
				
				$arVariDefault = array();
				 
				foreach ($arVariData as $var_key => $var)
				{

					$first_vari_key = '0';
					
					if (wpsg_isSizedArray($var['vari']))
					{
						
						$arKeys = array_keys($var['vari']);
						$first_vari_key = array_shift($arKeys);
						
					}
										
					$arVariDefault[] = $var_key.'_'.$first_vari_key;
					
				}

				return 'vp_'.$product_key.'/'.implode(':', $arVariDefault); 
				
			}
			else
			{
				
				// Ist schon ein Produktschlüssel
				return $product_key;
				
			}
			
		} // public function getDefaultVariKey($product_id)
		
		/**
		 * Speichert die Varianten
		 */
		public function saveVarianten($produkt_id, $vp_data)
		{

			$vp_data = $this->clearArrayForSerialization($vp_data);
			
			$this->db->UpdateQuery(WPSG_TBL_PRODUCTS, array(
				"mod_varianten" => wpsg_q(serialize($vp_data))
			), "`id` = '".wpsg_q($produkt_id)."'");
		  
		} // public function saveVarianten($produkt_id, $vp_data)

		/**
		 * Liest die Informationen anhand eines Variantenschlüssels aus
		 */
		public function getVariantenInfoArray($vari_key)
		{
			
			$produkt_id = preg_replace('/(vp_)|(\/(.*))/', '', $vari_key);								
			$arVari = explode(':', preg_replace('/vp_'.$produkt_id.'\//', '', $vari_key));
	
			$vp_data = $this->loadVarianten($produkt_id);
	
			$arKey = array();
			$arAKey = array();
			$arPics = array();
			
			$arReturn = array();
			
			if ($this->shop->hasMod('wpsg_mod_fuellmenge')) $arReturn['fmenge'] = 0;
			if ($this->shop->hasMod('wpsg_mod_weight')) $arReturn['weight'] = 0;
			
			foreach ($arVari as $var_key)
			{
				
				$var_id = preg_replace('/\_(.*)/', '', $var_key);
				$var_value = preg_replace('/(.*)\_/', '', $var_key);
			
				if ($vp_data[$var_id]['typ'] == 'checkbox')
				{
					
					$arPicsVariante = array();
						
					if (isset($vp_data[$var_id]['pic']))
					{
					
						$arPicsVariante = wpsg_trim(explode(',', $vp_data[$var_id]['pic']));						
																	
					}
					
					if ($var_value == '1')
					{  
					 
						$r = array(
							'name' => $vp_data[$var_id]['name'],
							'preis' => $vp_data[$var_id]['preis'],
							'artnr'	=> $vp_data[$var_id]['vari'][2]['artnr'],
							'pics' => $arPicsVariante
						);
						 
						if ($this->shop->hasMod('wpsg_mod_weight') && wpsg_isSizedInt($vp_data[$var_id]['weight']))
						{
							
							$r['weight'] = $vp_data[$var_id]['weight'];
							$arReturn['weight'] += $r['weight'];
							
						}						

						if ($this->shop->hasMod('wpsg_mod_fuellmenge') && wpsg_isSizedInt($vp_data[$var_id]['fmenge']))
						{
							
							$r['fmenge'] = $vp_data[$var_id]['fmenge'];
							$arReturn['fmenge'] += $r['fmenge'];
							
						}
												
						$arReturn[] = $r;
						
						$arKey[] = $vp_data[$var_id]['name'];
						
						$arPics = array_intersect($arPics, $arPicsVariante);
						
					}
					else
					{
						
						// Checkbox ist nicht markiert
						//$arPics = array_unique(array_merge($arPics, $arPicsVariante));
						
					}
					
				}				
				else 
				{
					
					$arPicsVariante = array();
					
					if (isset($vp_data[$var_id]['vari'][$var_value]['pic']))
					{
						
						$arPicsVariante = wpsg_trim(explode(',', $vp_data[$var_id]['vari'][$var_value]['pic']));							
						$arPics = array_unique(array_merge($arPics, $arPicsVariante));
						
					}
					 
					$r = array(
						'name' 	=> $vp_data[$var_id]['name'],
						'value' => $vp_data[$var_id]['vari'][$var_value]['name'],
						'preis'	=> $vp_data[$var_id]['vari'][$var_value]['preis'],
						'artnr'	=> @$vp_data[$var_id]['vari'][$var_value]['artnr'],
						'pics' => $arPicsVariante
					);
					
					if ($this->shop->hasMod('wpsg_mod_weight') && wpsg_isSizedInt($vp_data[$var_id]['vari'][$var_value]['weight']))
					{
					
						$r['weight'] = $vp_data[$var_id]['vari'][$var_value]['weight'];
						$arReturn['weight'] += $r['weight'];
					
					}
					
					if ($this->shop->hasMod('wpsg_mod_fuellmenge') && wpsg_isSizedInt($vp_data[$var_id]['vari'][$var_value]['fmenge']))
					{
						
						$r['fmenge'] = $vp_data[$var_id]['vari'][$var_value]['fmenge'];
						$arReturn['fmenge'] += $r['fmenge'];
						
					}
					
					$arReturn[] = $r;
					
					$arKey[] = $vp_data[$var_id]['vari'][$var_value]['name'];
					$arAKey[] = @$vp_data[$var_id]['vari'][$var_value]['artnr'];
										
				}
				
			}
			
			$arReturn['key'] = implode(' / ', $arKey);
			$arReturn['akey'] = implode(' / ', $arAKey);
			$arReturn['pics'] = array_unique($arPics);

			return $arReturn;			
			
		} // public function getVariantenText($vari_key)
				
		private function checkPics(&$arPics, $produkt_id)
		{
			
			foreach ($arPics as $k => $v)
			{
				
				if (!file_exists($this->shop->callMod('wpsg_mod_produktbilder', 'getPicPath', array($produkt_id)).'/'.$v))
				{
					unset($arPics[$k]);
				}
				
			}
			
			return $arPics;
			
		} // private function checkPics($arPics, $produkt_id)
				
		private function clearArrayForSerialization($ar)
		{
			
			foreach ((array)$ar as $k => $v)
			{
				
				if (wpsg_isSizedArray($v))
				{
					
					$ar[$k] = $this->clearArrayForSerialization($v);
					
				}
				else
				{
					
					$ar[$k] = preg_replace('/\'|\`|\´|\"/', '', $v);					
					
				}
				
			}
			
			return $ar;
			
		} // private function clearArrayForSerialization($ar)
		
	} // class wpsg_mod_varianten extends wpsg_mod_basic

?>