<?php
if( isset( $iContent ) && is_numeric( $iContent ) ){
	$aData = $oPage->throwPage( $iContent );
	$sUrlExtStr = null;
	if( !empty( $config['recaptcha_private'] ) && !empty( $config['recaptcha_public'] ) ) $oReCaptcha = new recaptchalib($config['recaptcha_private']);

	if( strpos( $_SERVER['REQUEST_URI'], '?' ) !== false ){
		$sUrlExtStr = substr( $_SERVER['REQUEST_URI'], strpos( $_SERVER['REQUEST_URI'], '?' ) + 1 );
	}
	saveUserAction( Array( 'iPage' => $iContent, 'iType' => 1 /* 1 - otworzenie, 2 - porównanie, 3 - dodanie do schowka, 4 - dodanie do koszyka */, 'sParameters' => $sUrlExtStr ) );
	if( isset( $mes ) && ( $mes == 'login_correct' ) ){
		$aUserData = throwUser( $_SESSION['iUserClient'] );
		$_SESSION['sUserName'] = $aUserData['sFirstName'] . ' ' . $aUserData['sLastName'];
		$_SESSION['sUserEmail'] = $aUserData['sEmail'];
		$_SESSION['sUserPhone'] = $aUserData['sPhone'];
		$sDiscount = ( $aUserData['fDiscount'] > 0 ) ? ( $lang['User_discount_message'] . '<strong>' . ( $aUserData['fDiscount'] * 100 ) . '%</strong><br />' . ( $config['join_promotions'] ? $lang['User_discount_promos_message'] : $lang['User_discount_nopromos_message'] ) ) : null;
		$aMessage = Array( 'header' => $lang['Login_header'], 'content' => '<p>' . $lang['Logged_in'] . '</p>' . ( !empty( $sDiscount ) ? '<p>' . $sDiscount . '</p>' : null ) );
	}
	//* Obsługa komunikatów 
	if (isset( $mes )) switch($mes){
		case 'logout_correct': 				$aMessage = Array( 'header' => $lang['Login_header'], 'content' => '<p>' . $lang['Logged_out'] . '</p>' ); break;
		case 'register_correct': 			$aMessage = Array( 'header' => $lang['Login_header'], 'content' => '<p>' . $lang['Registred'] . '</p>' );	break;
		case 'message_send': 				$aMessage = Array( 'header' => $lang['Send_ok'], 'content' => '<p>' . $lang['Message_send'] . '</p>' ); break;
		case 'message_error': 				$aMessage = Array( 'header' => $lang['Send_error'], 'content' => '<p>' . $lang['Message_send_error'].'</p>' ); break;
		case 'message_reCaptchaTimeout': 	$aMessage = Array( 'header' => $lang['Send_error'], 'content' => '<p>' . $lang['Message_reCaptcha_error'].'</p>' ); break;
		case 'password_send': 				$aMessage = Array( 'header' => $lang['Send_ok'], 'content' => '<p>' . $lang['Mail_send_correct'] . '</p>' ); break;
		case 'password_not_send': 			$aMessage = Array( 'header' => $lang['Send_error'], 'content' => '<p>' . $lang['Mail_send_error'] . '</p>' ); break;
		case 'nip_error': 					$aMessage = Array( 'header' => $lang['Basket_data_error'], 'content' => '<p>' . $lang['Nip_error'] . '</p>' ); break;
		case 'phone_error': 				$aMessage = Array( 'header' => $lang['Basket_data_error'], 'content' => '<p>' . $lang['Phone_error'] . '</p>' ); break;
		case 'pesel_error':					$aMessage = Array( 'header' => $lang['Basket_data_error'], 'content' => '<p>' . $lang['Pesel_error'] . '</p>' ); break;
		case 'login_error':
			if( isset( $_SESSION['sLoginErrorSer'] ) ){
				$aMessage = Array( 'header' => $lang['Login_header'], 'content' => '<p class="error">' . unserialize( $_SESSION['sLoginErrorSer'] ) . '</p>' );
				$_SESSION['sLoginErrorSer'] = null;
			}
		break;
	}

	if( isset( $mes ) && ( $mes == 'comment_add' ) ){
		$aMessage = Array( 'header' => $lang['Send_ok'], 'content' => '<p>' . $lang['Comment_add'] . '</p>' );
	}
	// Linki do templatki strony
	$sBestsellersLink = $oPage->aPages[$config['bestsellers_page']]['sLinkName'];
	/* Klasa dla tytulu wyszukiwarki */
	if( $iContent == $config['page_search'] ){
		$sClassTitle = 'searcher';
	}
	if( $config['users_plugin_active'] == true ){
		$sUsersPanel = null;
		$aUsersMenu = null;
		if( isset( $config['logout_page'] ) && is_numeric( $config['logout_page'] ) && $iContent == $config['logout_page'] && isset( $_SESSION['iUserClient'] ) ){
			$_SESSION['iUserClient'] = null;
			$_SESSION['sUserName'] = null;
			$_SESSION['sUserEmail'] = null;
			$_SESSION['sUserPhone'] = null;
			$_SESSION['iUserPriceGroup'] = null;
			header( 'Location: ' . $config['index'] . '?mes=logout_correct' );
			exit;
		}
		if( isset( $config['login_page'] ) && is_numeric( $config['login_page'] ) && $iContent == $config['login_page'] ){
			if( !empty( $_POST['sLogin'] ) && !empty( $_POST['sPass'] ) ){
				$_SESSION['iUserClient'] = checkUserLogin( $_POST['sLogin'], $_POST['sPass'] );
				if( isset( $_SESSION['iUserClient'] ) && is_numeric( $_SESSION['iUserClient'] ) ){
					$oOrder->autoGroupClient( LANGUAGE, $_SESSION['iUserClient'] );
					$oDB->executeSQL( 'UPDATE `' . $oDB->throwTableName( DB_USER_ACTIONS ) . '` SET `iUser` = \'' . $oDB->escape( $_SESSION['iUserClient'] ) . '\' WHERE `iCustomer` = ' . $_SESSION['iCustomer' . LANGUAGE] );
					if( isset( $_POST['bRedirectOrder'] ) ) $sUserPage = $oPage->aPages[$config['order_address_page']]['sLinkName'];
					if( isset( $_SESSION['sRedirectAfterLogin'] ) ){
						$sUserPage = $_SESSION['sRedirectAfterLogin'];
						$_SESSION['sRedirectAfterLogin'] = null;
					}
					if( !isset( $sUserPage ) ){
						if( isset( $oPage->aPages[$config['account_page']] ) ) $sUserPage = $oPage->getLinkName( $config['account_page'] );
						else $sUserPage = $oPage->getLinkName( $config['start_page'] );
					}
					//$_SESSION['sEmail'] = $_POST['sLogin'];
					header( 'Location: ' . $sUserPage . ( strpos( $sUserPage, '?' ) !== false ? '&' : '?' ) . 'mes=login_correct' );
					exit;
				} else{
					$oTpl->assign( 'aMessage', Array( 'message' => $lang['Error_login_or_pass'], 'bError' => true ) );
					$sUsersPanel.= $oTpl->parse( 'message.tpl' );
					if( isset( $_POST['bRedirectOrder'] ) && isset( $_SESSION['sRedirectAfterLogin'] ) ){
						$sUserPage = $_SESSION['sRedirectAfterLogin'];
						$_SESSION['sRedirectAfterLogin'] = null;
					} else{
						$sUserPage = $oPage->getLinkName( $config['login_page'] );
					}
					$_SESSION['sLoginErrorSer'] = serialize( $sUsersPanel );
					header( 'Location: ' . $sUserPage . ( strpos( $sUserPage, '?' ) !== false ? '&' : '?' ) . 'mes=login_error' );
					exit;
				}
			} else{
				$sUsersPanel.= $oTpl->parse( 'users_login_form.tpl' );
			}
		}
		if( isset( $config['remind_password_page'] ) && is_numeric( $config['remind_password_page'] ) && $iContent == $config['remind_password_page'] ){
			if( !empty( $_POST['sLogin'] ) && !empty( $_POST['sEmail'] ) ){
				if( SendRemindPassword( $_POST['sLogin'], $_POST['sEmail'] ) ){
					//$oTpl->assign( 'aMessage', Array( 'message' => $lang['Remind_mail_send_correct'] ) );
					//$sUsersPanel.= $oTpl->parse( 'message.tpl' );
					header( 'Location: ' . $sUserPage . ( strpos( $sUserPage, '?' ) !== false ? '&' : '?' ) . 'mes=password_send' );
				} else{
					//$oTpl->assign( 'aMessage', Array( 'message' => $lang['Remind_mail_send_error'], 'bError' => true ) );
					//$sUsersPanel.= $oTpl->parse( 'message.tpl' );
					header( 'Location: ' . $sUserPage . ( strpos( $sUserPage, '?' ) !== false ? '&' : '?' ) . 'mes=password_not_send' );
				}
			} else{
				$sUsersPanel.= $oTpl->parse( 'users_remind_form.tpl' );
			}
		}
		if( isset( $config['register_page'] ) && is_numeric( $config['register_page'] ) && $iContent == $config['register_page'] && !isset( $_SESSION['iUserClient'] ) ){
			if( isset( $_POST['sOption'] ) && ( !isset( $config['rules_page'] ) || !isset( $oPage->aPages[$config['rules_page']] ) || $_POST['iRulesAccept'] ) ){
				if (!$oReCaptcha->verify($_POST['g-recaptcha-response'],$_SERVER['REMOTE_ADDR'])){
					header( 'Location: ' . $sUserPage . ( strpos( $sUserPage, '?' ) !== false ? '&' : '?' ) . 'mes=message_reCaptchaTimeout' );
					exit;
				}
				if( !empty( $_POST['sLogin'] ) && !empty( $_POST['sPass'] ) && !empty( $_POST['sPass2'] ) && !empty( $_POST['sEmail'] ) ){
					if( $_POST['sPass'] != $_POST['sPass2'] ){
						$sUsersPanel = $lang['Password_dont_mach'];
						if( isset( $_SESSION['sRedirectAfterLogin'] ) ){
							$sUserPage = $_SESSION['sRedirectAfterLogin'];
							$_SESSION['sRedirectAfterLogin'] = null;
						} else{
							$sUserPage = $oPage->getLinkName( $config['register_page'] );
						}
						$_SESSION['sLoginErrorSer'] = serialize( $sUsersPanel );
						header( 'Location: ' . $sUserPage . ( strpos( $sUserPage, '?' ) !== false ? '&' : '?' ) . 'mes=login_error' );
						exit;
					} elseif( checkUserLoginNotExist( $_POST['sLogin'] ) == true && checkUserLoginNotExist( $_POST['sEmail'] ) == true ){
						$_SESSION['iUserClient'] = saveUser( $_POST );
						if( isset( $_POST['iNewsletterAccept'] ) && !empty( $_POST['iNewsletterAccept'] ) ){
							if( !empty( $_POST['sEmail'] ) && checkEmail( $_POST['sEmail'] ) == true ){
								require_once DIR_ENGINE . 'newsletter.php';
								saveNewsletter( $_POST['sEmail'] );
							}
						}
						if( isset( $_SESSION['sRedirectAfterLogin'] ) ){
							$sUserPage = $_SESSION['sRedirectAfterLogin'];
							$_SESSION['sRedirectAfterLogin'] = null;
						} else{
							$sUserPage = $oPage->getLinkName( $config['profile_page'] );
						}
						/**** SALESMANAGO ****/
						if( $oSalesManago->checkSettings() === true ) $oSalesManago->upsertContact( $_POST );
						/**** END SALESMANAGO ****/
						
						header( 'Location: ' . $sUserPage . ( strpos( $sUserPage, '?' ) !== false ? '&' : '?' ) . 'mes=register_correct' );
						exit;
					} else{
						$sUsersPanel = $lang['User_exists'];
						if( isset( $_SESSION['sRedirectAfterLogin'] ) ){
							$sUserPage = $_SESSION['sRedirectAfterLogin'];
							$_SESSION['sRedirectAfterLogin'] = null;
						} else{
							$sUserPage = $oPage->getLinkName( $config['register_page'] );
						}
						$_SESSION['sLoginErrorSer'] = serialize( $sUsersPanel );
						header( 'Location: ' . $sUserPage . ( strpos( $sUserPage, '?' ) !== false ? '&' : '?' ) . 'mes=login_error' );
						exit;
					}
				} else{
					$oTpl->assign( 'aMessage', Array( 'message' => $lang['Data_not_found'], 'bError' => true ) );
					$sUsersPanel.= $oTpl->parse( 'message.tpl' );
					if( isset( $_SESSION['sRedirectAfterLogin'] ) ){
						$sUserPage = $_SESSION['sRedirectAfterLogin'];
						$_SESSION['sRedirectAfterLogin'] = null;
					} else{
						$sUserPage = $oPage->getLinkName( $config['register_page'] );
					}
					$_SESSION['sLoginErrorSer'] = serialize( $sUsersPanel );
					header( 'Location: ' . $sUserPage . ( strpos( $sUserPage, '?' ) !== false ? '&' : '?' ) . 'mes=login_error' );
					exit;
				}
			} else{
				if( isset( $config['rules_page'] ) && isset( $oPage->aPages[$config['rules_page']] ) ){
					$oTpl->assign( 'sRulesLink', $oPage->aPages[$config['rules_page']]['sLinkName'] );
				}
				$sUsersPanel = $oTpl->parse( 'users_register.tpl' );
			}
		}
		if( isset( $config['profile_page'] ) && is_numeric( $config['profile_page'] ) && $iContent == $config['profile_page'] ){
			if( isset( $_SESSION['iUserClient'] ) ){
				if( isset( $_POST['sOption'] ) && $_POST['sOption'] == 'save' ){
					if( ( !empty( $_POST['sPass'] ) || !empty( $_POST['sPass2'] ) ) && $_POST['sPass'] != $_POST['sPass2'] ){
						$sUsersPanel = $lang['Password_dont_mach'];
					} elseif( checkUserLoginNotExist( $_POST['sEmail'], $_SESSION['iUserClient'] ) != true ){
						$sUsersPanel = $lang['User_exists'];
					} else{
						/**** SALESMANAGO ****/
						if( $oSalesManago->checkSettings() === true ){
							$aUserData = throwUser( $_SESSION['iUserClient'] );
							$_SESSION['sEmail'] = $aUserData['sEmail'];
							$aTmp = $oSalesManago->upsertContact( $_POST );
						}
						/**** END SALESMANAGO ****/
						
						saveUser( $_POST, $_SESSION['iUserClient'] );
						$aUserData = throwUser( $_SESSION['iUserClient'] );
						$_SESSION['sUserName'] = $aUserData['sFirstName'] . ' ' . $aUserData['sLastName'];
						$_SESSION['sUserEmail'] = $aUserData['sEmail'];
						$_SESSION['sUserPhone'] = $aUserData['sPhone'];
						$oTpl->assign( 'aMessage', Array( 'message' => $lang['Operation_completed'] ) );
						$sUsersPanel = $oTpl->parse( 'message.tpl' );
					}
				} else{
					$aUserProfile = throwUser( $_SESSION['iUserClient'] );
					$aCountries = $oOrder->throwCountriesArray( 'iCountry', 'sCountry', true );
//					$aRegions = $oDB->executeSQL( 'SELECT `iRegion`, `iCountry`, `sRegion` FROM `' . $oDB->throwTableName( DB_REGIONS ) . '` ORDER BY `iCountry`, `iRegion`', true ); //Póki co nieużywane
					$oTpl->assign( 'aUserProfile', $aUserProfile );
					$oTpl->assign( 'aCountries', $aCountries );
//					$oTpl->assign( 'aRegions', $aRegions );
					$sUsersPanel = $oTpl->parse( 'users_profile.tpl' );
				}
			} else $bRedirectToLogin = true;
		}
		if( isset( $config['user_orders_page'] ) && is_numeric( $config['user_orders_page'] ) && $iContent == $config['user_orders_page'] ){
			if( isset( $_SESSION['iUserClient'] ) ){
				if( isset( $iOrder ) && is_numeric( $iOrder ) ){
					$aOrder = $oOrder->throwOrder( $iOrder );
					if( $aOrder['iUser'] == $_SESSION['iUserClient'] ){
						if( isset( $_GET['a'] ) && $_GET['a'] == 'addToBasket' ){
							$aProducts = $oDB->executeSQL( 'SELECT `iProductVariant`, `iQuantity` FROM `' . $oDB->throwTableName( DB_ORDERS_PRODUCTS ) . '` WHERE `iOrder` = ' . $aOrder['iOrder'], true );
							foreach( $aProducts as $aProduct ){
								$oOrder->addVariantToBasket( $aProduct['iProductVariant'], $aProduct['iQuantity'] );
							}
							header( 'Location: ' . $oPage->getLinkName( $config['basket_page'] ) );
							exit;
						}
						require 'configure/lang_' . $aOrder['sLanguage'] . '.php';
						$aOrder['sComment'] = str_replace( '|n|', '<br />', $aOrder['sComment'] );
						//$aData['sLinkName'] = null;
						if( $config['gifts'] ){
							$aOrder['sGiftYesNo'] = throwYesNoTxt( $aOrder['iGift'] );
							$aOrder['sShowClientYesNo'] = throwYesNoTxt( $aOrder['iShowClient'] );
							if( $aOrder['iGift'] ) $aOrder['sGift'] = displayPrice( normalizePrice( $config['gift_cost'] ) );
							else $aOrder['sGift'] = '-';
						}
						$aOrder = array_merge( $aOrder, $oOrder->throwProducts( $iOrder, false ) );
						$aCountries = $oOrder->throwCountriesArray( );
						$aOrder['sCountry'] = $aCountries[$aOrder['iCountry']];
						$aOrder['sSummaryText'] = currency_in_text( $aOrder['fOrderSummary'] );
						$aOrder['sSummary'] = $aOrder['fOrderSummary'];
						$aOrder['account_id'] = preg_replace( '/[^0-9]/', '', $config['invoices_Account'] );
						$aOrder['sCompanyNameF'] = str_replace( '"', '\"', $aOrder['sCompanyName'] );
						$aOrder['sFirstNameF'] = str_replace( '"', '\"', $aOrder['sFirstName'] );
						$aOrder['sLastNameF'] = str_replace( '"', '\"', $aOrder['sLastName'] );
						$aOrder['aPayment'] = $oOrder->throwPayment( $aOrder['iPayment'] );
						$aOrder['aCarrier'] = $oOrder->throwCarrier( $aOrder['iCarrier'] );
						$oTpl->assign( 'aOrderInfo', $aOrder );
						$sUsersPanel = $oTpl->parse( 'users_order.tpl' );
						require DB_CONFIG_LANG;
					}
				} else $sUsersPanel = listUserOrders( $_SESSION['iUserClient'] );
				if( !isset( $sUsersPanel ) || empty( $sUsersPanel ) ){
					$oTpl->assign( 'aMessage', Array( 'message' => $lang['Data_not_found'], 'bError' => true ) );
					$sUsersPanel = $oTpl->parse( 'message.tpl' );
				}
			} else $bRedirectToLogin = true;
		}
		$iMainParent = $oPage->throwPagesMainParent( $iContent );
		if( ( isset( $iMainParent ) && $oPage->checkPageAuthorizedNotPassed( $iMainParent ) ) || !isset( $iMainParent ) || isset( $oPage->aPagesAuthorizationRemoved[$iContent] ) ){
			$aUrl = parse_url( $_SERVER['REQUEST_URI'] );
			if( !isset( $aUrl['host'] ) ) $aUrl['host'] = null;
			if( !isset( $aUrl['path'] ) ) $aUrl['path'] = null;
			if( isset( $aUrl['query'] ) ) $aUrl['query'] = '?' . $aUrl['query'];
			else $aUrl['query'] = null;
			$_SESSION['sRedirectAfterLogin'] = 'http' . ( $_SERVER['HTTPS'] ? 's' : '' ) . '://' . $_SERVER['HTTP_HOST'] . $aUrl['host'] . $aUrl['path'] . $aUrl['query'];
			$bRedirectToLogin = true;
		}
		if( isset( $bRedirectToLogin ) && $bRedirectToLogin === true ){
			if( !defined( 'INDEX' ) ) define( 'INDEX', $_SERVER['PHP_SELF'] );
			if( isset( $_SESSION['iUserClient'] ) || !isset( $config['login_page'] ) || !is_numeric( $config['login_page'] ) || !isset( $oPage->aPages[$config['login_page']]['sLinkName'] ) ) $sLink = INDEX;
			else $sLink = $oPage->aPages[$config['login_page']]['sLinkName'];
			header( 'Location: ' . $sLink );
			exit;
		}
	}
	if( empty( $config[base64_decode( 'Zm9vdF9pbmZv' ) ] ) ){
		$aFI = Array(
			'Q29weXJpZ2h0ICYjMTY5OyAyMDE3PGJyLz5Ta2xlcCBpbnRlcm5ldG93eSA8YSBocmVmPSJodHRwOi8vd3d3LnNlbGxzbWFydC5wbC8iPnNlbGw8c3Ryb25nPnNtYXJ0PC9zdHJvbmc+LnBsPC9hPjxici8+UHJvamVrdCBpIHd5a29uYW5pZSA8YSBocmVmPSJodHRwOi8vd3d3LmxhYnNxbC5wbC8iPkxhYjxzdHJvbmc+U1FMPC9zdHJvbmc+LnBsPC9hPg==',
			'Q29weXJpZ2h0ICYjMTY5OyAyMDE3PGJyLz5Ta2xlcHkgaW50ZXJuZXRvd2UgPGEgaHJlZj0iaHR0cDovL3d3dy5zZWxsc21hcnQucGwvIj5zZWxsPHN0cm9uZz5zbWFydDwvc3Ryb25nPi5wbDwvYT48YnIvPlByb2pla3QgaSB3eWtvbmFuaWUgPGEgaHJlZj0iaHR0cDovL3d3dy5sYWJzcWwucGwvIj5MYWI8c3Ryb25nPlNRTDwvc3Ryb25nPi5wbDwvYT4=',
			'Q29weXJpZ2h0ICYjMTY5OyAyMDE3PGJyLz5Qcm9ncmFtIHNrbGVwdSBXV1cgPGEgaHJlZj0iaHR0cDovL3d3dy5zZWxsc21hcnQucGwvIj5zZWxsPHN0cm9uZz5zbWFydDwvc3Ryb25nPi5wbDwvYT48YnIvPlByb2pla3QgaSB3eWtvbmFuaWUgPGEgaHJlZj0iaHR0cDovL3d3dy5sYWJzcWwucGwvIj5MYWI8c3Ryb25nPlNRTDwvc3Ryb25nPi5wbDwvYT4=',
			'Q29weXJpZ2h0ICYjMTY5OyAyMDE3PGJyLz5PcHJvZ3JhbW93YW5pZSBza2xlcHUgPGEgaHJlZj0iaHR0cDovL3d3dy5zZWxsc21hcnQucGwvIj5zZWxsPHN0cm9uZz5zbWFydDwvc3Ryb25nPjwvYT48YnIvPlByb2pla3QgaSB3eWtvbmFuaWUgPGEgaHJlZj0iaHR0cDovL3d3dy5sYWJzcWwucGwvIj5MYWI8c3Ryb25nPlNRTDwvc3Ryb25nPi5wbDwvYT4=',
			'Q29weXJpZ2h0ICYjMTY5OyAyMDE3PGJyLz5FLXNrbGVwIFdXVyA8YSBocmVmPSJodHRwOi8vd3d3LnNlbGxzbWFydC5wbC8iPnNlbGw8c3Ryb25nPnNtYXJ0PC9zdHJvbmc+LnBsPC9hPjxici8+UHJvamVrdCBpIHd5a29uYW5pZSA8YSBocmVmPSJodHRwOi8vd3d3LmxhYnNxbC5wbC8iPkxhYjxzdHJvbmc+U1FMPC9zdHJvbmc+LnBsPC9hPg==',
			'Q29weXJpZ2h0ICYjMTY5OyAyMDE3PGJyLz5Qcm9ncmFtIGUtc2tsZXB1IDxhIGhyZWY9Imh0dHA6Ly93d3cuc2VsbHNtYXJ0LnBsLyI+c2VsbDxzdHJvbmc+c21hcnQ8L3N0cm9uZz4ucGw8L2E+PGJyLz5Qcm9qZWt0IGkgd3lrb25hbmllIDxhIGhyZWY9Imh0dHA6Ly93d3cubGFic3FsLnBsLyI+TGFiPHN0cm9uZz5TUUw8L3N0cm9uZz4ucGw8L2E+',
		);
		$config[base64_decode( 'Zm9vdF9pbmZv' ) ] = base64_decode( $aFI[$iContent % 6] );
		$oTpl->assign( 'config', $config );
	}
	if( isset( $aData ) ){
		if( !empty( $aData['sUrl'] ) ){
			header( 'Location: ' . $aData['sUrl'] );
			exit;
		}

		//Przed blokami, bo inaczej nie działało :)
		if( isset( $_GET['iProductStorageAdd'] ) && is_numeric( $_GET['iProductStorageAdd'] ) ){
			$oProduct->addToStorage( $_GET['iProductStorageAdd'] );
			$aProduct = $oProduct->throwProduct( $_GET['iProductStorageAdd'] );
			saveUserAction( Array( 'iProduct' => $_GET['iProductStorageAdd'], 'iType' => 3 /* 1 - otworzenie, 2 - porównanie, 3 - dodanie do schowka, 4 - dodanie do koszyka */, 'fPrice' => $aProduct['bTimePromotionActive'] ? $aProduct['fTimePrice'] : $aProduct['fCatalogPrice'], 'iAvailable' => $aProduct['TiAvailable'] ) );
			$aStorageInfo['aProducts'] = $oProduct->listProductsStorage( );
			if( $oSalesManago->checkSettings() === true && isset( $_SESSION['sUserEmail'] ) && $_SESSION['sUserEmail'] != "" ) $oSalesManago->addEventContact( 'OTHER', $aStorageInfo['aProducts']['aList'], $_SESSION );
		}
		if( isset( $_GET['iProductStorageRemove'] ) && is_numeric( $_GET['iProductStorageRemove'] ) ){
			$oProduct->removeFromStorage( $_GET['iProductStorageRemove'] );
		}
		
		if( $config['filter_products_module'] && ( isset( $_GET['aFilterAttributes'] ) || isset( $_GET['aFilterSelectAttributes'] ) || isset( $_GET['fFilterPriceFrom'] ) || isset( $_GET['fFilterPriceTo'] ) ) ){
			$sAddUrlExt = null;
			if( is_array( $_GET['aFilterSelectAttributes'] ) ) foreach( $_GET['aFilterSelectAttributes'] as $iAttribute => &$aValues ){
				if( is_numeric( $iAttribute ) ){
					if( is_array( $aValues ) ) foreach( $aValues as $iValue ) if( is_numeric( $iValue ) || ( is_string( $iValue ) && preg_match( '/^g[0-9]+$/', $iValue ) ) ){
						$_GET['aFilterAttributes'][$iAttribute][$iValue] = 1;
					}
				}
			}
			if( is_array( $_GET['aFilterAttributes'] ) ) foreach( $_GET['aFilterAttributes'] as $iAttribute => &$aValues ){
				if( is_numeric( $iAttribute ) ){
					if( is_numeric( $aValues ) || ( is_string( $aValues ) && preg_match( '/^g[0-9]+$/', $aValues ) ) ){
						$aValues = Array( $aValues => 1 );
					}
					if( is_array( $aValues ) ){
						foreach( $aValues as $iValue => $sValue ){
							if( ( is_numeric( $iValue ) || preg_match( '/^g[0-9]+$/', $iValue ) ) && $sValue == 1 ){
								$sAddUrlExt.= '&amp;aFilterAttributes[' . $iAttribute . '][' . $iValue . ']=1';
							}
						}
					} else{
						$aValues = null;
						unset( $_GET['aFilterAttributes'][$iAttribute] );
					}
				}
			}
			if( isset( $fFilterPriceFrom ) ){
				$sAddUrlExt.= '&amp;fFilterPriceFrom=' . $fFilterPriceFrom;
			}
			if( isset( $fFilterPriceTo ) ){
				$sAddUrlExt.= '&amp;fFilterPriceTo=' . $fFilterPriceTo;
			}
			$sUrlExt.= empty( $sUrlExt ) ? preg_replace( '/\\&(amp\\;)?/', '?', $sAddUrlExt, 1 ) : $sAddUrlExt;
		}

		$iStatus = throwStatus();
		$aData['aBlocks'] = $oDB->executeSQL( 'SELECT * FROM `' . $oDB->throwTableName( DB_PAGES_BLOCKS ) . '` WHERE `iPage` = ' . intval( $iContent ) . ' AND `iStatus` >= ' . $iStatus . ' ORDER BY `iPosition` ASC', true );
		$aData['sDescriptionFull'] = null;
		
		foreach( $aData['aBlocks'] as $iBlockIteration => &$aBlock ){
			switch( $aBlock['sType'] ){
				case 'TEXT':
										$aBlock['sText'] = parseSpecials( $aBlock['sText'] );
										if( empty( $aBlock['sText'] ) ){
											unset( $aData['aBlocks'][$iBlockIteration] );
											continue;
										}
										$aData['sDescriptionFull'] .= $aBlock['sText'];
										break;
				case 'FORM':
										$aBlock['aForm'] = $oDB->executeSQL( 'SELECT `sTitle`, `sEmail` FROM `' . $oDB->throwTableName( DB_FORMS ) . '` WHERE `iForm` = ' . $aBlock['iForm'], true, DataBase::SINGLE_RECORD );
										if( empty( $aBlock['aForm'] ) ){
											unset( $aData['aBlocks'][$iBlockIteration] );
											continue;
										}
										$aBlock['aFormFields'] = $oDB->executeSQL( 'SELECT `iFormField`, `sName`, `iRequired`, `iEmail`, `sType`, GROUP_CONCAT( `sValue` SEPARATOR \';\' ) `aValues` FROM `' . $oDB->throwTableName( DB_FORMS_FIELDS ) . '` LEFT JOIN `' . $oDB->throwTableName( DB_FORMS_FIELDS_VALUES ) . '` USING( `iFormField` ) WHERE `iForm` = ' . $aBlock['iForm'] . ' GROUP BY `iFormField`', true );
										foreach( $aBlock['aFormFields'] as &$aField ){
											$aField['aValues'] = explode( ';', $aField['aValues'] );
											$aField['aValues'] = array_combine( $aField['aValues'], $aField['aValues'] );
										}
										if( isset( $_POST['commit_' . $aBlock['iElement']] ) ){
											//Wyślij e-mail
											if (!$oReCaptcha->verify($_POST['g-recaptcha-response'],$_SERVER['REMOTE_ADDR'])){
												header( 'Location: ' . $sUserPage . ( strpos( $sUserPage, '?' ) !== false ? '&' : '?' ) . 'mes=message_reCaptchaTimeout' );
												exit;
											}
											$sMailContent = '<table class="details">';
											foreach( $aBlock['aFormFields'] as $aFieldSend ){
												$sMailContent .= '<tr><td class="name">' . $aFieldSend['sName'] . ':</td><td>';

												if( $aFieldSend['sType'] == 'CHECKBOX' ){
													$_POST['field_' . $aFieldSend['iFormField']] = implode( ', ', $_POST['field_' . $aFieldSend['iFormField']] );
												}
												$sMailContent .= $_POST['field_' . $aFieldSend['iFormField']];
												if( $aFieldSend['iEmail'] ) $sSender = $_POST['field_' . $aFieldSend['iFormField']];

												$sMailContent .= "</td></tr>\n";
											}
											$sMailContent .= "</table>";
											
											$oDB->executeSQL( 'UPDATE `' . $oDB->throwTableName( DB_USER_ACTIONS ) . '` SET `sEmail` = \'' . $oDB->escape( $sSender ) . '\' WHERE `sEmail` IS NULL AND `iCustomer` = ' . $_SESSION['iCustomer' . LANGUAGE] );
											$aData['bEmailSend'] = sendEmail( Array( 'sTopic' => $aBlock['aForm']['sTitle'], 'sMailContent' => strip_tags( $sMailContent ), 'sHtmlContent' => $sMailContent, 'sSender' => $sSender ), $aBlock['aForm']['sEmail'] );

											if( $config['sms_send_new_contact_to_admin'] == 1 && !empty( $config['sms_admin_phone'] ) ){
												$aLangOld = $lang;
												include( DIR_LANG . 'admin.php' );
												$sText = str_replace( Array( '%sShopName%', '|n|' ), Array( $GLOBALS['config']['website_name'], "\n" ), $lang['sms_send_new_contact_to_admin'] );
												$oSMS = new SMS( $GLOBALS['config']['serwersms_login'], $GLOBALS['config']['serwersms_password'] );
												$oSMS->sendSMS_delay( $GLOBALS['config']['sms_admin_phone'], $sText );
												$lang = $aLangOld;
											}
											if( $aData['bEmailSend'] ){
												header( 'Location: ' . $sUserPage . ( strpos( $sUserPage, '?' ) !== false ? '&' : '?' ) . 'mes=message_send' );
												exit();
											} else{
												header( 'Location: ' . $sUserPage . ( strpos( $sUserPage, '?' ) !== false ? '&' : '?' ) . 'mes=message_error' );
												exit();
											}
										}
										break;
				case 'FORUM':
										$iElementsForum = 10;
										if( !empty( $iPage ) && is_numeric( $iPage ) ){
											$iStart = ( $iPage - 1 ) * $iElementsForum;
										} else{
											$iStart = 0;
											$iPage = 1;
										}
										
										$bModerator = false;
										if( $_SESSION['bSellSmartUser'] ){
											if( $_SESSION['iAdminId'] == -1 ){
												$bModerator = true;
											} else{
												$bModerator = $oDB->executeSQL( 'SELECT 1 FROM `' . $oDB->throwTableName( DB_ADMINS_PRIVILAGES ) . '` WHERE `iAdmin` = ' . intval( $_SESSION['iAdminId'] ) . ' AND `sActions` = \'forum\'', true, DataBase::SINGLE_VALUE );
											}
										}

										if( isset( $config['login_page'] ) && is_numeric( $config['login_page'] ) && isset( $oPage->aPages[$config['login_page']]['sLinkName'] ) ){
											$aBlock['sLinkLogin'] = $oPage->aPages[$config['login_page']]['sLinkName'];
										}

										if( !isset( $iTopic ) || intval( $iTopic ) < 1 ){
											if( !empty( $_POST['sText'] ) && !empty( $_POST['sTopic'] ) && !empty( $_SESSION['iUserClient'] ) ){
												$iTopic = $oDB->save( DB_TOPICS, Array( 'iPage' => $aData['iPage'], 'iUser' => $_SESSION['iUserClient'], 'iLastUser' => $_SESSION['iUserClient'], 'sTopic' => $oDB->escape( $_POST['sTopic'] ), 'iTime' => time(), 'iLastPost' => time(), 'iPosts' => 1 ) );
												$oDB->save( DB_POSTS, Array( 'iTopic' => intval( $iTopic ), 'iUser' => $_SESSION['iUserClient'], 'sText' => $oDB->escape( $_POST['sText'] ), 'iTime' => time() ) );
												
												if( $config['sms_send_forum_notify_admin'] == 1 && !empty( $config['sms_admin_phone'] ) ){
													$aLangOld = $lang;
													include( DIR_LANG . 'admin.php' );
													$sText = str_replace( Array( '%sShopName%', '|n|' ), Array( $GLOBALS['config']['website_name'], "\n" ), $lang['sms_send_forum_notify_admin_text'] );
													$oSMS = new SMS( $GLOBALS['config']['serwersms_login'], $GLOBALS['config']['serwersms_password'] );
													$oSMS->sendSMS_delay( $GLOBALS['config']['sms_admin_phone'], $sText );
													$lang = $aLangOld;
												}

												
												if( $config['email_send_forum_notify_admin'] == 1 ){
													$sIndex = ( !isset( $config['index'] ) || ( isset( $config['index'] ) && ( $config['index'] == '?' || $config['index'] == 'index.html' ) ) ) ? $_SERVER['PHP_SELF'] : $config['index'];
													$sIndex = ( dirname( $sIndex ) == '.' ) ? '/' : dirname( $sIndex ) . '/';
													$aLangOld = $lang;
													include( DIR_LANG . 'admin.php' );
													$aForm['sMailContent'] = str_replace( Array( '%sLink%', '|n|' ), Array( 'http' . ( $_SERVER['HTTPS'] ? 's' : '' ) . '://' . $_SERVER['SERVER_NAME'] . $sIndex . $aData['sLinkName'] . '?iTopic=' . intval( $iTopic ), "\n" ), $lang['email_send_forum_notify_admin_text'] );
													$aForm['sTopic'] = $lang['forum_topic_email_topic'];
													$lang = $aLangOld;
													$aForm['sName'] = '';
													$aForm['sSender'] = $config['email'];
													sendEmail( $aForm, $config['email'] );
												}
												
											}
											if( $bModerator ){
												if( !empty( $iTopicDelete ) ){
													$oDB->deleteInFile( DB_POSTS, $iTopicDelete, 'iTopic' );
													$oDB->deleteInFile( DB_TOPICS, $iTopicDelete, 'iTopic' );
												}
												if( !empty( $iTopicClose ) ){
													$oDB->update( DB_TOPICS, Array( 'iClosed' => 1 ), Array( 'iTopic' => $iTopicClose ) );
												}
												if( !empty( $iTopicOpen ) ){
													$oDB->update( DB_TOPICS, Array( 'iClosed' => 0 ), Array( 'iTopic' => $iTopicOpen ) );
												}
											}
											$aBlock['aForum']['aTopics'] = $oDB->executeSQL( 'SELECT SQL_CALC_FOUND_ROWS `iTopic`, `sTopic`, `iTime`, `u1`.`sLogin`, `iClosed`, `iViews`, `iPosts`, `iLastPost`, `u2`.`sLogin` AS `sLastLogin` FROM `' . $oDB->throwTableName( DB_TOPICS ) . '` INNER JOIN `' . $oDB->throwTableName( DB_USERS ) . '` `u1` USING( `iUser` ) INNER JOIN `' . $oDB->throwTableName( DB_USERS ) . '` `u2` ON( `u2`.`iUser` = `iLastUser` ) WHERE `iPage` = ' . $aData['iPage'] . ' ORDER BY `iTime` DESC LIMIT ' . intval( $iStart ) . ',' . intval( $iElementsForum ), true );
											$iTopicsAll = $oDB->executeSQL( 'SELECT FOUND_ROWS()', true, DataBase::SINGLE_VALUE );
											foreach( $aBlock['aForum']['aTopics'] as &$aTopic ){
												$aTopic['sLinkName'] = '?iTopic=' . $aTopic['iTopic'] . '-' . change2url( $aTopic['sTopic'] );
											}
											$aBlock['aForum']['bModerator'] = $bModerator;
											$aBlock['aForum']['aTopicsPages'] = Array( 'iCount' => ceil( $iTopicsAll / 10 ), 'iPageNumber' => $iPage );
										} else{
											if( !empty( $_POST['sText'] ) && !empty( $_SESSION['iUserClient'] ) ){
												if( !isset( $_POST['iPost'] ) ){
													$oDB->save( DB_POSTS, Array( 'iTopic' => intval( $iTopic ), 'iUser' => $_SESSION['iUserClient'], 'sText' => $oDB->escape( $_POST['sText'] ), 'iTime' => time() ) );
													$oDB->executeSQL( 'UPDATE `' . $oDB->throwTableName( DB_TOPICS ) . '` SET `iLastPost` = ' . time() . ', `iLastUser` = ' . intval( $_SESSION['iUserClient'] ) . ', `iPosts` = `iPosts` + 1 WHERE `iTopic` = ' . intval( $iTopic ) );
													
													$aNotifications = $oDB->executeSQL( 'SELECT DISTINCT `sEmail`, `sPhone`, `iForumNotifyEmail`, `iForumNotifySMS` FROM `' . $oDB->throwTableName( DB_POSTS ) . '` INNER JOIN `' . $oDB->throwTableName( DB_USERS ) . '` USING ( `iUser` ) WHERE `iTopic` = ' . intval( $iTopic ) . ' AND `iUser` != ' . intval( $_SESSION['iUserClient'] ), true );
													$aBlock['aForum']['aTopic'] = $oDB->executeSQL( 'SELECT `iTopic`, `sTopic` FROM `' . $oDB->throwTableName( DB_TOPICS ) . '` WHERE `iTopic` = ' . intval( $iTopic ), true, DataBase::SINGLE_RECORD );
													foreach( $aNotifications as $aNotification ){
														if( $config['sms_send_forum_notify_user'] && $aNotification['iForumNotifySMS'] && !empty( $aNotification['sPhone'] ) ){
															$sText = str_replace( Array( '%sShopName%', '%sTopic%', '|n|' ), Array( $config['website_name'], $aBlock['aForum']['aTopic']['sTopic'], "\n" ), $lang['sms_send_forum_notify_user_text'] );
															$oSMS = new SMS( $GLOBALS['config']['serwersms_login'], $GLOBALS['config']['serwersms_password'] );
															$oSMS->sendSMS_delay( $aNotification['sPhone'], $sText );
														}
														if( $aNotification['iForumNotifyEmail'] && !empty( $aNotification['sEmail'] ) ){
															$sIndex = ( !isset( $config['index'] ) || ( isset( $config['index'] ) && ( $config['index'] == '?' || $config['index'] == 'index.html' ) ) ) ? $_SERVER['PHP_SELF'] : $config['index'];
															$sIndex = ( dirname( $sIndex ) == '.' ) ? '/' : dirname( $sIndex ) . '/';
															$aForm['sMailContent'] = str_replace( Array( '%sTopic%', '%sLink%', '|n|' ), Array( $aBlock['aForum']['aTopic']['sTopic'], 'http' . ( $_SERVER['HTTPS'] ? 's' : '' ) . '://' . $_SERVER['SERVER_NAME'] . $sIndex . $aData['sLinkName'] . '?iTopic=' . intval( $iTopic ), "\n" ), $lang['email_send_forum_notify_user_text'] );
															$aForm['sTopic'] = $lang['forum_post_email_topic'];
															$aForm['sName'] = '';
															$aForm['sSender'] = $config['email'];
															sendEmail( $aForm, $aNotification['sEmail'] );
														}
													}
												} else{
													$aWhere = Array( 'iPost' => intval( $_POST['iPost'] ) );
													$aSet = Array( 'sText' => $oDB->escape( $_POST['sText'] ) );
													if( !$bModerator ){
														$aWhere['iUser'] = $_SESSION['iUserClient'];
														$aSet['iModificationTime'] = time();
													} else{
														$aSet['iModerationTime'] = time();
													}
													$oDB->update( DB_POSTS, $aSet, $aWhere );
												}
											} elseif( $_SESSION['bSellSmartUser'] && $bModerator ){
												if( isset( $iPostDelete ) ){
													$oDB->deleteInFile( DB_POSTS, $iPostDelete, 'iPost' );
													$oDB->executeSQL( 'UPDATE `' . $oDB->throwTableName( DB_TOPICS ) . '` SET `iPosts` = `iPosts` - 1 WHERE `iTopic` = ' . intval( $iTopic ) );
												} elseif( isset( $_POST['iPost'] ) ){
													$oDB->update( DB_POSTS, Array( 'sText' => $oDB->escape( $_POST['sText'] ), 'iModerationTime' => time() ), Array( 'iPost' => intval( $_POST['iPost'] ) ) );
												} elseif( isset( $_POST['sTopic'] ) ){
													$oDB->executeSQL( 'UPDATE `' . $oDB->throwTableName( DB_TOPICS ) . '` SET `sTopic` = \''.$oDB->escape( $_POST['sTopic'] ).'\' WHERE `iTopic` = ' . intval( $iTopic ) );
												}
											}
											$aBlock['aForum']['aTopic'] = $oDB->executeSQL( 'SELECT `iTopic`, `sTopic`, `iClosed` FROM `' . $oDB->throwTableName( DB_TOPICS ) . '` WHERE `iTopic` = ' . intval( $iTopic ), true, DataBase::SINGLE_RECORD );
											$aBlock['aForum']['aTopic']['sLinkName'] = '?iTopic=' . $aBlock['aForum']['aTopic']['iTopic'] . '-' . change2url( $aBlock['aForum']['aTopic']['sTopic'] );
											$oDB->executeSQL( 'UPDATE `' . $oDB->throwTableName( DB_TOPICS ) . '` SET `iViews` = `iViews` + 1 WHERE `iTopic` = ' . intval( $iTopic ) );
											$aBlock['aForum']['aPosts'] = $oDB->executeSQL( 'SELECT SQL_CALC_FOUND_ROWS `iPost`, `sText`, `iTime`, `iModificationTime`, `iUser`, `sLogin` FROM `' . $oDB->throwTableName( DB_POSTS ) . '` INNER JOIN `' . $oDB->throwTableName( DB_USERS ) . '` USING( `iUser` ) WHERE `iTopic` = ' . intval( $iTopic ) . ' ORDER BY `iTime` ASC LIMIT ' . intval( $iStart ) . ',' . intval( $iElementsForum ), true );
											$iPostsAll = $oDB->executeSQL( 'SELECT FOUND_ROWS()', true, DataBase::SINGLE_VALUE );
											foreach( $aBlock['aForum']['aPosts'] as &$aPost ){
												$aPost['sText'] = preg_replace( '(\\\\r\\\\n|\\\\r|\\\\n)', '<br/>', htmlspecialchars( $aPost['sText'] ) );
											}
											
											$aBlock['aForum']['bModerator'] = $bModerator;
											$aBlock['aForum']['aPostsPages'] = Array( 'iCount' => ceil( $iPostsAll / 10 ), 'iPageNumber' => $iPage );
										}
										break;
				case 'COMMENTS':
										if( isset( $_POST['sOption'] ) && $_POST['sOption'] == 'saveComment' && !empty( $_POST['sContent'] ) && !preg_match( "/(\[url)|(<a href=)/i", $_POST['sContent'] ) && !empty( $_POST['sName'] ) ){
											addComment( $_POST, $iContent );
											if( $config['sms_send_new_comment_to_admin'] == 1 && !empty( $config['sms_admin_phone'] ) ){
												$aLangOld = $lang;
												include( DIR_LANG . 'admin.php' );
												$sText = str_replace( Array( '%sShopName%', '|n|' ), Array( $GLOBALS['config']['website_name'], "\n" ), $lang['sms_send_new_comment_to_admin'] );
												$oSMS = new SMS( $GLOBALS['config']['serwersms_login'], $GLOBALS['config']['serwersms_password'] );
												$oSMS->sendSMS_delay( $GLOBALS['config']['sms_admin_phone'], $sText );
												$lang = $aLangOld;
											}
											$sIndex = ( !isset( $config['index'] ) || ( isset( $config['index'] ) && $config['index'] == '?' ) ) ? REDIRECT : null;
											header( 'Location: ' . $sIndex . $aData['sLinkName'] . ( strpos( $aData['sLinkName'], '?' ) !== false ? '&' : '?' ) . 'mes=comment_add' );
											exit;
										}
										$aBlock['aComments'] = throwComments( $iContent );
										break;
				case 'ADVSEARCHER':
										$aAdvsearcherColumns = $oDB->throwFileArraySmall( DB_ADVSEARCHER_COLUMNS, 'iColumn', 'sName' );
										if( empty( $aAdvsearcherColumns ) || !$config['show_advsearcher_form'] ){
											unset( $aData['aBlocks'][$iBlockIteration] );
											continue;
										}
										$iValue = -1;
										$bAuto0 = ( isset( $_GET['clear-advsearcher'] ) && $_GET['clear-advsearcher'] == 1 ) ? true : false;
										$sAdvsearcherPath = '';
										$aAdvsearcherValuesSelected = Array();
										foreach( $aAdvsearcherColumns as $iColumn => $sClumn ){
											if( $iValue == -1 ){
												$aAdvsearcherValues[$iColumn] = $oDB->throwFileArraySmall( DB_ADVSEARCHER_VALUES, 'iValue', 'sValue', null, Array( 'iColumn' => $iColumn ) );
											} elseif( $iValue > 0 ){
												$aAdvsearcherValues[$iColumn] = $oDB->throwFileArraySmall( DB_ADVSEARCHER_VALUES, 'iValue', 'sValue', null, Array( 'iParentValue' => $iValue ) );
											}
											if( $bAuto0 ) $_SESSION['iAdvsearcherValue_' . $iColumn] = null;
											elseif( isset( $_POST['aAdvsearcherValues'][$iColumn] ) && $_POST['aAdvsearcherValues'][$iColumn] == 0 ){ $_SESSION['iAdvsearcherValue_' . $iColumn] = null; $bAuto0 = true; }
											elseif( isset( $_POST['aAdvsearcherValues'][$iColumn] ) ) $_SESSION['iAdvsearcherValue_' . $iColumn] = $_POST['aAdvsearcherValues'][$iColumn];
											if( isset( $_SESSION['iAdvsearcherValue_' . $iColumn] ) ){
												$iValue = $_SESSION['iAdvsearcherValue_' . $iColumn];
												$sAdvsearcherPath .= ( empty( $sAdvsearcherPath ) ? null : ' &raquo; ' ) . $aAdvsearcherValues[$iColumn][$iValue];
												$aAdvsearcherValuesSelected[$iColumn] = $iValue;
											} else{
												$iValue = 0;
											}
										}
										$aBlock['sAdvsearcherPath'] = $sAdvsearcherPath;
										$aBlock['aAdvsearcherColumns'] = $aAdvsearcherColumns;
										$aBlock['aAdvsearcherValues'] = $aAdvsearcherValues;
										$aBlock['aAdvsearcherValuesSelected'] = $aAdvsearcherValuesSelected;
										if( isset( $_GET['clear-advsearcher'] ) && $_GET['clear-advsearcher'] == 1 ){
											header( 'Location: ' . $aData['sLinkName'] . '?' );
											exit;
										}
										break;
				case 'FILTER':
										if( !$config['filter_producers_module'] ){
											unset( $aData['aBlocks'][$iBlockIteration] );
											continue;
										}
										$aBlock['aFilterProducers'] = $oProduct->throwFilterProducers( $iContent );
										if( empty( $aBlock['aFilterProducers'] ) ){
											unset( $aData['aBlocks'][$iBlockIteration] );
											continue;
										}
										break;
				case 'GALLERY':
				case 'FILES':
				case 'VIDEO':
				case 'AUDIO':
										switch( $aBlock['sType'] ){
											case 'GALLERY':
												$iType = 5;
												break;
											case 'FILES':
												$iType = 1;
												break;
											case 'VIDEO':
												$iType = 9;
												break;
											case 'AUDIO':
												$iType = 8;
												break;
										}
										$aBlock['sFiles'] = $oFile->listFilesByTypes( $iContent, 1, 'media_%BLOCK%.tpl', $iType, $aBlock['iPositionMin'], $aBlock['iPositionMax'], $aBlock['iMinSize'], $aBlock['sSortFiles'] );
										if( empty( $aBlock['sFiles'] ) ){
											unset( $aData['aBlocks'][$iBlockIteration] );
											continue;
										}
										break;
				case 'SUBPAGES':
										$aBlock['aSubpages'] = $oPage->throwSubpagesBlock( $iContent, $aBlock['iElement'], $aBlock['iCount'], $aBlock['iSubpagesShow'], $aBlock['iPositionMin'], $aBlock['iPositionMax'] );
										if( empty( $aBlock['aSubpages']['aList'] ) ){
											unset( $aData['aBlocks'][$iBlockIteration] );
											continue;
										}
										break;
				case 'EXT_SUBPAGES':
										$aBlock['aSubpages'] = $oPage->throwSubpagesBlock( $aBlock['iAdditionalPage'], $aBlock['iElement'], $aBlock['iCount'], $aBlock['iSubpagesShow'], $aBlock['iPositionMin'], $aBlock['iPositionMax'] );
										if( empty( $aBlock['aSubpages']['aList'] ) ){
											unset( $aData['aBlocks'][$iBlockIteration] );
											continue;
										}
										break;
				case 'SITEMAP':
										$aBlock['aSiteMap'] = $oPage->listSiteMap( );
										if( empty( $aBlock['aSiteMap'] ) ){
											unset( $aData['aBlocks'][$iBlockIteration] );
											continue;
										}
										break;
				case 'POLL':
										if( isset( $_POST['poll_'.$aBlock['iElement']] ) && is_numeric( $_POST['poll_'.$aBlock['iElement']] ) ){
											savePollVote( $_POST['poll_'.$aBlock['iElement']] );
										}
										$aBlock['aPoll'] = throwPoll( $aBlock['iPoll'] );
										if( empty( $aBlock['aPoll'] ) ){
											unset( $aData['aBlocks'][$iBlockIteration] );
											continue;
										}
										break;
				case 'PRODUCTS':
										$_SESSION['sBackLink'] = $aData['sLinkName']; //Zapisanie aktualnej strony produktów do przycisku "Kontynuuj zakupy"

										/* count */
										$iCount = $config['products_list'];
										if( isset( $aBlock['iCount'] ) ) $iCount = $aBlock['iCount'];
										if( isset( $_POST['count_'.$aBlock['iElement']] ) ) $_SESSION['iCount_'.$aBlock['iElement']] = $_POST['count_'.$aBlock['iElement']];
										if( isset( $_SESSION['iCount_'.$aBlock['iElement']] ) ) $iCount = $_SESSION['iCount_'.$aBlock['iElement']];

										/* order */
										$sort_orders = Array( 'default' => '`products`.`iPosition` ASC, `products`.`sName` ASC, `products`.`iTime` ASC', 'price_inc' => '`products`.`fPrice` ASC', 'price_desc' => '`products`.`fPrice` DESC', 'name_inc' => '`products`.`sName` ASC', 'name_desc' => '`products`.`sName` DESC', 'date_inc' => '`products`.`iTime` ASC', 'date_desc' => '`products`.`iTime` DESC' );
										
										if( !isset( $aPromotedUsed ) ) $aPromotedUsed = $oDB->executeSQL( 'SELECT DISTINCT `iPromoted` FROM `' . $oDB->throwTableName( DB_PRODUCTS_PROMOTED ) . '` WHERE `iTimeValid` IS NULL OR `iTimeValid` > UNIX_TIMESTAMP()', true, DataBase::SINGLE_COLUMN );
										foreach( $aPromotedUsed as $iPromoted ){
											$sort_orders['promoted' . $iPromoted] = 'IF( EXISTS( SELECT 1 FROM `' . $oDB->throwTableName( DB_PRODUCTS_PROMOTED ) . '` `prom` WHERE `prom`.`iProduct` = `products`.`iProduct` AND `iPromoted` = ' . $iPromoted . ' AND ( `iTimeValid` IS NULL OR `iTimeValid` > UNIX_TIMESTAMP() ) LIMIT 1 ), 0, 1 ) ASC, `products`.`iPosition` ASC, `products`.`sName` ASC, `products`.`iTime` ASC';
										}
										$oTpl->assign( 'aPromotedUsed', $aPromotedUsed );
										
										$sSortOpt = 'default';
										if( isset( $_POST['sort_'.$aBlock['iElement']] ) && isset( $sort_orders[$_POST['sort_'.$aBlock['iElement']]] ) ) $_SESSION['sort_'.$aBlock['iElement']] = $_POST['sort_'.$aBlock['iElement']];
										if( isset( $_SESSION['sort_'.$aBlock['iElement']] ) ) $sSortOpt = $_SESSION['sort_'.$aBlock['iElement']];
										$sSort = $sort_orders[$sSortOpt];

										/* get */
										$aBlock['aProducts'] = $oProduct->throwProductsBlock( $iContent, $aBlock['iElement'], $iCount, $sSort, null, $aBlock['iPositionMin'], $aBlock['iPositionMax'] );
										$aBlock['aProducts']['sort_order'] = $sSortOpt;
										
										if( $config['filter_products_module'] && $aBlock['aProducts'] && ( !isset( $sPhrase ) || $config['page_search'] != $iContent ) ){
											$aData['aFilterProducts'] = $oProduct->throwFilterForm( $iContent );
										}
										
										if( !isset( $aBlock['aProducts'] ) || empty( $aBlock['aProducts']['aList'] ) ){
											$aBlock['bExtras'] = true;
										} else{
											$aBlock['bExtras'] = false;
										}
										
										if( ( !isset( $aBlock['aProducts'] ) || empty( $aBlock['aProducts']['aList'] ) ) && !empty( $config['storage_page'] ) && $config['storage_page'] == $iContent ) $aBlock['aProducts'] = $oProduct->listProductsStorage( $iContent, $iCount, $aBlock['iElement'] );
										if( ( !isset( $aBlock['aProducts'] ) || empty( $aBlock['aProducts']['aList'] ) ) && !empty( $config['bestsellers_page'] ) && $config['bestsellers_page'] == $iContent ) $aBlock['aProducts'] = $oProduct->listBestsellersProducts( $iContent, $iCount, $aBlock['iElement'] );
										if( ( !isset( $aBlock['aProducts'] ) || empty( $aBlock['aProducts']['aList'] ) ) && !empty( $config['products_time_page'] ) && $config['products_time_page'] == $iContent ) $aBlock['aProducts'] = $oProduct->listProductsTime( $iContent, $iCount, $aBlock['iElement'] );
										if( ( !isset( $aBlock['aProducts'] ) || empty( $aBlock['aProducts']['aList'] ) ) && !empty( $config['discounted_page'] ) && $config['discounted_page'] == $iContent ) $aBlock['aProducts'] = $oProduct->listProductsDiscounted( $iContent, $iCount, $aBlock['iElement'] );
										if( ( !isset( $aBlock['aProducts'] ) || empty( $aBlock['aProducts']['aList'] ) ) && !empty( $config['random_page'] ) && $config['random_page'] == $iContent ) $aBlock['aProducts'] = $oProduct->listRandomProducts( $iContent, $iCount, $aBlock['iElement'] );
										if( ( !isset( $aBlock['aProducts'] ) || empty( $aBlock['aProducts']['aList'] ) ) && !empty( $config['new_products_page'] ) && $config['new_products_page'] == $iContent ) $aBlock['aProducts'] = $oProduct->listNewProducts( $iContent, $iCount, $aBlock['iElement'] );
										if( ( !isset( $aBlock['aProducts'] ) || empty( $aBlock['aProducts']['aList'] ) ) && !empty( $config['last_visited_page'] ) && $config['last_visited_page'] == $iContent ) $aBlock['aProducts'] = $oProduct->listLastVisitedProducts( $iContent, $iCount, $aBlock['iElement'] );
										if( ( !isset( $aBlock['aProducts'] ) || empty( $aBlock['aProducts']['aList'] ) ) && !empty( $config['popular_page'] ) && $config['popular_page'] == $iContent ) $aBlock['aProducts'] = $oProduct->listPopularProducts( $iContent, $iCount, $aBlock['iElement'] );
										for( $i = 1; $i <= $config['promoted_types']; $i++ ){
											if( ( !isset( $aBlock['aProducts'] ) || empty( $aBlock['aProducts']['aList'] ) ) && !empty( $config['promoted' . $i . '_page'] ) && $config['promoted' . $i . '_page'] == $iContent ){
												$sFunction = 'listProductsPromoted' . $i . '_page';
												$aBlock['aProducts'] = $oProduct->$sFunction( $iContent, $iCount, $aBlock['iElement'] );
											}
										}
										if( isset( $config['user_ordered_products_page'] ) && is_numeric( $config['user_ordered_products_page'] ) && $iContent == $config['user_ordered_products_page'] ){
											$aBlock['aProducts'] = $oProduct->listBestsellersProducts( $iContent, 1000, $aBlock['iElement'], false, $_SESSION['iUserClient'] );
										}
										break;
				case 'HL':
										if( $aBlock['sHlFunction'] == 'throwProducts' ){
											$aBlock['aProducts'] = $oProduct->throwProductsBlock( $aBlock['iAdditionalPage'], $aBlock['iElement'], $aBlock['iCount'], 'RAND()', null, null, null, true );
										} else{
											$aBlock['aProducts'] = $oProduct->{$aBlock['sHlFunction']}( -1, $aBlock['iCount'], $aBlock['iElement'], true );
										}
										$aBlock['aMorePage'] = $oPage->aPages[$aBlock['iAdditionalPage']];
										if( empty( $aBlock['aProducts']['aList'] ) ){
											unset( $aData['aBlocks'][$iBlockIteration] );
											continue;
										}
										break;
				case 'BANNER':
										//$aBanners = $oDB->executeSQL( 'SELECT `iBanner`, `
										$aBlock['aBanner'] = throwBanners( Array( 3 => 'x' ), $aBlock['iPositionMin'], $aBlock['iPositionMax'] );
										if( empty( $aBlock['aBanner'] ) ){
											unset( $aData['aBlocks'][$iBlockIteration] );
											continue;
										}
										break;
			}
		}
		
		if( !empty( $aData['iRss'] ) ){
			$aData['sRssUrl'] = throwRssUrl( $iContent, $aData['sLinkName'] );
		}
		$aData['aPagesTree'] = $oPage->getPagesTree( $iContent );
		$sMetaPageTree = '';
		foreach( $aData['aPagesTree']['aPath'] as $aPage ) $sMetaPageTree.= ', ' . $aPage['sName'];
		if( !empty( $aData['iAdmin'] ) ){
			$aData['sSignature'] = throwAdmin( $aData['iAdmin'], true );
		}
		$oPage->mData = null;
		$sSubpagesList = null;
#		if( $aData['iProducts'] == 1 || ( isset( $sPhrase ) && $config['page_search'] == $iContent ) ){
#			$aData['aProducts'] = $oProduct->throwProducts( $iContent, $iList );
#			if( isset( $_GET['aFilterAttributes'] ) ) $aData['aProducts']['bFilter'] = true;
#		}
#		if( $config['filter_products_module'] && $aData['aProducts'] && ( !isset( $sPhrase ) || $config['page_search'] != $iContent ) ){
#			$aData['aFilterProducts'] = $oProduct->throwFilterForm( $iContent );
#		}
#		if( $config['filter_producers_module'] && $aData['aProducts'] && ( !isset( $sPhrase ) || $config['page_search'] != $iContent ) ){
#			$aData['aFilterProducers'] = $oProduct->throwFilterProducers( $iContent );
#		}
#		if( ( !isset( $aData['aProducts'] ) || empty( $aData['aProducts']['aList'] ) ) && !empty( $config['storage_page'] ) && $config['storage_page'] == $iContent ) $aData['aProducts'] = $oProduct->listProductsStorage( $iContent, $iList );
#		if( ( !isset( $aData['aProducts'] ) || empty( $aData['aProducts']['aList'] ) ) && !empty( $config['bestsellers_page'] ) && $config['bestsellers_page'] == $iContent ) $aData['aProducts'] = $oProduct->listBestsellersProducts( $iContent, $iList );
#		if( ( !isset( $aData['aProducts'] ) || empty( $aData['aProducts']['aList'] ) ) && !empty( $config['products_time_page'] ) && $config['products_time_page'] == $iContent ) $aData['aProducts'] = $oProduct->listProductsTime( $iContent, $iList );
#		if( ( !isset( $aData['aProducts'] ) || empty( $aData['aProducts']['aList'] ) ) && !empty( $config['discounted_page'] ) && $config['discounted_page'] == $iContent ) $aData['aProducts'] = $oProduct->listProductsDiscounted( $iContent, $iList );
#		if( ( !isset( $aData['aProducts'] ) || empty( $aData['aProducts']['aList'] ) ) && !empty( $config['random_page'] ) && $config['random_page'] == $iContent ) $aData['aProducts'] = $oProduct->listRandomProducts( $iContent, $iList );
#		if( ( !isset( $aData['aProducts'] ) || empty( $aData['aProducts']['aList'] ) ) && !empty( $config['new_products_page'] ) && $config['new_products_page'] == $iContent ) $aData['aProducts'] = $oProduct->listNewProducts( $iContent, $iList );
#		if( ( !isset( $aData['aProducts'] ) || empty( $aData['aProducts']['aList'] ) ) && !empty( $config['last_visited_page'] ) && $config['last_visited_page'] == $iContent ) $aData['aProducts'] = $oProduct->listLastVisitedProducts( $iContent, $iList );
#		if( ( !isset( $aData['aProducts'] ) || empty( $aData['aProducts']['aList'] ) ) && !empty( $config['popular_page'] ) && $config['popular_page'] == $iContent ) $aData['aProducts'] = $oProduct->listPopularProducts( $iContent, $iList );
#		for( $i = 1; $i <= $config['promoted_types']; $i++ ){
#			if( ( !isset( $aData['aProducts'] ) || empty( $aData['aProducts']['aList'] ) ) && !empty( $config['promoted' . $i . '_page'] ) && $config['promoted' . $i . '_page'] == $iContent ){
#				$sFunction = 'listProductsPromoted' . $i . '_page';
#				$aData['aProducts'] = $oProduct->$sFunction( $iContent, $iList );
#			}
#		}
##		if( ( !isset( $aData['aProducts'] ) || empty( $aData['aProducts']['aList'] ) ) && !empty( $config['promoted_page'] ) && $config['promoted_page'] == $iContent ) $aData['aProducts'] = $oProduct->listPromotedProducts( $iContent, $iList );
##		if( ( !isset( $aData['aProducts'] ) || empty( $aData['aProducts']['aList'] ) ) && !empty( $config['terminating_page'] ) && $config['terminating_page'] == $iContent ) $aData['aProducts'] = $oProduct->listProductsTerminating( $iContent, $iList );
##		if( ( !isset( $aData['aProducts'] ) || empty( $aData['aProducts']['aList'] ) ) && !empty( $config['sellout_page'] ) && $config['sellout_page'] == $iContent ) $aData['aProducts'] = $oProduct->listProductsSellOut( $iContent, $iList );
//		if( $aData['iSubpagesShow'] > 0 ){
//			$aData['aSubpages'] = $oPage->throwSubpages( $iContent, ( $aData['iSubpagesShow'] == 4 || $aData['iSubpagesShow'] == 10 ? null : $config['news_list'] ), '`iPosition` ASC, `iTime` DESC, `iPage` DESC' );
//		}
		if( isset( $sPhrase ) && $config['page_search'] == $iContent && empty( $sProductsList ) && empty( $sSubpagesList ) ){
			$oTpl->assign( 'aMessage', Array( 'message' => $lang['Data_not_found'], 'bError' => true ) );
			$sProductsList = $oTpl->parse( 'message.tpl' );
		}
		if( $config['page_search'] == $iContent ){
			$aData['aSearchData'] = Array( 'aProducers' => throwProducers( ), 'iProducer' => isset( $iProducer ) ? $iProducer : null, 'aAttributes' => throwAttributesValuesSelects( ), 'aSelectedAttributes' => $aAttributeValue, 'aSearchCategories' => $oPage->throwCategories( $config['search_category'], $iCategory, 0 ), 'sPhrase' => $sPhrase, 'sPriceFrom' => $sPriceFrom, 'sPriceTo' => $sPriceTo, 'sCatalogNumber' => $sCatalogNumber, 'sProductIndex' => $sProductIndex );
		}
		if( empty( $aData['sDescriptionFull'] ) ){
			$aData['sDescriptionFull'] = $aData['sDescriptionShort'];
			$aData['sDescriptionFull'] = changeTxt( $aData['sDescriptionFull'], 'nlNds' );
			$aData['sDescriptionFull'] = parseSpecials( $aData['sDescriptionFull'] );
		}
		if( !empty( $aData['sNameTitle'] ) ) $sTitle = strip_tags( $aData['sNameTitle'] );
		else $sTitle = strip_tags( ( empty( $aData['sDisplayTitle'] ) ? $aData['sName'] : $aData['sDisplayTitle'] ) . ( !empty( $sMetaPageTree ) ? ' -' . str_replace( ',', '', $sMetaPageTree ) : null ) . ( !empty( $config['title'] ) ? ' - ' . $config['title'] : null ) );
		if( !empty( $aData['sMetaKeywords'] ) ) $sKeywords = $aData['sMetaKeywords'];
		else $sKeywords = ( empty( $aData['sDisplayTitle'] ) ? $aData['sName'] : $aData['sDisplayTitle'] ) . $sMetaPageTree . ( !empty( $sKeywords ) ? ', ' . $sKeywords : null ) . ( !empty( $aData['sSignature'] ) ? ', ' . $aData['sSignature'] : null );
		if( !empty( $aData['sMetaAbstract'] ) ) $sMetaAbstract = $aData['sMetaAbstract'];
		if( !empty( $aData['sMetaPageTopic'] ) ) $sMetaPageTopic = $aData['sMetaPageTopic'];
		if( !empty( $aData['sMetaDescription'] ) ) $sDescription = $aData['sMetaDescription'];
//		elseif( !empty( $config['description'] ) ) $sDescription = $config['description'];
		else{
			$sMetaDescPart = $aData['sDescriptionShort'];
			if( empty( $sMetaDescPart ) ) $sMetaDescPart = $aData['sDescriptionFull'];
			$sMetaDescPart = str_replace( '|n|', ' ', strip_tags( $sMetaDescPart ) );
			$sMetaDescPart = preg_replace( '/\\s+/', ' ', $sMetaDescPart );
			$sMetaDescPart = htmlspecialchars( $sMetaDescPart );
			if( strlen( $sMetaDescPart ) > 200 ){
				$sMetaDescPart = substr( $sMetaDescPart, 0, 200 );
				$sMetaDescPart = preg_replace( '/\\s\\S+$/', '', preg_replace( '/&[^;]+$/', '', $sMetaDescPart ) ) . '...';
			}
			$sDescription = ( empty( $aData['sDisplayTitle'] ) ? $aData['sName'] : $aData['sDisplayTitle'] ) . ' - ' . ( !empty( $sMetaDescPart ) ? $sMetaDescPart : $config['description'] );
		}
		if( $config['basket_page'] == $iContent ){
			// koszyk
			if( isset( $config['basket_page'] ) ){
				$sBasketLink = $oPage->getLinkName( $config['basket_page'] );
				$sBasketPage = !empty( $sBasketLink ) ? ( $sBasketLink . '?' ) : null;
			} else{
				$sBasketPage = null;
			}
			$sBasketErrors = null;
			$oOrder->generateBasket( );
			if( isset( $_SESSION['sOrderError'] ) ){
				$aOrderErrors = unserialize( $_SESSION['sOrderError'] );
				$_SESSION['sOrderError'] = null;
			}
			if( is_array( $aOrderErrors[0] ) ) foreach( $aOrderErrors[0] as &$mOrderError ){
				$aProductError = $oOrder->aProducts[$mOrderError['iProductVariant']];
				$mOrderError = str_replace( Array( '%sProductName%' ), Array( $aProductError['sName'] ), $lang['ErrorMessageNotAvailableFinal'] );
			}
			if( is_array( $aOrderErrors[1] ) ){
				$iNewDays = 0;
				foreach( $aOrderErrors[1] as &$mOrderError ){
					$aProductError = $oOrder->aProducts[$mOrderError['iProductVariant']];
					if( $mOrderError['iDays'] > $iNewDays ) $iNewDays = $mOrderError['iDays'];
					$mOrderError = str_replace( Array( '%sProductName%', '%iDays%' ), Array( $aProductError['sName'], $mOrderError['iDays'] ), $lang['WarningMessageNotAvailableFinal'] );
				}
				$oOrder->saveTempOrderInfo( Array( 'iDays' => $iNewDays ) );
			}
			if( isset( $mes ) && ( $mes == 'too_small_order' ) ){
				$aMessage = Array( 'header' => $lang['too_small_order_header'], 'content' => '<p>' . $lang['too_small_order'] . ' ' . displayPrice( normalizePrice( $config['min_products_summary'] ) ) . ' ' . $config['currency_symbol'] . '</p>' );
			}
			if( isset( $mes ) && ( $mes == 'too_small_order_quantity' ) ){
				$aMessage = Array( 'header' => $lang['too_small_order_header_quantity'], 'content' => '<p>' . $lang['too_small_order_quantity'] . ' ' . $config['min_products_count'] . '</p>' );
			}
			if( isset( $_POST['aProducts'] ) ){
				// zapisz koszyk
				$aBasketErrors = $oOrder->saveBasket( $_POST );
				if( isset( $_POST['sSave'] ) ){
					setCookie( 'sCustomer' . LANGUAGE, md5( $_SESSION['iCustomer' . LANGUAGE] ), time( ) + 2592000 );
					$aMessage = Array( 'header' => $lang['Basket_saved_header'], 'content' => '<p>' . $lang['Basket_saved_message'] . '</p>' );
				}
				if( empty( $aBasketErrors ) && isset( $_POST['sNext'] ) && ( ( $config['users_plugin_active'] && isset( $config['order_login_page'] ) && isset( $oPage->aPages[$config['order_login_page']]  ) ) || ( !( $config['users_plugin_active'] ) && isset( $config['order_address_page']) && isset($oPage->aPages[$config['order_address_page']]) ) ) ){
					$_POST['discount_coupon_code'] = trim( $_POST['discount_coupon_code'] );
					$oOrder->saveTempOrderInfo( $_POST );
					if($config['users_plugin_active']){
						header( 'Location: ' . REDIRECT . $oPage->aPages[$config['order_login_page']]['sLinkName'] );
					}else{
						header( 'Location: ' . REDIRECT . $oPage->aPages[$config['order_address_page']]['sLinkName'] );
					}
					exit;
				}
			}
			if( isset( $iProductDelete ) && is_numeric( $iProductDelete ) ){
				// usuń z koszyka
				$oOrder->deleteFromBasket( $iProductDelete );
			}
			if( isset( $_POST['iProductAdd'] ) && isset( $_POST['iQuantity'] ) ){
				$iProductAdd = $_POST['iProductAdd'];
				$iQuantity = $_POST['iQuantity'];
			}
			if( isset( $iProductAdd ) && is_numeric( $iProductAdd ) && isset( $iQuantity ) && is_numeric( $iQuantity ) && $iQuantity > 0 && $iQuantity < 10000 ){
				// dodaj do koszyka
				$sBasketError = $oOrder->addToBasket( $iProductAdd, $iQuantity, $_POST['aAttributes'] );
				if( !empty( $sBasketError ) ){
					$aBasketErrors = Array( $sBasketError );
				} else{
					$aProduct = $oProduct->throwProduct( $iProductAdd );
					saveUserAction( Array( 'iProduct' => $iProductAdd, 'iType' => 4 /* 1 - otworzenie, 2 - porównanie, 3 - dodanie do schowka, 4 - dodanie do koszyka */, 'fPrice' => $aProduct['bTimePromotionActive'] ? $aProduct['fTimePrice'] : $aProduct['fCatalogPrice'], 'iAvailable' => $aProduct['TiAvailable'] ) );
					$aBasket = $oOrder->throwProductsBasket( );
					$aBasket['sUserEmail'] = $_SESSION['sUserEmail'];
					if( $oSalesManago->checkSettings() === true && count( $aBasket['aProducts'] ) > 0 && isset( $aBasket['sUserEmail'] ) && $aBasket['sUserEmail'] != "" ) $oSalesManago->addEventContact( 'CART', $aBasket['aProducts'], $aBasket );
					header( 'Location: ' . REDIRECT . $aData['sLinkName'] );
					exit;
				}
			}
			if( isset( $_POST['aVariantsAdd'] ) && is_array( $_POST['aVariantsAdd'] ) ){
				foreach( $_POST['aVariantsAdd'] as $iProductVariantToAdd => $iVariantQuantityToAdd ){
					if( $iVariantQuantityToAdd > 0 ){
						$oOrder->addVariantToBasket( $iProductVariantToAdd, $iVariantQuantityToAdd );
						$iProductAdded = $oDB->executeSQL( 'SELECT `iProduct` FROM `' . $oDB->throwTableName( DB_PRODUCTS_VARIANTS ) . '` WHERE `iProductVariant` = ' . intval( $iProductVariantToAdd ) . ' LIMIT 1', true, DataBase::SINGLE_VALUE );
						$aProduct = $oProduct->throwProduct( $iProductAdded );
						saveUserAction( Array( 'iProduct' => $iProductAdded, 'iType' => 4 /* 1 - otworzenie, 2 - porównanie, 3 - dodanie do schowka, 4 - dodanie do koszyka */,'fPrice' => $aProduct['bTimePromotionActive'] ? $aProduct['fTimePrice'] : $aProduct['fCatalogPrice'], 'iAvailable' => $aProduct['TiAvailable'] ) );
						$aBasket = $oOrder->throwProductsBasket( );
						$aBasket['sUserEmail'] = $_SESSION['sUserEmail'];
						if( $oSalesManago->checkSettings() === true && count( $aBasket['aProducts'] ) > 0 && isset( $aBasket['sUserEmail'] ) && $aBasket['sUserEmail'] != "" ) $oSalesManago->addEventContact( 'CART', $aBasket['aProducts'], $aBasket );
					}
				}
				header( 'Location: ' . $oPage->getLinkName( $config['basket_page'] ) );
				exit;
			}
			// pokaż koszyk
			$aBasket = $oOrder->throwProductsBasket( );
		}
		if( $config['order_login_page'] == $iContent ){
			//order - login or register or no account (1st step)
			if( $oOrder->checkEmptyBasket( ) === false ){
				if( isset( $_SESSION['iUserClient'] ) ){
					$sRedirectPage = $oPage->getLinkName( $config['order_address_page'] );
					header( 'Location: ' . $sRedirectPage . ( strpos( $sRedirectPage, '?' ) !== false ? '&' : '?' ) . 'mes=' . $mes );
					exit;
				}
				if( isset( $_POST['sOrderPrev'] ) ){
					$oOrder->saveTempOrderInfo( $_POST );
					header( 'Location: ' . $oPage->getLinkName( $config['basket_page'] ) );
					exit;
				}
				if( isset( $_POST['sOrderNext'] ) ){
					$oOrder->saveTempOrderInfo( $_POST );
					$sRedirectPage = $oPage->getLinkName( $config['order_address_page'] );
					header( 'Location: ' . $sRedirectPage . ( strpos( $sRedirectPage, '?' ) !== false ? '&' : '?' ) . 'mes=' . $mes );
					exit;
				}
				if( $config['users_plugin_active'] == true ){
					$_SESSION['sRedirectAfterLogin'] = $oPage->getLinkName( $config['order_login_page'] );
					if( isset( $config['login_page'] ) && is_numeric( $config['login_page'] ) && isset( $oPage->aPages[$config['login_page']]['sLinkName'] ) ){
						$aData['sLinkLogin'] = $oPage->aPages[$config['login_page']]['sLinkName'];
					}
					if( isset( $config['register_page'] ) && is_numeric( $config['register_page'] ) && isset( $oPage->aPages[$config['register_page']]['sLinkName'] ) ){
						$aData['sLinkRegister'] = $oPage->aPages[$config['register_page']]['sLinkName'];
					}
					if( isset( $config['rules_page'] ) && isset( $oPage->aPages[$config['rules_page']] ) ){
						$oTpl->assign('sRulesLink', $oPage->aPages[$config['rules_page']]['sLinkName'] );
					}

				}
			} else{
				$aBasket = false;
			}
		}
		if( $config['order_address_page'] == $iContent ){
			//order - address info (2nd step)
			if( $oOrder->checkEmptyBasket( ) === false ){
				if( isset( $_POST['company_info'] ) && empty( $_POST['company_info'] ) ){
					$_POST['sCompanyName'] = '';
					$_POST['sNip'] = '';
				}
				if( isset( $_POST['postal_info'] ) && empty( $_POST['postal_info'] ) ){
					$_POST['sPostalName'] = '';
					$_POST['sPostalStreet'] = '';
					$_POST['sPostalZipCode'] = '';
					$_POST['sPostalCity'] = '';
					$_POST['iPostalCountry'] = 0;
					$_POST['sPostalPhone'] = '';
				}
				if( isset( $_POST['sOrderPrev'] ) ){
					$oOrder->saveTempOrderInfo( $_POST );
					header( 'Location: ' . $oPage->getLinkName( $config['basket_page'] ) );
					exit;
				} elseif( isset( $_POST['sOrderNext'] ) ){
					if( ( !isset( $config['rules_page'] ) || !isset( $oPage->aPages[$config['rules_page']] ) || $_POST['iRulesAccept'] ) && $_POST['iRulesAccept2'] ){
						$oOrder->saveTempOrderInfo( $_POST );
						$aErrors = Array();
						if( empty( $_POST['sFirstName'] ) ) $aErrors['EsFirstName']   = true;
						if( empty( $_POST['sLastName']  ) ) $aErrors['EsLastName']    = true;
						if( empty( $_POST['sStreet']    ) ) $aErrors['EsStreet']      = true;
						if( empty( $_POST['sCity']      ) ) $aErrors['EsCity']        = true;
						if( empty( $_POST['sZipCode']   ) /** /|| !preg_match( '/^[0-9]{2}[\\ \\-]?[0-9]{3}$/', $_POST['sZipCode'] )/**/
																							) $aErrors['EsZipCode']     = true;
						if( empty( $_POST['sPhone']     ) /** /|| !preg_match( '/^[0-9]{9}$/', str_replace( Array( ' ', '-' ), Array( '', '' ), $_POST['sPhone'] ) )/**/
																							) $aErrors['EsPhone']       = true;
																							
						//var_dump( $_POST['sPhone'], preg_match( '/^[0-9]{9}$/', str_replace( Array( ' ', '-' ), Array( '', '' ), $_POST['sPhone'] ) ) );
																							
						if( empty( $_POST['sEmail']     ) || !checkEmail( $_POST['sEmail'] )
																							) $aErrors['EsEmail']       = true;
						if( ( $_POST['iInvoice'] == 1 ) && empty( $_POST['sCompanyName'] )
																							) $aErrors['EsCompanyName'] = true;
						if( ( $_POST['iInvoice'] == 1 ) && ( empty( $_POST['sNip'] ) /** /|| !preg_match( '/^[0-9]{10}$/', str_replace( Array( ' ', '-' ), Array( '', '' ), $_POST['sNip'] ) )/**/ )
																							) $aErrors['EsNip']         = true;
						/** /if( !empty( $_POST['sPostalZipCode'] ) && !preg_match( '/^[0-9]{2}[\\ \\-]?[0-9]{3}$/', $_POST['sZipCode'] )
																							) $aErrors['EsPostalZipCode'] = true;/**/
						/** /if( !empty( $_POST['sPostalPhone']   ) && !preg_match( '/^[0-9]{9}$/', str_replace( Array( ' ', '-' ), Array( '', '' ), $_POST['sPostalPhone'] ) )
																							) $aErrors['EsPostalPhone']   = true;/**/
						
						if( isset( $_POST['iNewsletterAccept'] ) && !empty( $_POST['iNewsletterAccept'] ) ){
							if( !empty( $_POST['sEmail'] ) && checkEmail( $_POST['sEmail'] ) == true ){
								require_once DIR_ENGINE . 'newsletter.php';
								saveNewsletter( $_POST['sEmail'] );
							}
						}
						if( empty( $aErrors ) ){
							header( 'Location: ' . $oPage->getLinkName( $config['order_carrier_payment_page'] ) );
							exit;
						} else{
							$aOrderInfo = array_merge( $aErrors, $oOrder->getTempOrderInfo( ) );
						}
					} else{
						$aOrderInfo = array_merge( $oOrder->getTempOrderInfo( ), $_POST );
					}
				} else{
					$aOrderInfo = $oOrder->getTempOrderInfo( );
				}
				$aCountries = $oOrder->throwCountriesArray( );
				$aRegions = $oDB->executeSQL( 'SELECT `iRegion`, `iCountry`, `sRegion` FROM `' . $oDB->throwTableName( DB_REGIONS ) . '` ORDER BY `iCountry`, `iRegion`', true );
				$oTpl->assign( 'sRegions', json_encode( $aRegions ) );
				$aUser = Array( 'sFirstName' => '', 'sLastName' => '', 'sCompanyName' => '', 'sStreet' => '', 'sZipCode' => '', 'sCity' => '', 'sCountry' => '', 'sPhone' => '', 'sEmail' => '', 'sNip' => '' );
				if( $config['users_plugin_active'] == true ){
					if( isset( $_SESSION['iUserClient'] ) ) $aUser = throwUser( $_SESSION['iUserClient'] );
				}
				foreach( $aOrderInfo as $sIInfo => $sVInfo ){
					if( empty( $sVInfo ) ) unset( $aOrderInfo[$sIInfo] );
				}
				$aOrderInfo = array_merge( Array( 'iCountry' => $config['default_country'] ), $aUser, $aOrderInfo );
				$aOrderInfo['aInvoices'] = $oOrder->throwInvoice( );
				$aOrderInfo['aCountries'] = $aCountries;
				if( isset( $config['rules_page'] ) && isset( $oPage->aPages[$config['rules_page']] ) ){
					$aOrderInfo['sRulesLink'] = $oPage->aPages[$config['rules_page']]['sLinkName'];
				}
				$oTpl->assign( 'aOrderInfo', $aOrderInfo );
			} else{
				$aBasket = false;
			}
		}
		if( $config['order_carrier_payment_page'] == $iContent ){
			//order - carrier and payment info (3rd step)
			if( $oOrder->checkEmptyBasket( ) === false ){
				if( isset( $_POST['sOrderPrev'] ) ){
					if( !isset( $_POST['iGift'] ) ) $_POST['iGift'] = 0;
					if( !isset( $_POST['iShowClient'] ) ) $_POST['iShowClient'] = 0;
					$oOrder->saveTempOrderInfo( $_POST );
					header( 'Location: ' . $oPage->getLinkName( $config['order_address_page'] ) );
					exit;
				}
				if( isset( $_POST['sOrderNext'] ) ){
					if( !isset( $_POST['iGift'] ) ) $_POST['iGift'] = 0;
					if( !isset( $_POST['iShowClient'] ) ) $_POST['iShowClient'] = 0;
					$oOrder->saveTempOrderInfo( $_POST );
					$aOrderInfo = $oOrder->getTempOrderInfo( );
					if( !empty( $aOrderInfo['iCarrier'] ) && !empty( $aOrderInfo['iPayment'] ) ){
						header( 'Location: ' . $oPage->getLinkName( $config['order_final_page'] ) );
						exit;
					}
				}
				$aOrderInfo = $oOrder->getTempOrderInfo( );
				$aOrderProducts = $oOrder->throwProductsBasket( $aOrderInfo['fPaymentCarrierPrice'], $aOrderInfo['fSummary'] );
				$oOrder->fOrderSummary = $aOrderInfo['fSummary'];
				
				if( $config['verify_customer_option'] >= 3 ){
					$params = 'key='. $config['verify_customer_API_key'].'&order=&email=' . $aOrderInfo['sEmail'];
					$VCR = http::unchunkHttpResponse( http::httpPost( 'verifycustomer.com', 443, '/api/verify', $params, $prefix = 'ssl://' ) );
					$VCR = json_decode( $VCR );
					if( $VCR->black_list >= $config['verify_customer_API_black_list_percent'] && $VCR->negative_reports >= $config['verify_customer_API_black_list_count'] ){
						$bBlockCOD = true;
					} else{
						$bBlockCOD = false;
					}
				} else{
					$bBlockCOD = false;
				}
				$aPaymentCarriers = $oOrder->throwCarriersPayments( ( ( isset( $aOrderInfo['iPostalCountry'] ) && !empty( $aOrderInfo['iPostalCountry'] ) ) ? $aOrderInfo['iPostalCountry'] : $aOrderInfo['iCountry'] ), ( ( isset( $aOrderInfo['iPostalRegion'] ) && !empty( $aOrderInfo['iPostalRegion'] ) ) ? $aOrderInfo['iPostalRegion'] : $aOrderInfo['iRegion'] ), $aPaczkomaty, $bBlockCOD );

				//wyklucz LR jeśli niedozwolony towar
				$LR_forbidden=false;
				foreach ($aOrderProducts['aProducts'] as &$aProduct) {
					$LR_forbidden = $LR_forbidden || in_array($aProduct['iMainCategory'], explode(',', $config['LR_categories']));
				}
				if ($LR_forbidden)
					foreach( $aPaymentCarriers as $iIndex => &$aCarrier ){
						foreach( $aCarrier['aPayments'] as $iIndexPayment => &$aPayment ){
							if( $aPayment['iOuterSystem'] == LR_SYSTEM ){
								unset( $aCarrier['aPayments'][$iIndexPayment] );
							}
						}
					}

				$aPBN = Array();
				foreach( $aPaymentCarriers as $iIndex => &$aCarrier ){
					foreach( $aCarrier['aPayments'] as $iIndexPayment => &$aPayment ){
						if( $aPayment['iOuterSystem'] == PAYBYNET_SYSTEM ){
							$aPBN[ $aPayment['iPayment'] ] = true;
						}
					}
				}
				$aPBN = array_keys( $aPBN );
				if( !empty( $aPBN ) ){
					//Wyciągnij info o bankach PayByNet
					$xml = new DOMDocument( '1.0', 'utf-8' );
					$xml->load( 'https://pbn.paybynet.com.pl/PayByNet/update/os/banks.xml' );
					$xPath = new DOMXPath( $xml );
					function xPathVal( $xPath, $sPath, $oNode = null ){
						if( isset( $oNode ) ) $oTmp = $xPath->query( $sPath, $oNode );
						else $oTmp = $xPath->query( $sPath );
						if( empty( $oTmp->item( 0 )->value ) && isset( $oTmp->item( 0 )->childNodes ) ){
							return $oTmp->item( 0 )->childNodes->item( 0 )->wholeText;
						} else{
							return $oTmp->item( 0 )->value;
						}
					}
					$oBanks = $xPath->query( '/banks' )->item( 0 );
					$aBanks = Array();
					for( $i = 0;$i < $oBanks->childNodes->length;$i++ ){
						$oBank = $oBanks->childNodes->item( $i );
						$aBank = Array( 'sName' => xPathVal( $xPath, 'name', $oBank ), 'sImage' => 'https://pbn.paybynet.com.pl/PayByNet/update/os/' . xPathVal( $xPath, 'image', $oBank ) );
						if( !empty( $aBank['sName'] ) ){
							$aBanks[] = $aBank;
						}
					}
					$aOrderInfo['aPBNBanks'] = $aBanks;
					$aOrderInfo['sPBNJSON'] = json_encode( $aPBN );
					
				}
				
				$aAdvanceSystem = array_keys( $aAdvanceSystem );
				$aOrderInfo['sCarriersJSON'] = $oOrder->throwCarriersJSON( );
				$aOrderInfo['sPaymentsJSON'] = $oOrder->throwPaymentsJSON( );
				# Paczkomaty
				if( !empty( $aPaczkomaty ) ){
					require_once( $config['dir_libraries'] . 'paczkomaty/inpost.php' );
					$aOrderInfo['aPaczkomatyInfo'] = inpost_get_params();

					$aOrderInfo['sPaczkomatyJSON'] = json_encode( $aPaczkomaty );
					
					$aPobrania = Array();
					foreach( $aPaymentCarriers as $iIndex => &$aCarrier ){
						foreach( $aCarrier['aPayments'] as $iIndexPayment => &$aPayment ){
							if( $aPayment['iOuterSystem'] == PAID_ON_DELIVERY ){
								$aPobrania[ $aPayment['iPayment'] ] = true;
							}
						}
					}
					$aPobrania = array_keys( $aPobrania );
					$aOrderInfo['sPobraniaJSON'] = json_encode( $aPobrania );
				}
				$oTpl->assign( 'aOrderInfo', $aOrderInfo );
				$oTpl->assign( 'aOrderProducts', $aOrderProducts );
				$oTpl->assign( 'aPaymentCarriers', $aPaymentCarriers );
			} else{
				$aBasket = false;
			}
		}
		if( $config['order_final_page'] == $iContent ){
			//order - final order info (4th step)
			if( $oOrder->checkEmptyBasket( ) === false ){
				if( isset( $_POST['sOrderPrev'] ) ){
					$oOrder->saveTempOrderInfo( $_POST );
					header( 'Location: ' . $oPage->getLinkName( $config['order_carrier_payment_page'] ) );
					exit;
				}
				if( isset( $_POST['sOrderNext'] ) ){
					$iOrder = $oOrder->addOrder( );
					$oOrder->sendSMSWithOrderInfo( $iOrder );
					$oOrder->sendEmailWithOrderDetails( $iOrder );
					if( is_numeric( $iOrder ) ){
						$_SESSION['iOrderAvailable'] = $iOrder;
						header( 'Location: ' . $oPage->getLinkName( $config['order_summary_page'] ) . '?iOrder=' . $iOrder );
						exit;
					} elseif( is_array( $iOrder ) ){
						$_SESSION['sOrderError'] = serialize( $iOrder );
						header( 'Location: ' . $oPage->getLinkName( $config['basket_page'] ) );
					} else{
						die( 'Error - order not saved!' );
					}
				} else{
					$aOrderInfo = $oOrder->getTempOrderInfo( );
				}
				$aCountries = $oOrder->throwCountriesArray( );
				$aRegions = $oDB->executeSQL( 'SELECT `iRegion`, `sRegion` FROM `' . $oDB->throwTableName( DB_REGIONS ) . '` WHERE `iRegion` = ' . intval( $aOrderInfo['iRegion'] ) . ' OR `iRegion` = ' . intval( $aOrderInfo['iPostalRegion'] ), true, DataBase::ASSOCIATIVE );
				$aOrderInfo['sComment'] = str_replace( '|n|', '<br />', $aOrderInfo['sComment'] );
				$aOrderInfo['sCountry'] = $aCountries[$aOrderInfo['iCountry']];
				$aOrderInfo['sRegion'] = $aRegions[$aOrderInfo['iRegion']];
				$aOrderInfo['sPostalCountry'] = $aCountries[$aOrderInfo['iPostalCountry']];
				$aOrderInfo['sPostalRegion'] = $aRegions[$aOrderInfo['iPostalRegion']];
				$aOrderInfo['aCarrier'] = $oOrder->throwCarrier( $aOrderInfo['iCarrier'] );
				$aOrderInfo['aPayment'] = $oOrder->throwPayment( $aOrderInfo['iPayment'] );
				$aOrderProducts = $oOrder->throwProductsBasket( $aOrderInfo['fPaymentCarrierPrice'], $aOrderInfo['fSummary'] );
				$aOrderInfo['fPaymentCarrierPrice'] = $oOrder->throwCarrierPaymentPrice( $aOrderInfo['iPayment'], $aOrderInfo['iCarrier'], $aOrderInfo['fSummary'] );
				$aOrderInfo['sInvoice'] = $oOrder->throwInvoice( $aOrderInfo['iInvoice'] );
				if( $config['gifts'] ){
					if( $aOrderInfo['iGift'] ){
						$aOrderInfo['sGift'] = displayPrice( normalizePrice( $config['gift_cost'] ) );
						$aOrderInfo['fGiftCost'] = $config['gift_cost'];
					} else $aOrderInfo['sGift'] = '-';
				}
				$aOrderProducts = $oOrder->throwProductsBasket( $aOrderInfo['fPaymentCarrierPrice'], $aOrderInfo['fSummary'] );
				$oTpl->assign( 'aOrderInfo', $aOrderInfo );
				$oTpl->assign( 'aOrderProducts', $aOrderProducts );
			} else{
				$aBasket = false;
			}
		}
		if( $config['order_summary_page'] == $iContent || $config['order_advance_page'] == $iContent ){
			//order - order summary (after order was sent)
			#var_dump( $iOrder, $_SESSION['iOrderAvailable'], $_GET['sOrderKey'], md5( PK . $iOrder ), PK );
			if( is_numeric( $iOrder ) && ( ( isset( $_SESSION['iOrderAvailable'] ) && ( $_SESSION['iOrderAvailable'] == $iOrder ) ) || ( isset( $_GET['sOrderKey'] ) && ( $_GET['sOrderKey'] == md5( PK . $iOrder ) ) ) ) ){
				$aOrderInfo = $oOrder->throwOrder( $iOrder );
				$aOrderProducts = $oOrder->throwProductsBasket( $aOrderInfo['fPaymentCarrierPrice'], $aOrderInfo['fSummary'] );
				/**** SALESMANAGO ****/
				if( $oSalesManago->checkSettings() === true && $config['order_summary_page'] == $iContent ){
					$aOrderProducts = $oOrder->throwProducts( $iOrder );
					$oSalesManago->addEventContact( 'PURCHASE', $aOrderProducts['aProducts'], $aOrderInfo );
				}
				/**** END SALESMANAGO ****/
				$aOrderInfo['aCarrier'] = $oOrder->throwCarrier( $aOrderInfo['iCarrier'] );
				$aOrderInfo['aPayment'] = $oOrder->throwPayment( $aOrderInfo['iPayment'] );
				$aOrderInfo = array_merge( $aOrderInfo, $oOrder->throwProducts( $iOrder ) );
				$aOrderInfo['sSummary'] = displayPrice( $aOrderInfo['fOrderSummary'] );
				$aDescriptionWords = Array( '%sSummary%' => $aOrderInfo['sSummary'], '%sCarrierName%' => $aOrderInfo['aCarrier']['sName'], '%iOrder%' => $aOrderInfo['iOrder'], '%sName%' => $aOrderInfo['sFirstName'] . ' ' . $aOrderInfo['sLastName'], '%sEmail%' => $aOrderInfo['sEmail'], '%sInvoice%' => $aOrderInfo['sInvoice'], '%sBankName%' => $config['invoices_Bank'], '%sBankAccount%' => $config['invoices_Account'] );
				$aOrderInfo['aPayment']['sDescription'] = str_replace( array_keys( $aDescriptionWords ), array_values( $aDescriptionWords ), parseSpecials( $aOrderInfo['aPayment']['sDescription'] ) );
				$aOrderInfo['sCompanyNameF'] = $aOrderInfo['sCompanyName'];
				$aOrderInfo['sFirstNameF'] = $aOrderInfo['sFirstName'];
				$aOrderInfo['sLastNameF'] = $aOrderInfo['sLastName'];
				$aOrderInfo['sSummaryText'] = currency_in_text( $aOrderInfo['fOrderSummary'] );
				$aOrderInfo['account_id'] = preg_replace( '/[^0-9]/', '', $config['invoices_Account'] );
				if( $config['order_advance_page'] == $iContent ){
					$aOrderInfo['aPayment'] = $oOrder->throwPayment( $aOrderInfo['iOrderAdvancePayment'] );
					$aOrderInfo['iPaymentSystem'] = $aOrderInfo['aPayment']['iOuterSystem'];
					$aOrderInfo['fOrderSummary'] = $aOrderInfo['fOrderAdvance'];
					$aOrderInfo['sSummary'] = displayPrice( $aOrderInfo['fOrderAdvance'] );
					$aDescriptionWords = Array( '%sSummary%' => $aOrderInfo['sSummary'], '%sCarrierName%' => $aOrderInfo['aCarrier']['sName'], '%iOrder%' => $aOrderInfo['iOrder'], '%sName%' => $aOrderInfo['sFirstName'] . ' ' . $aOrderInfo['sLastName'], '%sEmail%' => $aOrderInfo['sEmail'], '%sInvoice%' => $aOrderInfo['sInvoice'], '%sBankName%' => $config['invoices_Bank'], '%sBankAccount%' => $config['invoices_Account'] );
					$aOrderInfo['aPayment']['sDescription'] = str_replace( array_keys( $aDescriptionWords ), array_values( $aDescriptionWords ), parseSpecials( $aOrderInfo['aPayment']['sDescription'] ) );
				}
				#var_dump( $aPaymentSystem, $aOrderInfo['iPaymentSystem'], $aOrderInfo['fOrderSummary'] );
				
				/*******************************************************************************************************************/
				/*                                     P Ł A T N O Ś C I         O N - L I N E                                     */
				/*******************************************************************************************************************/
				if( !empty( $aOrderInfo['iPaymentSystem'] ) && isset( $aOuterPaymentOption[$aOrderInfo['iPaymentSystem']] ) ){
					$aUrl = parse_url( 'http' . ( $_SERVER['HTTPS'] ? 's' : '' ) . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
					if( !empty( $aUrl['path'] ) ) $aUrl['path'] = dirname( $aUrl['path'] ) . '/';
					$aUrl['path'] = str_replace( '//', '/', $aUrl['path'] );
					$oTpl->assign( 'aUrl', $aUrl );
					$aOrderInfo['aStreet'] = throwStreetDetails( $aOrderInfo['sStreet'] );
					if( isset( $aOrderInfo['fOrderSummary'] ) ) $aOrderInfo['iAmount'] = sprintf( '%01.2f', $aOrderInfo['fOrderSummary'] ) * 100;
					$aOrderInfoTmp = $oOrder->throwOrder( $iOrder );
					$aOrderInfo['sOrderSummary'] = sprintf( '%01.2f', $aOrderInfoTmp['fOrderSummary'] );
					$aCountries2 = $oOrder->throwCountriesArray( 'iCountry', 'sCountry2', true );
					$aCountries = $oOrder->throwCountriesArray( 'iCountry', 'sCountry', true );
					$aOrderInfo['sCountry2'] = $aCountries2[$aOrderInfo['iCountry']];
					$aOrderInfo['sCountry'] = $aCountries[$aOrderInfo['iCountry']];
					//					$aOrderInfo['aProducts'] = $oOrder->aProducts;
//					if( $aOrderInfo['iPaymentSystem'] == ECARD_SYSTEM ){
//						$currencies = array( 'ALL' => '8', 'DZD' => '12', 'ARS' => '32', 'AUD' => '36', 'BSD' => '44', 'BHD' => '48', 'BDT' => '50', 'AMD' => '51', 'BBD' => '52', 'BMD' => '60', 'BTN' => '64', 'BOB' => '68', 'BWP' => '72', 'BZD' => '84', 'SBD' => '90', 'BND' => '96', 'MMK' => '104', 'BIF' => '108', 'KHR' => '116', 'CAD' => '124', 'CVE' => '132', 'KYD' => '136', 'LKR' => '144', 'CLP' => '152', 'CNY' => '156', 'COP' => '170', 'KMF' => '174', 'CRC' => '188', 'HRK' => '191', 'CUP' => '192', 'CZK' => '203', 'DKK' => '208', 'DOP' => '214', 'SVC' => '222', 'ETB' => '230', 'ERN' => '232', 'FKP' => '238', 'FJD' => '242', 'DJF' => '262', 'GMD' => '270', 'GIP' => '292', 'GTQ' => '320', 'GNF' => '324', 'GYD' => '328', 'HTG' => '332', 'HNL' => '340', 'HKD' => '344', 'HUF' => '348', 'ISK' => '352', 'INR' => '356', 'IDR' => '360', 'IRR' => '364', 'IQD' => '368', 'ILS' => '376', 'JMD' => '388', 'JPY' => '392', 'KZT' => '398', 'JOD' => '400', 'KES' => '404', 'KPW' => '408', 'KRW' => '410', 'KWD' => '414', 'KGS' => '417', 'LAK' => '418', 'LBP' => '422', 'LSL' => '426', 'LRD' => '430', 'LYD' => '434', 'MOP' => '446', 'MWK' => '454', 'MYR' => '458', 'MVR' => '462', 'MRO' => '478', 'MUR' => '480', 'MXN' => '484', 'MNT' => '496', 'MDL' => '498', 'MAD' => '504', 'OMR' => '512', 'NAD' => '516', 'NPR' => '524', 'ANG' => '532', 'AWG' => '533', 'VUV' => '548', 'NZD' => '554', 'NIO' => '558', 'NGN' => '566', 'NOK' => '578', 'PKR' => '586', 'PAB' => '590', 'PGK' => '598', 'PYG' => '600', 'PEN' => '604', 'PHP' => '608', 'QAR' => '634', 'RUB' => '643', 'RWF' => '646', 'SHP' => '654', 'STD' => '678', 'SAR' => '682', 'SCR' => '690', 'SLL' => '694', 'SGD' => '702', 'VND' => '704', 'SOS' => '706', 'ZAR' => '710', 'SSP' => '728', 'SZL' => '748', 'SEK' => '752', 'CHF' => '756', 'SYP' => '760', 'THB' => '764', 'TOP' => '776', 'TTD' => '780', 'AED' => '784', 'TND' => '788', 'UGX' => '800', 'MKD' => '807', 'EGP' => '818', 'GBP' => '826', 'TZS' => '834', 'USD' => '840', 'UYU' => '858', 'UZS' => '860', 'WST' => '882', 'YER' => '886', 'TWD' => '901', 'CUC' => '931', 'ZWL' => '932', 'TMT' => '934', 'GHS' => '936', 'VEF' => '937', 'SDG' => '938', 'UYI' => '940', 'RSD' => '941', 'MZN' => '943', 'AZN' => '944', 'RON' => '946', 'CHE' => '947', 'CHW' => '948', 'TRY' => '949', 'XAF' => '950', 'XCD' => '951', 'XOF' => '952', 'XPF' => '953', 'XBA' => '955', 'XBB' => '956', 'XBC' => '957', 'XBD' => '958', 'XAU' => '959', 'XDR' => '960', 'XAG' => '961', 'XPT' => '962', 'XTS' => '963', 'XPD' => '964', 'XUA' => '965', 'ZMW' => '967', 'SRD' => '968', 'MGA' => '969', 'COU' => '970', 'AFN' => '971', 'TJS' => '972', 'AOA' => '973', 'BYR' => '974', 'BGN' => '975', 'CDF' => '976', 'BAM' => '977', 'EUR' => '978', 'MXV' => '979', 'UAH' => '980', 'GEL' => '981', 'BOV' => '984', 'PLN' => '985', 'BRL' => '986', 'CLF' => '990', 'XSU' => '994', 'USN' => '997', 'XXX' => '999' );
//						$aOrderInfo['iCurrency'] = $currencies[$config['currency_symbol_ISO']];
//					}
					if( $aOrderInfo['iPaymentSystem'] == ZAGIEL_SYSTEM ){
						$aOrderInfo['sPhone'] = preg_replace( '/[^\\d]/', '', $aOrderInfo['sPhone'] );
						$aOrderInfo['sZagielFailLink'] = $oPage->getLinkName( $config['zagiel_page_fail'] ) . '?res=fail';
						$aOrderInfo['sZagielOkLink'] = $oPage->getLinkName( $config['zagiel_page_ok'] ) . '?res=ok';
					}
					if( $aOrderInfo['iPaymentSystem'] == PAYBYNET_SYSTEM ){
						$aOrderInfo['sPlatnosciFailLink'] = $oPage->getLinkName( $config['platnosci_page_fail'] );
						$aOrderInfo['sPlatnosciOkLink'] = $oPage->getLinkName( $config['platnosci_page_ok'] );
						$aOrderInfo['sPayByNetHash'] = '<id_client>' . $config['paybynet_id'] . '</id_client>' . '<id_trans>' . str_repeat( '0', 10 - strlen( $aOrderInfo['iOrder'] ) ) . $aOrderInfo['iOrder'] . '</id_trans>' . '<date_valid>' . date( 'd-m-Y H:i:s', time( ) + 7 * 24 * 3600 ) . '</date_valid>' . '<amount>' . str_replace( '.', ',', sprintf( '%01.2f', $aOrderInfoTmp['fOrderSummary'] ) ) . '</amount>' . '<currency>PLN</currency>' . '<email>' . $aOrderInfo['sEmail'] . '</email>' . '<account>' . $config['paybynet_account'] . '</account>' . '<accname>' . $config['paybynet_accname'] . '</accname>' . '<backpage>' . $aUrl['scheme'] . '://' . $aUrl['host'] . $aUrl['path'] . $aOrderInfo['sPlatnosciOkLink'] . '</backpage>' . '<backpagereject>' . $aUrl['scheme'] . '://' . $aUrl['host'] . $aUrl['path'] . $aOrderInfo['sPlatnosciFailLink'] . '</backpagereject>';
						$aOrderInfo['sPayByNetHash'].= '<hash>' . sha1( $aOrderInfo['sPayByNetHash'] . '<password>' . $config['paybynet_pass'] . '</password>' ) . '</hash>';
						$aOrderInfo['sPayByNetHash'] = base64_encode( $aOrderInfo['sPayByNetHash'] );
						$aOrderInfo['sPayByNetAddress'] = $config['paybynet_test'] ? 'https://pbn.paybynet.com.pl/PayByNetT/trans.do' : 'https://pbn.paybynet.com.pl/PayByNet/trans.do';
					}
					if( $aOrderInfo['iPaymentSystem'] == PRZELEWY24_SYSTEM ){
						$aOrderInfo['p24_crc'] = md5( $iOrder . '|' . $config['przelewy24_id'] . '|' . $aOrderInfo['iAmount'] . '|' . $config['przelewy24_crc'] );
					}
					if( $aOrderInfo['iPaymentSystem'] == PAYU_SYSTEM ){
						$aOrderInfo['client_ip'] = $_SERVER['REMOTE_ADDR'];
						$aOrderInfo['ts'] = time();
						$aOrderInfo['sig'] = md5( $config['platnosci_id'] . $aOrderInfo['iOrder'] . $config['platnosci_pos_auth_key'] . $aOrderInfo['iAmount'] . 'ID ' . $aOrderInfo['iOrder'] . $aOrderInfo['iOrder'] . $aOrderInfo['sFirstName'] . $aOrderInfo['sLastName'] . $aOrderInfo['aStreet']['sStreetName'] . $aOrderInfo['aStreet']['sStreetNumber1'] . $aOrderInfo['aStreet']['sStreetNumber2'] . $aOrderInfo['sCity'] . $aOrderInfo['sZipCode'] . $aOrderInfo['sCountry2'] . $aOrderInfo['sEmail'] . $aOrderInfo['sPhone'] . $aOrderInfo['client_ip'] . $aOrderInfo['ts'] . $config['platnosci_key1'] );
					}
					if( $aOrderInfo['iPaymentSystem'] == LR_SYSTEM ){
						$aOrderInfo['randomizer'] = date("YmdHis") . rand();
						$t1 = "";
						foreach ($aOrderInfo['aProducts'] as $product) if ($t1 == "") $t1 = $product;
						$hash = $config['LR_psp_id'] . "RAT" . "2" . number_format($aOrderInfo['sSummary'],2, '.', '') . stripslashes(change2Latin($t1['sName'])) . number_format($t1['fPrice'],2, '.', '') . $aOrderInfo['randomizer'] . $config['LR_password'];
						$aOrderInfo['paramHash'] = md5($hash);
					}
					if( $aOrderInfo['iPaymentSystem'] == SOFORT_SYSTEM ){
						$aOrderInfo['sPlatnosciFailLink'] = $oPage->getLinkName( $config['platnosci_page_fail'] );
						$aOrderInfo['sPlatnosciOkLink'] = $oPage->getLinkName( $config['platnosci_page_ok'] );
						$con = fsockopen( 'ssl://api.sofort.com', 443 );
						if( isset( $con ) ){
							$data = '<?xml version="1.0" encoding="UTF-8"?>
<multipay>
<project_id>' . $config['SOFORT_Project'] . '</project_id>
<language_code>' . LANGUAGE . '</language_code>
<interface_version>pn_sellsmart_' . VERSION . '</interface_version>
<amount>' . $aOrderInfo['sOrderSummary'] . '</amount>
<currency_code>' . $config['currency_symbol_ISO'] . '</currency_code>
<email_customer>' . $aOrderInfo['sEmail'] . '</email_customer>
<phone_customer>' . $aOrderInfo['sPhone'] . '</phone_customer>
<reasons>
<reason>Order ' . $aOrderInfo['iOrder'] . '</reason>
</reasons>
<success_url>' . $aUrl['scheme'] . '://' . $aUrl['host'] . $aUrl['path'] . $aOrderInfo['sPlatnosciOkLink'] . '</success_url>
<abort_url>' . $aUrl['scheme'] . '://' . $aUrl['host'] . $aUrl['path'] . $aOrderInfo['sPlatnosciFailLink'] . '</abort_url>
<notification_urls>
<notification_url notify_on="pending">' . $aUrl['scheme'] . '://' . $aUrl['host'] . $aUrl['path'] . '?p=payment-sofort_ok</notification_url>
</notification_urls>
<su>
</su>
</multipay>';
							fwrite( $con, 'POST /api/xml HTTP/1.1
Host: api.sofort.com
Authorization: Basic ' . base64_encode( $config['SOFORT_Customer_number'] . ':' . $config['SOFORT_Api_key'] ) . '
Content-Type: application/xml; charset=UTF-8
Content-Length: '.strlen( $data ).'
Accept: application/xml; charset=UTF-8

'.$data );
							while( !feof( $con ) ){
								$str = fgets( $con, 256 );
								$resp .= $str;
							}
							if( preg_match( '/^HTTP\\/1.1 200 OK/', $resp ) ){
								$resp = explode( "\n", $resp );
								while( trim( $resp[0] ) != '' ){
									array_shift( $resp );
								}
								$resp = trim( implode( "\n", $resp ) );
								//var_dump( $resp );

								function xPathVal( $xPath, $sPath, $oNode = null ){
									if( isset( $oNode ) ) $oTmp = $xPath->query( $sPath, $oNode );
									else $oTmp = $xPath->query( $sPath );
									if( empty( $oTmp->item( 0 )->value ) && isset( $oTmp->item( 0 )->childNodes ) ){
										return $oTmp->item( 0 )->childNodes->item( 0 )->wholeText;
									} else{
										return $oTmp->item( 0 )->value;
									}
								}

								$oResp = new DomDocument();
								$oResp->loadXML( $resp );
								$xPath = new DOMXPath( $oResp );
								$sTransaction = xPathVal( $xPath, '/new_transaction/transaction' );
								$aOrderInfo['sPaymentUrl'] = xPathVal( $xPath, '/new_transaction/payment_url' );
								
								$oDB->update( DB_ORDERS, Array( 'mPaymentChannel' => $sTransaction ), Array( 'iOrder' => $aOrderInfo['iOrder'] ) );
							}
						}
					}
					if( $aOrderInfo['iPaymentSystem'] == TRANSFERUJ_SYSTEM ){
						$aOrderInfo['sPlatnosciFailLink'] = $oPage->getLinkName( $config['platnosci_page_fail'] );
						$aOrderInfo['sPlatnosciOkLink'] = $oPage->getLinkName( $config['platnosci_page_ok'] );
					}
					
					if( $aOrderInfo['iPaymentSystem'] == BLUE_MEDIA ){
						$aOrderInfo['sHash'] = hash( $oBM->bmFunction, $oBM->bmServiceId . "|" . $aOrderInfo['iOrder'] . "|" . $aOrderInfo['fOrderSummary'] . "|" . $oBM->bmKey );
						#var_dump( $oBM->bmServiceId . "|" . $aOrderInfo['iOrder'] . "|" . $aOrderInfo['fOrderSummary'] . "|" . $oBM->bmKey );
						#var_dump( hash( $oBM->bmFunction, $oBM->bmServiceId . "|" . $aOrderInfo['iOrder'] . "|" . $aOrderInfo['fOrderSummary'] . "|" . $oBM->bmKey ) );
						$aOrderInfo['sLinkBlueMedia'] = $config['bluemedia_website_gate']; //. "?ServiceID=" . $config['bluemedia_service_id'] . "&OrderID=" . $aOrderInfo['iOrder'] .  "&Amount=" . $aOrderInfo['fOrderSummary'] . "&Hash=" . $aOrderInfo['sHash'];
					}
					
					if( $aOrderInfo['iPaymentSystem'] == First_Data ){
						#$aOrderInfo['sCountry'] = $oOrder->throwCountry( isset( $aOrderInfo['iPostalCountry'] ) ? $aOrderInfo['iPostalCountry'] : $aOrderInfo['iCountry'], 'sCountry2' );
						$aOrderInfo['session_id'] = md5( PK . microtime() );
						$aOrderInfo['sControlData'] = $oFD->calculateControlData( array( 'pos_id' => $oFD->sFdPosId, 'order_id' => $aOrderInfo['iOrder'], 'session_id' => $aOrderInfo['session_id'], 'amount' => $aOrderInfo['iAmount'], 'currency' => $config['currency_symbol_ISO'], 'test' => $oFD->sFdTest, 'language' => 'pl', 'client_ip' => $aOrderInfo['sIp'], 'country' => $aOrderInfo['sCountry2'], 'email' => $aOrderInfo['sEmail'] ) );
					}

					$aOrderInfo['sPaymentCarrierPrice']+= ( $aOrderInfo['iGift'] ? $config['gift_cost'] : 0 );
				}
				/********************************************************************************************************/				
				$oTpl->assign( 'aOrderInfo', $aOrderInfo );
			} else{
				die( 'HACKING ATTEMPT!' );
			}
		}
		$aUrl = parse_url( 'http' . ( $_SERVER['HTTPS'] ? 's' : '' ) . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
		if( !empty( $aUrl['path'] ) && !preg_match( '|/$|', $aUrl['path'] ) ) $aUrl['path'] = dirname( $aUrl['path'] ) . '/';
		if( $config['social_facebook_pages'] || $config['social_nk_pages'] || $config['social_twitter_pages'] || $config['social_gg_pages'] || $config['social_google_pages'] ){
			if( !empty( $aData['sDescriptionShort'] ) ) $aData['sFBDescription'] = trim_text( strip_tags( changeTxt( $aData['sDescriptionShort'], 'nlNds' ) ), 250 );
			else $aData['sFBDescription'] = trim_text( strip_tags( changeTxt( $aData['sDescriptionFull'], 'nlNds' ) ), 250 );
			$aData['sFBDescriptionEncode'] = rawurlencode( $aData['sFBDescription'] );
			$aData['sFBTitle'] = $aData['sName'];
			$aData['sFBTitleEncode'] = rawurlencode( htmlspecialchars_decode( $aData['sName'] ) );
			$aData['sFBUrl'] = $aUrl['scheme'] . '://' . $aUrl['host'] . $aUrl['path'] . $aData['sLinkName'];
			$aData['sFBUrlEncode'] = rawurlencode( $aData['sFBUrl'] );
			$aData['sFBWebsite'] = $config['website_name'];
			$aData['sFBWebsiteEncode'] = rawurlencode( $aData['sFBWebsite'] );
			$aData['sFBImage'] = $oFile->aImagesDefault[1][$aData['iPage']];
			if( isset( $aData['sFBImage'] ) && $aData['sFBImage'] != '' ){
				$aData['sFBImage'] = $aUrl['scheme'] . '://' . $aUrl['host'] . $aUrl['path'] . $config['dir_files'] . $aData['sFBImage']['iSize'] . '/' . $aData['sFBImage']['sFileName'];
			}
		}
		$oTpl->assign( 'aPage', $aData );
		$oTpl->assign( 'aMessage', $aMessage );
		$oTpl->assign( 'aOrderErrors', $aOrderErrors );
		$oTpl->assign( 'aBasketErrors', $aBasketErrors );
		$oTpl->assign( 'aBasket', $aBasket );
		$oTpl->assign( 'sUrlExt', $sUrlExt );
		$oTpl->assign( 'SMARTY_sUsersPanel', $sUsersPanel );
		$oTpl->assign( 'SMARTY_sProductsList', $sProductsList );
		$oTpl->assign( 'SMARTY_sPromotedProducts', $sPromotedProducts );
		$content.= $oTpl->parse( 'pages_default.tpl' );
	} else{
		$oTpl->assign( 'aMessage', Array( 'message' => $lang['Data_not_found'], 'bError' => true ) );
		$content.= $oTpl->parse( 'message.tpl' );
	}
}
$sCookieLink = $oPage->aPages[$config['cookie_page']]['sLinkName'];
$oTpl->assign( 'sCookieLink', $sCookieLink );
?>