<?php
//This code is copyright (c) ViciSoft SL, all rights reserved.
//The contents of this file are protected under law as the intellectual property 
//of ViciSoft SL. Any use, reproduction, disclosure or copying of any kind 
//without the express and written permission of ViciSoft SL is forbidden.
//Author: Vince Reid, vincereid@gmail.com
//Build: 7.8.9.001
$GLOBALS['incfunctionsdefined']=TRUE;
$GLOBALS['defimagejs']='';
if(function_exists('set_magic_quotes_runtime')) @set_magic_quotes_runtime(0);
@ini_set('display_errors','On');
@error_reporting(E_ALL^(@$GLOBALS['debugmode']||@$GLOBALS['showwarnings']?0:E_NOTICE|E_DEPRECATED));
$GLOBALS['magicq']=(isset($GLOBALS['wp_did_header']));
$GLOBALS['wpjavascriptcomments']=$GLOBALS['wpjavascriptendcomments']='';
if(@$GLOBALS['iswordpress']){
	if(!@isset($GLOBALS['usepnamefordetaillinks'])) $GLOBALS['usepnamefordetaillinks']=TRUE;
	$GLOBALS['wpjavascriptcomments']="\n<!--\n// This comment stops wordpress escaping the ampersands\n";
	$GLOBALS['wpjavascriptendcomments']="\n-->\n";
}
if(!@isset($GLOBALS['extension'])) $GLOBALS['extension']='.php';
$GLOBALS['storehomeurl']='categories'.$GLOBALS['extension'];
if(@$GLOBALS['xxHomeURL']!='') $GLOBALS['storehomeurl']=$GLOBALS['xxHomeURL'];
if(!@isset($GLOBALS['usecsslayout'])) $GLOBALS['usecsslayout']=TRUE;
if(!@isset($GLOBALS['bad_emails']))$GLOBALS['bad_emails']=['testing@example.com','sample@email.tst','netsparker@example.com'];
if(@$GLOBALS['usecsslayout']){ $GLOBALS['nomarkup']=TRUE; $GLOBALS['useproductbodyformat']=2; $GLOBALS['usesearchbodyformat']=2; $GLOBALS['usedetailbodyformat']=4; }
if(@$GLOBALS['productpagelayout']){ $GLOBALS['useproductbodyformat']=2; $GLOBALS['usesearchbodyformat']=2; }
if(@$GLOBALS['giftcertificateid']=='') $GLOBALS['giftcertificateid']='giftcertificate';
if(@$GLOBALS['donationid']=='') $GLOBALS['donationid']='donation';
if(@$GLOBALS['giftwrappingid']=='') $GLOBALS['giftwrappingid']='giftwrapping';
if(@$GLOBALS['mobilebrowser']!=TRUE) $GLOBALS['mobilebrowser']=detectmobilebrowser();
if($GLOBALS['mobilebrowser']){ $GLOBALS['inlinecheckout']=TRUE; $GLOBALS['hideshipaddress']=TRUE; if(@$GLOBALS['usehardcartformobile'])$GLOBALS['usehardaddtocart']=TRUE; $GLOBALS['disableupdatechecker']=TRUE; if(@$GLOBALS['mobilebrowsercolumns']!='') $GLOBALS['productcolumns']=$GLOBALS['mobilebrowsercolumns']; }
if(@$GLOBALS['adminencoding']=='') $GLOBALS['adminencoding']='iso-8859-1';
if(@$GLOBALS['emailencoding']=='') $GLOBALS['emailencoding']=$GLOBALS['adminencoding'];
if(@$_SESSION['languageid']!='') $GLOBALS['languageid']=$_SESSION['languageid']; elseif(@$GLOBALS['languageid']=='') $GLOBALS['languageid']=1;
if(@$GLOBALS['emailcr']=='')$GLOBALS['emailcr']="\r\n";
if(@$GLOBALS['htmlemails']) $GLOBALS['emlNl']='<br>'; else $GLOBALS['emlNl']=$GLOBALS['emailcr'];
$GLOBALS['sstrong']=$GLOBALS['estrong']='';
if(@$GLOBALS['customeraccounturl']=='') $GLOBALS['customeraccounturl']='clientlogin'.$GLOBALS['extension'];
if(@$GLOBALS['fedextestmode']) $GLOBALS['fedexurl']='https://wsbeta.fedex.com:443/web-services'; else $GLOBALS['fedexurl']='https://ws.fedex.com:443/web-services';
if(@$GLOBALS['loyaltypointvalue']=='') $GLOBALS['loyaltypointvalue']=0.0001;
if(@$GLOBALS['detlinkspacechar']=='') $GLOBALS['detlinkspacechar']=' ';
if(@$GLOBALS['showtaxinclusive']===TRUE) $GLOBALS['showtaxinclusive']=1;
if(!is_numeric(@$GLOBALS['showtaxinclusive'])) $GLOBALS['showtaxinclusive']=0;
if(@$GLOBALS['dateadjust']=='') $GLOBALS['dateadjust']=0;
if(@$GLOBALS['nopriceanywhere']==TRUE) $GLOBALS['noprice']=TRUE;
if(@$GLOBALS['forceclientlogin']) $GLOBALS['enableclientlogin']=TRUE;
$GLOBALS['redasterix']='<span style="color:#FF0000">*</span>';
$GLOBALS['redstar']='<span class="redstar">*</span>';
$GLOBALS['fedexcopyright']='FedEx service marks are owned by Federal Express Corporation and are used by permission.';
if(@$GLOBALS['righttoleft']==TRUE){ $GLOBALS['tright']='left'; $GLOBALS['tleft']='right'; }else{ $GLOBALS['tright']='right'; $GLOBALS['tleft']='left'; }
$GLOBALS['txtcollen']=8000;
$path_parts=pathinfo(@$_SERVER['PHP_SELF']);
if($path_parts['dirname']=='/'||$path_parts['dirname']=='\\')$path_parts['dirname']='';
$GLOBALS['pathtohere']=strreplace('"','',strip_tags($path_parts['dirname'].'/'));
if(@$GLOBALS['seocategoryurls']){
	if(@$GLOBALS['seocaturlpattern']=='') $GLOBALS['seocaturlpattern']='/category/%s';
	if(@$GLOBALS['seoprodurlpattern']=='') $GLOBALS['seoprodurlpattern']='/products/%s';
	if(@$GLOBALS['seomanufacturerpattern']=='') $GLOBALS['seomanufacturerpattern']='/manufacturer/%s';
}else
	$GLOBALS['seocaturlpattern']=$GLOBALS['seoprodurlpattern']=$GLOBALS['seomanufacturerpattern']='';
$GLOBALS['seodetailurls']=@$GLOBALS['seodetailurls'] || @$GLOBALS['seodetailurlpattern']!='';
if(@$GLOBALS['orhomeurl']!='') $GLOBALS['storehomeurl']=$GLOBALS['orhomeurl']; elseif(@$GLOBALS['seocategoryurls']) $GLOBALS['storehomeurl']=strreplace('%s','',$GLOBALS['seocaturlpattern']);
if(@$GLOBALS['checksumtext']=='') $GLOBALS['checksumtext']='random text for checksum PHP version';
if(@$GLOBALS['currencyseparator']=='') $GLOBALS['currencyseparator']=' ';
$GLOBALS['REMOTE_ADDR']=ipv6to4(trim_(strreplace("'",'',substr(@$_SERVER['HTTP_CF_CONNECTING_IP']!=''?@$_SERVER['HTTP_CF_CONNECTING_IP']:@$_SERVER['REMOTE_ADDR'],0,48))));
if(@$GLOBALS['dateformatstr']=='') $GLOBALS['dateformatstr']='m/d/Y';
$GLOBALS['zipoptional']=[85,91,149,154,200];
$GLOBALS['topcpnids_cache']=[];
// For PayPal Checkout. Do not alter!
$paypal_merchant_id='FHRZDZ5ZNVEKG';
$paypal_clientid='ATX4CJrINhzqx1VBCW8VVA4NJdJQ3nLzo5kTKygkgHBEy3XCZFk3VaeYML_6fYix5YyvkByFmgkBJ7Tf';
$paypal_sandbox='';
function checkcustomerblock(){
	if(! @$GLOBALS['isectadmin']){
		$logip=ip2long($GLOBALS['REMOTE_ADDR']);
		$sSQL='SELECT dcid FROM ipblocking ' . ($GLOBALS['REMOTE_ADDR']=='none' || $logip==FALSE ? 'LIMIT 0,1' : 'WHERE (dcip1=' . $logip . ' AND dcip2=0) OR (dcip1<=' . $logip . ' AND ' . $logip . '<=dcip2 AND dcip2<>0)');
		$result=ect_query($sSQL) or ect_error();
		if(ect_num_rows($result)>0){
			if(@$GLOBALS['customerserviceemail']==''){
				$sSQL='SELECT adminEmail FROM admin WHERE adminID=1';
				$result2=ect_query($sSQL) or ect_error();
				$rs2=ect_fetch_assoc($result2);
				$allemailsarray=explode(',',$rs2['adminEmail']);
				$GLOBALS['customerserviceemail']=$allemailsarray[0];
			}
			@ob_clean();
			header('HTTP/1.1 403 Forbidden');
			print '<html><head><title>System Block</title></head><body><div style="padding:50px;text-align:center"><p>We apologize but you have been automatically flagged and blocked from this website.</p><p>Please contact us via our customer service email (' . $GLOBALS['customerserviceemail'] . ') to have this rectified.</p></div></body></html>';
			exit();
		}
		ect_free_result($result);
	}
}
checkcustomerblock();
if(@$_SESSION['clientID']!=''){
	$sSQL="SELECT clID,clUserName,clActions,clLoginLevel,clPercentDiscount,avalaraentityuse FROM customerlogin WHERE clID='" . escape_string($_SESSION['clientID']) . "' AND clPW='".escape_string(@$_SESSION['clientPW']) . "'";
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		$_SESSION['clientUser']=$rs['clUserName'];
		$_SESSION['clientActions']=$rs['clActions'];
		$_SESSION['clientLoginLevel']=$rs['clLoginLevel'];
		$_SESSION['clientPercentDiscount']=(100.0-(float)$rs['clPercentDiscount'])/100.0;
		$_SESSION['avalaraentityuse']=$rs['avalaraentityuse'];
	}else{
		$_SESSION['clientID']=NULL; unset($_SESSION['clientID']);
	}
}
function getdirnamefromurl($url){
	$spos=strpos($url,'//');
	if($spos!==FALSE){
		$spos=strpos($url,'/',$spos+2);
		if($spos!==FALSE){
			$url=substr($url,$spos);
		}
	}
	return $url;
}
function getadminsettings(){
	if(! @$GLOBALS['alreadygotadmin']){
		$sSQL='SELECT adminLogging,adminEmail,htmlemails,adminEmailConfirm,adminPayLater,adminProdsPerPage,adminStoreURL,adminStoreURLSSL,adminHandling,adminHandlingPercent,adminDelCC,adminUSZones,adminStockManage,adminShipping,adminIntShipping,adminZipCode,adminUnits,adminlanguages,adminlangsettings,currRate1,currSymbol1,currRate2,currSymbol2,currRate3,currSymbol3,currConvUser,currConvPw,currLastUpdate,adminSecret,countryLCID,countryCurrency,countryNumCurrency,countryName,countryCode,countryID,countryTax,currSymbolText,currDecimalSep,currThousandsSep,currPostAmount,currDecimals,currSymbolHTML,cardinalProcessor,cardinalMerchant,cardinalPwd,avalarastate,avalaraacctno,avalaralicensekey,avalaracompanycode,catalogRoot,adminAltRates,prodFilter,sideFilter,prodFilterText,prodFilterText2,prodFilterText3,prodFilterOrder,sortOrder,sortOptions,storelang,reCAPTCHAsitekey,reCAPTCHAsecret,reCAPTCHAuseon,googleTagID,googleTagNoHead,onvacation,mailchimpAPIKey,mailchimpList,blockMultiPurchase,blockContactEmails,blockMaxCartAdds FROM admin LEFT JOIN countries ON admin.adminCountry=countries.countryID WHERE adminID=1';
		$result=ect_query($sSQL) or ect_error();
		$rs=ect_fetch_assoc($result);
		$GLOBALS['splitUSZones']=((int)$rs['adminUSZones']==1);
		$GLOBALS['adminLocale']=$rs['countryLCID'];
		$GLOBALS['adminLogging']=$rs['adminLogging'];
		$GLOBALS['countryCurrency']=$rs['countryCurrency'];
		$GLOBALS['countryNumCurrency']=$rs['countryNumCurrency'];
		if(@$GLOBALS['orcurrencyisosymbol']!='') $GLOBALS['countryCurrency']=$GLOBALS['orcurrencyisosymbol'];
		$GLOBALS['useEuro']=($GLOBALS['countryCurrency']=='EUR');
		$GLOBALS['storeurl']=$rs['adminStoreURL'];
		$GLOBALS['storeurlssl']=$rs['adminStoreURLSSL'];
		$GLOBALS['useStockManagement']=($rs['adminStockManage']!=0);
		$GLOBALS['adminProdsPerPage']=$rs['adminProdsPerPage'];
		$GLOBALS['countryTax']=(float)$rs['countryTax'];
		$GLOBALS['countryTaxRate']=(float)$rs['countryTax'];
		$GLOBALS['delccafter']=(int)$rs['adminDelCC'];
		$GLOBALS['handling']=(float)$rs['adminHandling'];
		$GLOBALS['handlingchargepercent']=(float)$rs['adminHandlingPercent'];
		$GLOBALS['origZip']=$rs['adminZipCode'];
		$GLOBALS['shipType']=(int)$rs['adminShipping'];
		$GLOBALS['adminIntShipping']=(int)$rs['adminIntShipping'];
		$GLOBALS['origCountry']=$rs['countryName'];
		$GLOBALS['origCountryCode']=$rs['countryCode'];
		$GLOBALS['origCountryID']=$rs['countryID'];
		$GLOBALS['adminUnits']=(int)$rs['adminUnits'];
		$GLOBALS['emailAddr']=$rs['adminEmail'];
		$GLOBALS['htmlemails']=$rs['htmlemails'];
		if(@$GLOBALS['htmlemails']) $GLOBALS['emlNl']='<br>'; else $GLOBALS['emlNl']=$GLOBALS['emailcr'];
		$GLOBALS['allStoreEmails']=$rs['adminEmail'];
		$GLOBALS['sendEmail']=($rs['adminEmailConfirm']&1)==1;
		$GLOBALS['adminEmailConfirm']=$rs['adminEmailConfirm'];
		$GLOBALS['adminlanguages']=(int)$rs['adminlanguages'];
		$storelangarr=explode('|',trim_($rs['storelang']));
		$GLOBALS['storelang']=@$storelangarr[$GLOBALS['languageid']-1];
		$GLOBALS['adminlangsettings']=(int)$rs['adminlangsettings'];
		$GLOBALS['currRate1']=(float)$rs['currRate1'];
		$GLOBALS['currSymbol1']=trim_($rs['currSymbol1']);
		$GLOBALS['currRate2']=(float)$rs['currRate2'];
		$GLOBALS['currSymbol2']=trim_($rs['currSymbol2']);
		$GLOBALS['currRate3']=(float)$rs['currRate3'];
		$GLOBALS['currSymbol3']=trim_($rs['currSymbol3']);
		$GLOBALS['currConvUser']=$rs['currConvUser'];
		$GLOBALS['currConvPw']=$rs['currConvPw'];
		$GLOBALS['currLastUpdate']=$rs['currLastUpdate'];
		$GLOBALS['currSymbolText']=$rs['currSymbolText'];
		$GLOBALS['currDecimalSep']=$rs['currDecimalSep'];
		$GLOBALS['currThousandsSep']=$rs['currThousandsSep'];
		$GLOBALS['currPostAmount']=$rs['currPostAmount'];
		$GLOBALS['currDecimals']=$rs['currDecimals'];
		$GLOBALS['currSymbolHTML']=$rs['currSymbolHTML'];
		$GLOBALS['adminSecret']=$rs['adminSecret'];
		$GLOBALS['avalarastate']=$rs['avalarastate'];
		$GLOBALS['avalaraacctno']=$rs['avalaraacctno'];
		$GLOBALS['avalaralicensekey']=$rs['avalaralicensekey'];
		$GLOBALS['avalaracompanycode']=$rs['avalaracompanycode'];
		$GLOBALS['cardinalprocessor']=$rs['cardinalProcessor'];
		$GLOBALS['cardinalmerchant']=$rs['cardinalMerchant'];
		$GLOBALS['cardinalpwd']=$rs['cardinalPwd'];
		$GLOBALS['catalogroot']=$rs['catalogRoot'];
		$GLOBALS['adminAltRates']=$rs['adminAltRates'];
		$GLOBALS['dosortby']=$rs['sortOrder'];
		$GLOBALS['sortoptions']=$rs['sortOptions'];
		$GLOBALS['reCAPTCHAsitekey']=$rs['reCAPTCHAsitekey'];
		$GLOBALS['reCAPTCHAsecret']=$rs['reCAPTCHAsecret'];
		$GLOBALS['reCAPTCHAuseon']=$rs['reCAPTCHAuseon'];
		$GLOBALS['googletagid']=$rs['googleTagID'];
		$GLOBALS['googletagnohead']=$rs['googleTagNoHead'];
		$GLOBALS['onvacation']=$rs['onvacation'];
		$GLOBALS['mailchimpapikey']=$rs['mailchimpAPIKey'];
		$GLOBALS['mailchimplist']=$rs['mailchimpList'];
		$GLOBALS['prodfilter']=$rs['prodFilter'];
		$GLOBALS['sidefilter']=$rs['sideFilter'];
		$GLOBALS['prodfilterorder']=$rs['prodFilterOrder'];
		$GLOBALS['prodfiltertext']=$rs[getlangid('prodFilterText',262144)];
		$GLOBALS['blockmultipurchase']=$rs['blockMultiPurchase'];
		$GLOBALS['blockcontactemails']=$rs['blockContactEmails'];
		$GLOBALS['blockmaxcartadds']=$rs['blockMaxCartAdds'];
		$GLOBALS['adminPayLater']=$rs['adminPayLater'];
		ect_free_result($result);
	}
	// Overrides
	if(@$GLOBALS['orstoreurl']!='') $GLOBALS['storeurl']=$GLOBALS['orstoreurl'];
	if((substr(strtolower($GLOBALS['storeurl']),0,7)!='http://') && (substr(strtolower($GLOBALS['storeurl']),0,8)!='https://') && $GLOBALS['storeurl']!='') $GLOBALS['storeurl']='http://' . $GLOBALS['storeurl'];
	if(substr($GLOBALS['storeurl'],-1)!='/' && $GLOBALS['storeurl']!='') $GLOBALS['storeurl'].='/';
	if(@$GLOBALS['orstoreurlssl']!='') $GLOBALS['storeurlssl']=$GLOBALS['orstoreurlssl'];
	if((substr(strtolower($GLOBALS['storeurlssl']),0,7)!='http://') && (substr(strtolower($GLOBALS['storeurlssl']),0,8)!='https://') && $GLOBALS['storeurlssl']!='') $GLOBALS['storeurlssl']='https://' . $GLOBALS['storeurlssl'];
	if(substr($GLOBALS['storeurlssl'],-1)!='/' && $GLOBALS['storeurlssl']!='') $GLOBALS['storeurlssl'].='/';
	if($GLOBALS['storeurlssl']==''&&$GLOBALS['storeurl']!='') $GLOBALS['storeurlssl']=$GLOBALS['storeurl'];
	if($GLOBALS['storeurl']==''&&$GLOBALS['storeurlssl']!='') $GLOBALS['storeurl']=$GLOBALS['storeurlssl'];
	$GLOBALS['pathtohere']=getdirnamefromurl($GLOBALS['storeurl']);
	if(@$GLOBALS['oremailaddr']!='') $GLOBALS['allStoreEmails']=$GLOBALS['oremailaddr'];
	$allemailsarray=explode(',',$GLOBALS['allStoreEmails']);
	$GLOBALS['emailAddr']=$allemailsarray[0];
	if(@isset($GLOBALS['orcatalogroot'])) $GLOBALS['catalogroot']=$GLOBALS['orcatalogroot'];
	// Language
	if($GLOBALS['origCountryCode']=='GB' || $GLOBALS['origCountryCode']=='IE'){
		$GLOBALS['ssIncTax']=strreplace('Tax','VAT',@$GLOBALS['ssIncTax']);
		$GLOBALS['xxCntTax']='VAT';
	}elseif($GLOBALS['origCountryCode']=='AU' || $GLOBALS['origCountryCode']=='CA'){
		$GLOBALS['xxStaTax']='PST';
		$GLOBALS['xxCntTax']='GST';
		if($GLOBALS['storelang']=='fr' && $GLOBALS['origCountryCode']=='CA'){
			$GLOBALS['xxStaTax']='TVQ';
			$GLOBALS['xxCntTax']='TPS';
		}
	}
	if($GLOBALS['origCountryCode']=='CA' && $GLOBALS['storelang']=='')
		$GLOBALS['xxPostco']='Postal Code';
	if(@$GLOBALS['isectstore']){
		if($GLOBALS['origCountryID']==201){
			//$GLOBALS['dateadjust']=8;
			$GLOBALS['admindateformat']=2;
			$GLOBALS['dateformatstr']='d/m/Y';
			date_default_timezone_set('Europe/London');
		}elseif($GLOBALS['origCountryID']==65||$GLOBALS['origCountryID']==71||$GLOBALS['origCountryID']==93||$GLOBALS['origCountryID']==175){
			//$GLOBALS['dateadjust']=9;
			$GLOBALS['admindateformat']=2;
			$GLOBALS['dateformatstr']='d/m/Y';
			date_default_timezone_set('Europe/Paris');
		}elseif($GLOBALS['origCountryID']==14){
			//$GLOBALS['dateadjust']=17;
			$GLOBALS['admindateformat']=2;
			$GLOBALS['dateformatstr']='d/m/Y';
			date_default_timezone_set('Australia/Perth');
		}
	}
	return(TRUE);
}
function encodeimage($imurl){
	$imurl=strreplace('\\','/',$imurl);
	if($imurl=='prodimages/')$imurl='';
	$imurl=strreplace(array('*','|','<','>','?'),array('%2A','%7C','%3C','%3E','%3F'),$imurl);
	return(strreplace("'","\'",$imurl));
}
function replaceaccentsansi($surl){
	return(iconv('ISO-8859-1','ASCII//TRANSLIT//IGNORE',$surl));
}
function replaceaccentsutf($surl){
	return(iconv('UTF-8','ASCII//TRANSLIT//IGNORE',$surl));
}
function replaceaccents($surl){
	global $adminencoding;
	if(strtolower($adminencoding)=='iso-8859-1') return(replaceaccentsansi($surl)); else if(strtolower($adminencoding)=="utf-8") return(replaceaccentsutf($surl)); else return($surl);
}
function cleanforurl($surl){
global $urlfillerchar;
if(! @isset($urlfillerchar)) $urlfillerchar='_';
$surl=strreplace(' ',$urlfillerchar,strtolower(strip_tags($surl)));
$surl=replaceaccents($surl);
return(preg_replace('/[^a-z\\'.$urlfillerchar.'0-9]/','',$surl));
}
function vrxmlencode($xmlstr){
	return strreplace(array('&','"',"'",'<','>','’'),array('&amp;','&quot;','&apos;','&lt;','&gt;','&apos;'),$xmlstr);
}
function xmlencodecharref($xmlstr){
	$xmlstr=strreplace(array('&reg;','&','<','>','®'),array('','&#x26;','&#x3c;','&#x3e;',''),$xmlstr);
	$tmp_str='';
	for($i=0; $i < strlen($xmlstr); $i++){
		$ch_code=ord(substr($xmlstr,$i,1));
		if($ch_code<=130) $tmp_str.=substr($xmlstr,$i,1);
	}
	return($tmp_str);
}
function getaltlang($col, $bfield){
	global $languageid, $adminlangsettings;
	if(@$languageid==1){
		return($col);
	}else{
		if(($adminlangsettings & $bfield)!=$bfield) return($col);
	}
	return($col . $languageid.' AS ' . $col);
}
function getlangid($col, $bfield){
	global $languageid, $adminlangsettings;
	if(@$languageid==1){
		return($col);
	}else{
		if(($adminlangsettings & $bfield)!=$bfield) return($col);
	}
	return($col . $languageid);
}
function parsedate($tdat){
	global $admindateformat;
	if($admindateformat==0)
		list($year, $month, $day)=sscanf($tdat, '%d-%d-%d');
	elseif($admindateformat==1)
		list($month, $day, $year)=sscanf($tdat, '%d/%d/%d');
	elseif($admindateformat==2)
		list($day, $month, $year)=sscanf($tdat, '%d/%d/%d');
	if(! is_numeric($year))
		$year=date('Y');
	elseif((int)$year < 39)
		$year=(int)$year + 2000;
	elseif((int)$year < 100)
		$year=(int)$year + 1900;
	if($year < 1970 || $year > 2038) $year=date('Y');
	if(! is_numeric($month))
		$month=date('m');
	if(! is_numeric($day))
		$day=date('d');
	return(mktime(0, 0, 0, $month, $day, $year));
}
function unstripslashes($slashedText){
	global $magicq;
	return($magicq||@$GLOBALS['iswordpress']?trim_(stripslashes((string)$slashedText)):trim_((string)$slashedText));
}
function getattributes($attlist,$attid){
	$pos=strpos($attlist, $attid.'=');
	if($pos===FALSE)
		return '';
	$pos+=strlen($attid) + 1;
	$quote=$attlist[$pos];
	$pos2=strpos($attlist, $quote, $pos + 1);
	$retstr=substr($attlist, $pos + 1, $pos2 - ($pos + 1));
	return($retstr); 
}
class vrNodeList{
	var $length;
	var $childNodes;
	var $nodeName;
	var $nodeValue;
	var $attributes;

	function createNodeList($xmlStr){
		if(is_null($xmlStr))$xmlStr='';
		$xLen=strlen($xmlStr);
		for($i=0; $i < $xLen; $i++){
			if(substr($xmlStr, $i, 1)=='<' && substr($xmlStr, $i+1, 1)!='/' && substr($xmlStr, $i+1, 1)!='?'){ // Got a tag
				$j=strpos($xmlStr,'>',$i);
				$l=strpos($xmlStr,' ',$i);
				if(is_integer($l) && $l < $j){
					$this->nodeName[$this->length]=substr($xmlStr,$i+1,$l-($i+1));
					$this->attributes[$this->length]=substr($xmlStr,$l+1,($j-$l)-1);
				}else
					$this->nodeName[$this->length]=substr($xmlStr,$i+1,$j-($i+1));
				$k=$i+1;
				$nodeNameLen=strlen($this->nodeName[$this->length]);
				if(substr($xmlStr, $j-1, 1)=='/'){
					$this->nodeValue[$this->length]=null;
				}else{
					$currLev=0;
					while($k < $xLen && $currLev >= 0){
						if(substr($xmlStr, $k, 2)=='</'){
							if($currLev==0 && substr($xmlStr, $k+2, $nodeNameLen)==$this->nodeName[$this->length])
								break;
							$currLev--;
						}elseif(substr($xmlStr, $k, 1)=='<')
							$currLev++;
						elseif(substr($xmlStr, $k, 2)=='/>')
							$currLev--;
						$k++;
					}
					$this->nodeValue[$this->length]=substr($xmlStr,$j+1,$k-($j+1));
				}
				$this->childNodes[$this->length]=new vrNodeList($this->nodeValue[$this->length]);
				$this->length++;
				$i=$k;
			}
		}
	}
	function __construct($xmlStr){
		$this->length=0;
		$this->childNodes=[];
		$this->createNodeList($xmlStr);
	}
	function getValueByTagName($tagname){
		for($i=0; $i < $this->length; $i++){
			if($this->nodeName[$i]==$tagname){
				return($this->nodeValue[$i]);
			}else{
				if(count($this->childNodes)>0){
					if(($retval=$this->childNodes[$i]->getValueByTagName($tagname))!=null)
						return($retval);
				}
			}
		}
		return(null);
	}
	function getAttributeByTagName($tagname, $attrib){
		for($i=0; $i < $this->length; $i++){
			if($this->nodeName[$i]==$tagname){
				return(getattributes($this->attributes[$i], $attrib));
			}else{
				if(count($this->childNodes)>0){
					if(($retval=$this->childNodes[$i]->getAttributeByTagName($tagname, $attrib))!=null)
						return($retval);
				}
			}
		}
		return(null);
	}
}
class vrXMLDoc{
	var $tXMLStr;
	var $nodeList;
	function __construct($xmlStr){
		$this->tXMLStr=$xmlStr;
		$this->nodeList=new vrNodeList($xmlStr);
	}
	function getElementsByTagName($tagname){
		$currlevel=0;
		$taglen=strlen($tagname);
	}
}
$GLOBALS['codestr']='2952710692840328509902143349209039553396765';
function upsencode($thestr, $propcodestr){
	global $codestr;
	if($propcodestr=='') $localcodestr=$codestr; else $localcodestr=$propcodestr;
	$newstr='';
	for($index=0; $index < strlen($localcodestr); $index++){
		$thechar=substr($localcodestr,$index,1);
		if(! is_numeric($thechar)){
			$thechar=ord($thechar) % 10;
		}
		$newstr.=$thechar;
	}
	$localcodestr=$newstr;
	while(strlen($localcodestr) < 40)
		$localcodestr.=$localcodestr;
	$newstr='';
	for($index=0; $index < strlen($thestr); $index++){
		$thechar=substr($thestr,$index,1);
		$newstr.=chr(ord($thechar)+(int)substr($localcodestr,$index,1));
	}
	return $newstr;
}
function upsdecode($thestr, $propcodestr){
	global $codestr;
	if($propcodestr=='') $localcodestr=$codestr; else $localcodestr=$propcodestr;
	$newstr='';
	if($localcodestr=='') return('');
	for($index=0; $index < strlen($localcodestr); $index++){
		$thechar=substr($localcodestr,$index,1);
		if(! is_numeric($thechar)){
			$thechar=ord($thechar) % 10;
		}
		$newstr.=$thechar;
	}
	$localcodestr=$newstr;
	while(strlen($localcodestr) < 40)
		$localcodestr.=$localcodestr;
	if(is_null($thestr)){
		return '';
	}else{
		$newstr='';
		for($index=0; $index < strlen($thestr); $index++){
			$thechar=substr($thestr,$index,1);
			$newstr.=chr(ord($thechar)-(int)substr($localcodestr,$index,1));
		}
		return($newstr);
	}
}
$locale_info='';
function FormatEuroCurrency($amount){
	$retval='';
	if($GLOBALS['currPostAmount']==0) $retval=$GLOBALS['currSymbolHTML'];
	$retval.=number_format((float)$amount,$GLOBALS['currDecimals'],$GLOBALS['currDecimalSep'],$GLOBALS['currThousandsSep']);
	if($GLOBALS['currPostAmount']!=0) $retval.=$GLOBALS['currSymbolHTML'];
	return($retval);
}
function FormatCurrencyZeroDP($amount){
	$retval='';
	if($GLOBALS['currPostAmount']==0) $retval=$GLOBALS['currSymbolHTML'];
	$retval.=number_format($amount,0,$GLOBALS['currDecimalSep'],$GLOBALS['currThousandsSep']);
	if($GLOBALS['currPostAmount']!=0) $retval.=$GLOBALS['currSymbolHTML'];
	return($retval);
}
function FormatEmailEuroCurrency($amount){
	$retval='';
	if($GLOBALS['currPostAmount']==0) $retval=$GLOBALS['currSymbolText'];
	$retval.=number_format($amount,$GLOBALS['currDecimals'],$GLOBALS['currDecimalSep'],$GLOBALS['currThousandsSep']);
	if($GLOBALS['currPostAmount']!=0) $retval.=$GLOBALS['currSymbolText'];
	return($retval);
}
if(getget('PARTNER')!='' || getget('REFERER')!=''){
	if(@$expireaffiliate=='') $expireaffiliate=30;
	if(getget('PARTNER')!='') $thereferer=strip_tags(getget('PARTNER')); else $thereferer=strip_tags(getget('REFERER'));
	setacookie('PARTNER',htmlspecialsid($thereferer),$expireaffiliate);
}
function docheckpackage($newid){
	$sSQL="SELECT packageID FROM productpackages WHERE pID='".escape_string($newid)."'";
	$result=ect_query($sSQL) or ect_error();
	while($rs=ect_fetch_assoc($result)){
		$sSQL="SELECT pID,quantity FROM productpackages WHERE packageID='".escape_string($rs['packageID'])."'";
		$result2=ect_query($sSQL) or ect_error();
		$sumprice=$sumwsprice=$sumlistprice=$sumweight=0; $stockavailable=100000;
		while($rs2=ect_fetch_assoc($result2)){
			$sSQL="SELECT pPrice,pWholesalePrice,pListPrice,pWeight,pInStock FROM products WHERE pID='".escape_string($rs2['pID'])."'";
			$result3=ect_query($sSQL) or ect_error();
			if($rs3=ect_fetch_assoc($result3)){
				$sumprice+=($rs3['pPrice']*$rs2['quantity']);
				$sumwsprice+=($rs3['pWholesalePrice']*$rs2['quantity']);
				$sumlistprice+=($rs3['pListPrice']*$rs2['quantity']);
				$sumweight+=($rs3['pWeight']*$rs2['quantity']);
				if((int)($rs3['pInStock']/$rs2['quantity'])<$stockavailable) $stockavailable=(int)($rs3['pInStock']/$rs2['quantity']);
			}
			ect_free_result($result3);
		}
		ect_free_result($result2);
		$sSQL="UPDATE products SET pPrice=".$sumprice.",pWholesalePrice=".$sumwsprice.",pListPrice=".$sumlistprice.",pWeight=".$sumweight.",pInStock=".$stockavailable." WHERE pID='".escape_string($rs['packageID'])."'";
		ect_query($sSQL) or ect_error();
	}
	ect_free_result($result);
}
function do_stock_management($smOrdId){
}
function calculate_stock_for_altid($csProdID){
	$availallgroups=1000000;
	$maxallgroups=0;
	$idlist=$csProdID;
	$hasanoption=FALSE;
	$sSQL="SELECT poOptionGroup FROM prodoptions WHERE poProdID='" . escape_string($csProdID) . "' ORDER BY poID";
	$result=ect_query($sSQL) or ect_error();
	while($rs=ect_fetch_assoc($result)){
		$maxthisgroup=0;
		$thisopttype=0;
		$newids='';
		$idarray=explode(' ',trim($idlist));
		$sSQL="SELECT optGroup,optName,optRegExp,optStock,optType FROM options INNER JOIN optiongroup ON options.optGroup=optiongroup.optGrpID WHERE optGroup=" . $rs['poOptionGroup'] . " AND optType IN (-4,-2,-1,1,2,4)";
		$result2=ect_query($sSQL) or ect_error();
		while($rs2=ect_fetch_assoc($result2)){
			$hasanoption=TRUE;
			if(trim_($rs2['optRegExp'])!=''){
				for($index=0;$index<count($idarray);$index++){
					$theid=$idarray[$index];
					$startoptname=@$idoptions[$theid];
					$theexp=trim($rs2['optRegExp']);
					if($theexp!='' && substr($theexp, 0, 1)!='!'){
						$theexp=str_replace('%s',$theid,$theexp);
						if(strpos($theexp,' ')!==FALSE){ // Search and replace
							$exparr=explode(' ', $theexp, 2);
							$theid=str_replace($exparr[0], $exparr[1], $theid);
						}else
							$theid=$theexp;
					}
					$newids.=$theid.' ';
					$idoptions[$theid]=$startoptname . ($startoptname!=''?' / ':'') . $rs2['optName'];
				}
			}else{
				$newids=$idlist;
				$thisopttype=$rs2['optType'];
				if($rs2['optStock']>$maxthisgroup) $maxthisgroup=$rs2['optStock'];
			}
		}
		if($maxthisgroup<$availallgroups && $thisopttype>0) $availallgroups=$maxthisgroup;
		if($maxthisgroup>$maxallgroups) $maxallgroups=$maxthisgroup;
		$idlist=$newids;
		ect_free_result($result2);
	}
	ect_free_result($result);
	if($hasanoption){
		if(trim($idlist)!=$csProdID && trim($idlist)!=''){
			$totalstock=0;
			$idarray=explode(' ',trim($idlist));
			$sSQL="SELECT pID,pInStock FROM products WHERE pID IN (";
			for($index=0;$index<count($idarray);$index++){
				$sSQL.="'" . escape_string($idarray[$index]) . "'";
				if($index!=count($idarray)-1) $sSQL.=",";
			}
			$sSQL.=")";
			$result=ect_query($sSQL) or ect_error();
			if(ect_num_rows($result)>0){
				while($rs=ect_fetch_assoc($result)){
					$totalstock+=$rs['pInStock'];
				}
				$sSQL="UPDATE products SET pStockByOpts=1,pInStock=" . $totalstock . " WHERE pID='" . escape_string($csProdID) . "'";
				ect_query($sSQL) or ect_error();
				//print "REGEXP: " . $sSQL . "<br>";
			}
		}else{
			if($availallgroups>$maxallgroups) $maxallgroups=$availallgroups;
			$sSQL="UPDATE products SET pInStock=" . $availallgroups . " WHERE pID='" . escape_string($csProdID) . "' AND pStockByOpts=1";
			ect_query($sSQL) or ect_error();
			//print "NORMAL: " . $sSQL . "<br>";
		}
	}
}
function calculate_stock_for_options($optgrouplist){
	if($GLOBALS['useStockManagement']){
		$hasaltids=FALSE;
		$sSQL="SELECT DISTINCT poProdID FROM prodoptions WHERE poOptionGroup IN (" . escape_string($optgrouplist) . ")";
		//print $sSQL."<br>";
		$result=ect_query($sSQL) or ect_error();
		while($rs=ect_fetch_assoc($result)){
			calculate_stock_for_altid($rs['poProdID']);
		}
	}
}
function calculate_all_stock_for_options(){
	if($GLOBALS['useStockManagement']){
		$hasaltids=FALSE;
		$sSQL="SELECT pID FROM products WHERE pStockByOpts<>0 AND pDisplay<>0";
		$result=ect_query($sSQL) or ect_error();
		while($rs=ect_fetch_assoc($result)){
			//print 'CS: ' . $rs['pID'] . "<br>";
			calculate_stock_for_altid($rs['pID']);
		}
	}
}
function stock_subtract($smOrdId){
	$optgrouplist='';
	$sSQL="SELECT cartID,cartProdID,cartQuantity,cartOrigProdID,pStockByOpts FROM cart INNER JOIN products ON cart.cartProdID=products.pID WHERE cartOrderID='" . escape_string($smOrdId) . "'";
	$result=ect_query($sSQL) or ect_error();
	while($rs=ect_fetch_assoc($result)){
		$sSQL="UPDATE products SET pNumSales=pNumSales+1 WHERE pID='" . escape_string($rs['cartProdID']) . "'";
		ect_query($sSQL) or ect_error();
		if(trim_($rs['cartOrigProdID'])!=''){
			$sSQL="UPDATE products SET pNumSales=pNumSales+1 WHERE pID='" . escape_string($rs['cartOrigProdID']) . "'";
			ect_query($sSQL) or ect_error();
		}
		if($GLOBALS['useStockManagement']){
			if((int)$rs['pStockByOpts']!=0){
				$sSQL='SELECT coOptID,optGroup FROM cartoptions INNER JOIN options ON cartoptions.coOptID=options.optID INNER JOIN optiongroup ON options.optGroup=optiongroup.optGrpID WHERE optType IN (-4,-2,-1,1,2,4) AND coCartID=' . $rs['cartID'];
				$result2=ect_query($sSQL) or ect_error();
				while($rs2=ect_fetch_assoc($result2)){
					$optgrouplist.=($optgrouplist!=''?',':'').$rs2['optGroup'];
					$sSQL='UPDATE options SET optStock=optStock-' . $rs['cartQuantity'] . ' WHERE optID=' . $rs2['coOptID'];
					ect_query($sSQL) or ect_error();
				}
				ect_free_result($result2);
			}else{
				$sSQL='UPDATE products SET pInStock=pInStock-' . $rs['cartQuantity'] . " WHERE pID='" . $rs['cartProdID'] . "'";
				ect_query($sSQL) or ect_error();
			}
			$sSQL="SELECT pID,quantity FROM productpackages WHERE packageID='" . $rs['cartProdID'] . "'";
			$result2=ect_query($sSQL) or ect_error();
			while($rs2=ect_fetch_assoc($result2)){
				$sSQL='UPDATE products SET pInStock=pInStock-' . ($rs['cartQuantity']*$rs2['quantity']) . " WHERE pID='" . $rs2['pID'] . "'";
				ect_query($sSQL) or ect_error();
			}
			ect_free_result($result2);
			docheckpackage($rs['cartProdID']);
			if(trim_($rs['cartOrigProdID'])!='') calculate_stock_for_altid($rs['cartOrigProdID']);
		}
	}
	ect_free_result($result);
	if($optgrouplist!='') calculate_stock_for_options($optgrouplist);
}
function release_stock($smOrdId){
	$optgrouplist='';
	$sSQL="SELECT cartID,cartProdID,cartQuantity,pStockByOpts FROM cart LEFT JOIN orders ON cart.cartOrderID=orders.ordID INNER JOIN products ON cart.cartProdID=products.pID WHERE ordAuthStatus<>'MODWARNOPEN' AND cartOrderID=" . $smOrdId;
	$result=ect_query($sSQL) or ect_error();
	while($rs=ect_fetch_assoc($result)){
		$sSQL="UPDATE products SET pNumSales=pNumSales-1 WHERE pID='" . escape_string($rs['cartProdID']) . "'";
		ect_query($sSQL) or ect_error();
		if($GLOBALS['useStockManagement']){
			if(((int)$rs['pStockByOpts'] <> 0)){
				$sSQL='SELECT coOptID,optGroup FROM cartoptions INNER JOIN options ON cartoptions.coOptID=options.optID INNER JOIN optiongroup ON options.optGroup=optiongroup.optGrpID WHERE optType IN (-4,-2,-1,1,2,4) AND coCartID=' . $rs['cartID'];
				$result2=ect_query($sSQL) or ect_error();
				while($rs2=ect_fetch_assoc($result2)){
					$optgrouplist.=($optgrouplist!=''?',':'').$rs2['optGroup'];
					$sSQL='UPDATE options SET optStock=optStock+' . $rs['cartQuantity'] . ' WHERE optID=' . $rs2['coOptID'];
					ect_query($sSQL) or ect_error();
				}
				ect_free_result($result2);
			}else{
				$sSQL='UPDATE products SET pInStock=pInStock+' . $rs['cartQuantity'] . " WHERE pID='" . $rs['cartProdID'] . "'";
				ect_query($sSQL) or ect_error();
			}
			$sSQL="SELECT pID,quantity FROM productpackages WHERE packageID='" . $rs['cartProdID'] . "'";
			$result2=ect_query($sSQL) or ect_error();
			while($rs2=ect_fetch_assoc($result2)){
				$sSQL='UPDATE products SET pInStock=pInStock+' . ($rs['cartQuantity']*$rs2['quantity']) . " WHERE pID='" . $rs2['pID'] . "'";
				ect_query($sSQL) or ect_error();
			}
			ect_free_result($result2);
		}
	}
	ect_free_result($result);
	if($optgrouplist!='') calculate_stock_for_options($optgrouplist);
}
function productdisplayscript($doaddprodoptions,$isdetail){
global $prodoptions,$countryTaxRate,$useStockManagement,$OWSP,$noupdateprice,$noprice,$hideoptpricediffs,$showinstock,$noshowoptionsinstock,$showtaxinclusive,$notifybackinstock,$absoptionpricediffs,$usecsslayout,$xxCOTxt,$xxCarCon,$xxSCCarT,$magictool,$imgsoftcartcheckout;
global $currSymbol1,$currFormat1,$currSymbol2,$currFormat2,$currSymbol3,$currFormat3,$pricecheckerisincluded,$currRate1,$currSymbol1,$currRate2,$currSymbol2,$currRate3,$currSymbol3,$currencyseparator,$pricezeromessage,$txtcollen;
if($currSymbol1!='' && $currFormat1=='') $currFormat1='%s <span style="font-weight:bold">'  . $currSymbol1 . '</span>';
if($currSymbol2!='' && $currFormat2=='') $currFormat2='%s <span style="font-weight:bold">'  . $currSymbol2 . '</span>';
if($currSymbol3!='' && $currFormat3=='') $currFormat3='%s <span style="font-weight:bold">'  . $currSymbol3 . '</span>';
	if(! (@$pricecheckerisincluded==TRUE)){
		if(@$_SESSION['clientID']!='' && @$GLOBALS['enablewishlists'] && (@$GLOBALS['wishlistonproducts'] || $isdetail)){ ?>
<div id="savelistdiv" class="savecartlist" onmouseover="oversldiv=true" onmouseout="oversldiv=false;setTimeout('checksldiv()',2500)">
<div onclick="return subformid(gtid,'0','<?php print jsescape($GLOBALS['xxMyWisL'])?>')"><?php print $GLOBALS['xxMyWisL']?></div>
<?php		$sSQL="SELECT listID,listName FROM customerlists WHERE listOwner=" . $_SESSION['clientID'];
			$result2=ect_query($sSQL) or ect_error();
			while($rs2=ect_fetch_assoc($result2)){
				print '<div onclick="return subformid(gtid,\''.$rs2['listID'].'\',\''.jsescape($rs2['listName']).'\')">'.htmlspecials($rs2['listName']).'</div>';
			}
			ect_free_result($result2); ?>
</div>
<?php	}
		if(@$notifybackinstock){ ?>
<div id="notifyinstockcover" class="ectopaque" style="display:none" onclick="if(event.target==this)this.style.display='none'" tabindex="0">
	<div class="ectsoftwrapper"><div class="scart scclose" role="img" onclick="closeinstock()" title="<?php print htmlspecials($GLOBALS['xxClsWin'])?>"></div>
		<div class="softformheader"><?php print $GLOBALS['xxNotSor']?></div>
		<div style="margin:20px;text-align:center"><h2><?php print $GLOBALS['xxNotCur']?></h2></div>
		<div style="padding:20px;text-align:center;font-weight:bold;"><?php print $GLOBALS['xxNotEnt']?></div>
		<div style="padding:20px;" class="ectsf2col"><div><?php print labeltxt($GLOBALS['xxEmail'],'nsemailadd')?></div><div><input class="ectinput" id="nsemailadd" type="text"></div></div>
		<div class="softformsend"><input type="button" class="ectbutton" value="<?php print $GLOBALS['xxEmaiMe']?>" onclick="regnotifystock()"></div>
	</div>
</div>
<?php	}
?><input type="hidden" id="hiddencurr" value="<?php print strreplace('"','&quot;',FormatEuroCurrency(0))?>"><div id="opaquediv" class="ectopaque" style="display:none" onclick="if(event.target==this)this.style.display='none'" tabindex="0"></div><?php
//if(recaptchaenabled(2)) displayrecaptchajs('efcaptcha',FALSE,FALSE);
?><script>
/* <![CDATA[ */
<?php
print 'var xxAddWiL="' . jscheck($GLOBALS['xxAddWiL']) . '",' .
		'xxBakOpt="' . jscheck($GLOBALS['xxBakOpt']) . '",' .
		'xxCarCon="' . jscheck($GLOBALS['xxCarCon']) . '",' .
		'xxClkHere="' . jscheck($GLOBALS['xxClkHere']) . '",' .
		'xxClsWin="' . jscheck($GLOBALS['xxClsWin']) . '",' .
		'xxCntShp="' . jscheck($GLOBALS['xxCntShp']) . '",' .
		'xxCntTax="' . jscheck($GLOBALS['xxCntTax']) . '",' .
		'xxDigits="' . jscheck($GLOBALS['xxDigits']) . '",' .
		'xxDscnts="' . jscheck($GLOBALS['xxDscnts']) . '",' .
		'xxEdiOrd="' . jscheck($GLOBALS['xxEdiOrd']) . '",' .
		'xxEntMul="' . jscheck($GLOBALS['xxEntMul']) . '",' .
		'xxHasAdd="' . jscheck($GLOBALS['xxHasAdd']) . '",' .
		'xxInStNo="' . jscheck($GLOBALS['xxInStNo']) . '",' .
		'xxInvCha="' . jscheck($GLOBALS['xxInvCha']) . '",' .
		'xxListPrice="' . jscheck($GLOBALS['xxListPrice']) . '",' .
		'xxAddToC="' . jscheck($GLOBALS['xxAddToC']) . '",' .
		'xxNotBaS="' . jscheck($GLOBALS['xxNotBaS']) . '",' .
		'xxNotSto="' . jscheck($GLOBALS['xxNotSto']) . '",' .
		'xxBakOrd="' . jscheck($GLOBALS['xxBakOrd']) . '",' .
		'xxOpSkTx="' . jscheck($GLOBALS['xxOpSkTx']) . '",' .
		'xxOptOOS="' . jscheck($GLOBALS['xxOptOOS']) . '",' .
		'xxOutStok="' . jscheck($GLOBALS['xxOutStok']) . '",' .
		'xxPrd255="' . jscheck($GLOBALS['xxPrd255']) . '",' .
		'xxPrdChs="' . jscheck($GLOBALS['xxPrdChs']) . '",' .
		'xxPrdEnt="' . jscheck($GLOBALS['xxPrdEnt']) . '",' .
		'xxPrice="' . jscheck($GLOBALS['xxPrice']) . '",' .
		'xxSCAdOr="' . jscheck($GLOBALS['xxSCAdOr']) . '",' .
		'xxSCBakO="' . jscheck($GLOBALS['xxSCBakO']) . '",' .
		'xxSCCarT="' . jscheck($GLOBALS['xxSCCarT']) . '",' .
		'xxSCItem="' . jscheck($GLOBALS['xxSCItem']) . '",' .
		'xxSCStkW="' . jscheck($GLOBALS['xxSCStkW']) . '",' .
		'xxCOTxt="' . jscheck($GLOBALS['xxCOTxt']) . '",' .
		'xxValEm="' . jscheck($GLOBALS['xxValEm']) . "\";\r\n";
$tempStr=FormatEuroCurrency(0);
print "var " . (@$GLOBALS['absoptionpricediffs'] ? 'absoptionpricediffs=true,' : '') .
		(@$GLOBALS['cartpageonhttps'] ? 'cartpageonhttps=true,' : '') .
		(@$GLOBALS['currDecimalSep']!='.' ? "currDecimalSep='" . jsescape(@$GLOBALS['currDecimalSep']) . "'," : '') .
		(@$GLOBALS['currencyseparator']!='' ? "currencyseparator='" . jsescape(@$GLOBALS['currencyseparator']) . "'," : '') .
		(@$GLOBALS['iosoos']!='' ? "iosoos='" . jsescape(@$GLOBALS['iosoos']) . "'," : '') .
		(@$GLOBALS['currThousandsSep']!=',' ? "currThousandsSep='" . jsescape(@$GLOBALS['currThousandsSep']) . "'," : '') .
		(@$GLOBALS['ectbody3layouttaxinc'] ? "ectbody3layouttaxinc=true," : '') .
		"extension='" . @$GLOBALS['extension'] . "'," .
		"extensionabs='php'," .
		(strstr($tempStr,',')===FALSE && strstr($tempStr,'.')===FALSE ? "hasdecimals=false," : '') .
		(@$GLOBALS['hideoptpricediffs'] ? "hideoptpricediffs=true," : '') .
		"imgsoftcartcheckout='" . jsescapel(imageorbutton(@$GLOBALS['imgsoftcartcheckout'],$GLOBALS['xxCOTxt'],'sccheckout',(@$GLOBALS['cartpageonhttps']?@$GLOBALS['storeurlssl']:'').'cart'.$GLOBALS['extension'], FALSE)) . "'," .
		(@$GLOBALS['noprice'] ? "noprice=true," : '') .
		(@$GLOBALS['nopriceanywhere'] ? "nopriceanywhere=true," : '') .
		(@$GLOBALS['noshowoptionsinstock'] ? "noshowoptionsinstock=true," : '') .
		(@$GLOBALS['notifybackinstock'] ? "notifybackinstock=true," : '') .
		(@$GLOBALS['noupdateprice'] ? "noupdateprice=true," : '') .
		'pricezeromessage="' . jscheck(@$GLOBALS['pricezeromessage']) . '",' .
		(@$GLOBALS['showinstock'] ? "showinstock=true," : '') .
		(@$GLOBALS['stockdisplaythreshold'] ? "stockdisplaythreshold=" . $GLOBALS['stockdisplaythreshold'] . ',' : '') .
		"showtaxinclusive=" . $GLOBALS['showtaxinclusive'] . ',' .
		"storeurlssl='" . $GLOBALS['storeurlssl'] . "'," .
		"tax=" . replace($GLOBALS['countryTaxRate'],",",".") . ',' .
		"txtcollen=" . $GLOBALS['txtcollen'] . ',' .
		(@$GLOBALS['usehardaddtocart'] ? "usehardaddtocart=true," : '') .
		(@$GLOBALS['useStockManagement'] ? "usestockmanagement=true," : '') .
		(@$GLOBALS['softcartrelated'] ? "softcartrelated=true," : '') .
		(@$GLOBALS['softcartupsell']!='' ? "softcartupsell=true," : '') .
		'yousavetext="' . jscheck(@$GLOBALS['yousavetext']) . '",' .
		"zero2dps='" . number_format(0,2,'.',',') . "'," .
		"currFormat1='" . jsescapel($GLOBALS['currFormat1']) . "',currFormat2='" . jsescapel($GLOBALS['currFormat2']) . "',currFormat3='" . jsescapel($GLOBALS['currFormat3']) . "'," .
		"currRate1=" . $GLOBALS['currRate1'] . ",currRate2=" . $GLOBALS['currRate2'] . ",currRate3=" . $GLOBALS['currRate3'] . ',' .
		"currSymbol1='" . jsescapel($GLOBALS['currSymbol1']) . "',currSymbol2='" . jsescapel($GLOBALS['currSymbol2']) . "',currSymbol3='" . jsescapel($GLOBALS['currSymbol3']) . "';\r\n";
?>
function updateoptimage(theitem,themenu,opttype){
var imageitemsrc='',mzitem,theopt,theid,imageitem,imlist,imlistl,fn=window['updateprice'+theitem];
fn();
if(opttype==1){
	theopt=document.getElementsByName('optn'+theitem+'x'+themenu);
	for(var i=0; i<theopt.length; i++){
		if(theopt[i].checked)theid=theopt[i].value;
		ectremoveclass(theopt[i],'ectwarning');
	}
}else{
	theopt=ectById('optn'+theitem+'x'+themenu);
	ectremoveclass(theopt,'ectwarning');
	theid=theopt.options[theopt.selectedIndex].value;
}
<?php	if(@$magictool!=''){ ?>
if(mzitem=(ectById("zoom1")?ectById("zoom1"):ectById("mz"+(globalquickbuyid!==''?'qb':'prod')+"image"+theitem))){
	if(altimage_small!=''){
		if(altimage_large=='')altimage_large=altimage_small;
		<?php print $magictool?>.update(mzitem,vsdecimg(altimage_large),vsdecimg(altimage_small));
	}else if(aIML[theid]){
		<?php print $magictool?>.update(mzitem,vsdecimg(aIML[theid]),vsdecimg(aIM[theid]));
	}else if(pIM[0]&&pIM[999]){
		imlist=pIM[0];imlistl=pIM[999];
		for(var index=0;index<imlist.length;index++)
			if(imlist[index]==aIM[theid]&&imlistl[index]){<?php print $magictool?>.update(mzitem.id,vsdecimg(imlistl[index]),vsdecimg(aIM[theid]));return;}
		if(aIM[theid])<?php print $magictool?>.update(mzitem.id,vsdecimg(aIM[theid]),vsdecimg(aIM[theid]));
	}else if(aIM[theid])
		<?php print $magictool?>.update(mzitem.id,vsdecimg(aIM[theid]),vsdecimg(aIM[theid]));
}else
<?php	} ?>
	if(imageitem=ectById((globalquickbuyid!==''?'qb':'prod')+"image"+theitem)){
		if(altimage_small!=''){
			if(typeof(imageitem.src)!='unknown')imageitem.src=vsdecimg(altimage_small);
		}else if(aIM[theid]){
			if(typeof(imageitem.src)!='unknown')imageitem.src=vsdecimg(aIM[theid]);
		}
	}
	altimage_small='';
	altimage_large='';
}
function vsdecimg(timg){
	return decodeURIComponent(timg<?php print @$GLOBALS['noencodeimages']?'':'.replace("|","prodimages/").replace("<",".gif").replace(">",".jpg").replace("?",".png")'?>);
}
function updateprodimage(theitem,isnext){
	return updateprodimage2(false,theitem,isnext);
}
function updateprodimage2(isqb,theitem,isnext){
var imlist=pIM[theitem];
if(!pIX[theitem])pIX[theitem]=0;
if(isnext) pIX[theitem]++; else pIX[theitem]--;
if(pIX[theitem] < 0) pIX[theitem]=imlist.length-1;
if(pIX[theitem]>=imlist.length) pIX[theitem]=0;
if(ectById((isqb?'qb':'prod')+"image"+theitem)){
	var telem=ectById((isqb?'qb':'prod')+"image"+theitem);
	var imgsrc=vsdecimg(imlist[pIX[theitem]]);
	var fileext=imgsrc.split('.').pop().toLowerCase();
	telem.src='';
	if(ectisvideoext(fileext)){
		if(telem.nodeName.toUpperCase()!='VIDEO') telem=swapimgandvideoelem(telem,'video');
	}else{
		if(telem.nodeName.toUpperCase()!='IMG') telem=swapimgandvideoelem(telem,'img');
	}
	telem.src=imgsrc;
}
ectById((isqb?'qb':'extra')+"imcnt"+theitem).innerHTML=pIX[theitem]+1;
<?php	if(@$magictool!=''){ ?>
if(pIML[theitem]){
	var imlistl=pIML[theitem];
	if(imlistl.length>=pIX[theitem])
		if(mzitem=ectById("mz"+(isqb?'qb':'prod')+"image"+theitem))<?php print $magictool?>.update(mzitem,vsdecimg(imlistl[pIX[theitem]]),vsdecimg(imlist[pIX[theitem]]));
}
<?php	} ?>
return false;
}
/* ]]> */
</script><?php
		$pricecheckerisincluded=TRUE;
	}
}
function updatepricescript(){
	global $rs,$extraimages,$giftcertificateid,$donationid,$useStockManagement,$showinstock,$noshowoptionsinstock,$prodoptions,$Count,$allimages,$numallimages,$alllgimages,$numalllgimages;
	$prodoptions=[];
	$sSQL="SELECT poOptionGroup,optType,optFlags,optTxtMaxLen,optAcceptChars,0 AS isDepOpt FROM prodoptions INNER JOIN optiongroup ON optiongroup.optGrpID=prodoptions.poOptionGroup WHERE poProdID='".$rs['pId']."' AND NOT (poProdID='".$giftcertificateid."' OR poProdID='".$donationid."') ORDER BY poID";
	$result=ect_query($sSQL) or ect_error();
	for($rowcounter=0;$rowcounter<ect_num_rows($result);$rowcounter++){
		$prodoptions[$rowcounter]=ect_fetch_assoc($result);
	}
	ect_free_result($result);
	if($numallimages>1){
		print '<script>/* <![CDATA[ */' . "\r\n" . 'pIM['.$Count."]=['".encodeimage($allimages[0]['imageSrc'])."'";
		$extraimages=1;
		for($index=1;$index<$numallimages;$index++){
			print ",'" . encodeimage($allimages[$index]['imageSrc'])."'"; $extraimages++;
		}
		print "];\r\n";
		if($numalllgimages>1){
			print 'pIML['.$Count."]=['".encodeimage($alllgimages[0]['imageSrc'])."'";
			for($index=1;$index<$numalllgimages;$index++)
				print ",'" . encodeimage($alllgimages[$index]['imageSrc'])."'";
			print "];\r\n";
		}
		print '/* ]]> */</script>';
	}
}
function checkDPs($currcode){
	if($currcode=='JPY'||$currcode=='TWD') return(0); else return(2);
}
function checkCurrencyRates($currConvUser,$currConvPw,$currLastUpdate,&$currRate1,$currSymbol1,&$currRate2,$currSymbol2,&$currRate3,$currSymbol3){
	global $countryCurrency;
	$ccsuccess=TRUE;
	if($currConvUser!="" && (strtotime($currLastUpdate) < time()-(60*60*24))){
		$str="";
		if($currSymbol1!='') $str.='&curr=' . $currSymbol1;
		if($currSymbol2!='') $str.='&curr=' . $currSymbol2;
		if($currSymbol3!='') $str.='&curr=' . $currSymbol3;
		if($str==''){
			ect_query("UPDATE admin SET currLastUpdate='" . date('Y-m-d H:i:s', time()) . "'") or ect_error();
			return;
		}
		$str='?source=' . $countryCurrency . '&user=' . $currConvUser . '&pw=' . $currConvPw . $str;
		if($ccsuccess=callcurlfunction('https://www.ecommercetemplates.com/currencyxml.asp'.$str,'',$sXML,'',$errormsg,FALSE)){
			$xmlDoc=new vrXMLDoc($sXML);
			$nodeList=$xmlDoc->nodeList->childNodes[0];
			for($j=0; $j < $nodeList->length; $j++){
				if($nodeList->nodeName[$j]=='currError'){
					notification_err_msg($nodeList->nodeValue[$j]);
					$ccsuccess=FALSE;
				}elseif($nodeList->nodeName[$j]=='selectedCurrency'){
					$e=$nodeList->childNodes[$j];
					$currRate=0;
					for($i=0; $i < $e->length; $i++){
						if($e->nodeName[$i]=='currSymbol')
							$currSymbol=$e->nodeValue[$i];
						elseif($e->nodeName[$i]=='currRate')
							$currRate=$e->nodeValue[$i];
					}
					if($currSymbol1==$currSymbol){
						$currRate1=$currRate;
						ect_query('UPDATE admin SET currRate1=' . $currRate . ' WHERE adminID=1') or ect_error();
					}
					if($currSymbol2==$currSymbol){
						$currRate2=$currRate;
						ect_query('UPDATE admin SET currRate2=' . $currRate . ' WHERE adminID=1') or ect_error();
					}
					if($currSymbol3==$currSymbol){
						$currRate3=$currRate;
						ect_query('UPDATE admin SET currRate3=' . $currRate . ' WHERE adminID=1') or ect_error();
					}
				}
			}
			if($ccsuccess) ect_query("UPDATE admin SET currLastUpdate='" . date('Y-m-d H:i:s', time()) . "'");
		}
	}
}
function getsectionids($thesecid, $delsections){
	global $returnalltopsections;
	$resolvedids='';
	$secarr=explode(',', $thesecid);
	$secid=''; $addcomma=''; $addcomma2='';
	foreach($secarr as $sect){
		if(is_numeric(trim_($sect))) $secid.=$addcomma . "'".(int)$sect."'"; $addcomma=',';
	}
	if($secid=='') $secid='0';
	$iterations=0;
	$iteratemore=TRUE;
	if(@$_SESSION['clientLoginLevel']!='') $minloglevel=$_SESSION['clientLoginLevel']; else $minloglevel=0;
	if($delsections) $nodel=''; else $nodel='sectionDisabled<=' . $minloglevel . ' AND ';
	if(@$GLOBALS['usesubsectioncache'] && ! $delsections && is_numeric($thesecid)){
		$sSQL2="SELECT subSections FROM subsectionidcache WHERE sectionID='" . escape_string($thesecid) . "' AND sectionDisabled=" . $minloglevel;
		$result2=ect_query($sSQL2) or ect_error();
		if($rs2=ect_fetch_assoc($result2)) $resolvedids=trim_($rs2['subSections']);
	}
	if($resolvedids==''){
		while($iteratemore && $iterations<10){
			$sSQL2='SELECT DISTINCT sectionID,rootSection FROM sections WHERE ' . $nodel . '(topSection IN (' . $secid . ')';
			if($iterations==0) $sSQL2.=' OR (sectionID IN (' . $secid . ') AND rootSection=1))'; else $sSQL2.=')';
			$secid='';
			$iteratemore=FALSE;
			$result2=ect_query($sSQL2) or ect_error();
			$addcomma='';
			while($rs2=ect_fetch_assoc($result2)){
				if($rs2['rootSection']==0){
					if(@$returnalltopsections){ $resolvedids.=$addcomma2 . $rs2['sectionID']; $addcomma2=','; }
					$iteratemore=TRUE;
					$secid.=$addcomma . $rs2['sectionID'];
					$addcomma=',';
				}else{
					$resolvedids.=$addcomma2 . $rs2['sectionID'];
					$addcomma2=',';
				}
			}
			$iterations++;
		}
		if($resolvedids=='') $resolvedids='0';
		if(@$GLOBALS['usesubsectioncache']){
			$sSQL2="INSERT INTO subsectionidcache (sectionID,sectionDisabled,subSections) VALUES (".$thesecid.",".$minloglevel.",'".$resolvedids."')";
			ect_query($sSQL2);
		}
	}
	return($resolvedids);
}
function callcurlfunction($cfurl, $cfxml, &$cfres, $cfcert, &$cferrmsg, $settimeouts){
	global $curlproxy,$pathtocurl,$xmlfnheaders,$debugxmlemails,$emailAddr,$htmlemails,$http_status,$xmlfnuser,$xmlfnpassword;
	$cfsuccess=TRUE;
	$GLOBALS['callxmlfunctionstatus']=0;
	$cfres='';
	if(@$pathtocurl!=''){
		exec($pathtocurl . ($cfcert!='' ? ' -E \'' . $cfcert . '\'' : '') . ' --data-binary ' . escapeshellarg($cfxml) . ' ' . $cfurl, $cfres, $retvar);
		$cfres=implode("\n",$cfres);
		if($cfres==''){ $cferrmsg='No response from path: '.$pathtocurl; $cfsuccess=FALSE; }
	}else{
		if(!function_exists('curl_init')||!$ch=curl_init()) {
			$cferrmsg='cURL package not installed in PHP. Set \$pathtocurl parameter.';
			$cfsuccess=FALSE;
		}else{
			curl_setopt($ch, CURLOPT_URL, $cfurl);
			if($xmlfnuser!='' && $xmlfnpassword!=''){
				curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
				curl_setopt($ch, CURLOPT_USERPWD,$xmlfnuser.':'.$xmlfnpassword);
			}
			if(is_array($xmlfnheaders))curl_setopt($ch, CURLOPT_HTTPHEADER, $xmlfnheaders);
			if($cfcert!=''){
				if(substr($cfcert,0,6)=='CAINFO'){
					$cfcert=substr($cfcert,6);
					curl_setopt($ch,CURLOPT_CAINFO,$cfcert);
				}else
					curl_setopt($ch,CURLOPT_SSLCERT,$cfcert);
			}
			if($cfxml!=''||@$GLOBALS['callxmlfunctionforcemethod']!=''){@$GLOBALS['callxmlfunctionforcemethod']!='' ? curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $GLOBALS['callxmlfunctionforcemethod']) : curl_setopt($ch, CURLOPT_POST, 1); }
			curl_setopt($ch, CURLOPT_HEADER, 0);
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
			if($cfxml!='')curl_setopt($ch, CURLOPT_POSTFIELDS, $cfxml);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			if($settimeouts===TRUE)
				curl_setopt($ch, CURLOPT_TIMEOUT, 25);
			elseif($settimeouts)
				curl_setopt($ch, CURLOPT_TIMEOUT, $settimeouts);
			if(@$curlproxy!='')
				curl_setopt($ch, CURLOPT_PROXY, $curlproxy);
			$cfres=curl_exec($ch);
			$http_status=curl_getinfo($ch, CURLINFO_HTTP_CODE);
			if(curl_error($ch)!=''&&curl_errno($ch)!=0){
				if($cfcert!='' && ! is_file($cfcert)){
					$cferrmsg='Certificate file not found: ' . $cfcert . '<br>';
				}else
					$cferrmsg=curl_error($ch) . '<br>';
				$cfsuccess=FALSE;
			}elseif($http_status==0){
				$cfsuccess=FALSE;
				$cferrmsg='Could not connect to the URL: ' . $cfurl;
			}else{
				$GLOBALS['callxmlfunctionstatus']=$http_status;
				if(@$GLOBALS['callcurlfunctionhttperrors']&&$http_status!=200&&$http_status!=201){
					$cfsuccess=FALSE;
					$cferrmsg='ERROR: ' . $http_status . ' : ' .$cfres;
				}
			}
		}
	}
	if(@$debugxmlemails){ dosendemail($emailAddr,$emailAddr,'','PHP XML Function Debug',(@$GLOBALS['htmlemails']?strreplace('<','&lt;',$cfxml):$cfxml).$GLOBALS['emlNl'].$GLOBALS['emlNl'].(@$GLOBALS['htmlemails']?strreplace('<','&lt;',$cfres):$cfres).$GLOBALS['emlNl'].$GLOBALS['emlNl'].$cfsuccess); }
	if(@$GLOBALS['adminLogging']){
		logevent(substr(getipaddress(), 0, 24),$cfurl,$cfsuccess,@debug_backtrace()[1]['function'],'',"REQUEST\n\n".$cfxml."\n\nRESPONSE\n\n".$cfres);
	}
	$xmlfnheaders=$xmlfnuser=$xmlfnpassword='';
	$GLOBALS['callcurlfunctionhttperrors']=FALSE;
	$GLOBALS['callxmlfunctionforcemethod']='';
	return($cfsuccess);
}
function getpayprovdetails($ppid,&$ppdata1,&$ppdata2,&$ppdata3,&$ppdemo,&$ppmethod){
	return(getpayprovdetx($ppid,$ppdata1,$ppdata2,$ppdata3,$ppdata4,$ppdata5,$ppdata6,$ppflag1,$ppflag2,$ppflag3,$ppbits,$ppdemo,$ppmethod));
}
function getpayprovdetx($ppid,&$ppdata1,&$ppdata2,&$ppdata3,&$ppdata4,&$ppdata5,&$ppdata6,&$ppflag1,&$ppflag2,&$ppflag3,&$ppbits,&$ppdemo,&$ppmethod){
	$sSQL="SELECT payProvData1,payProvData2,payProvData3,payProvData4,payProvData5,payProvData6,payProvFlag1,payProvFlag2,payProvFlag3,payProvBits,payProvDemo,payProvMethod FROM payprovider WHERE payProvEnabled=1 AND payProvID='" . escape_string($ppid=='26'?25:$ppid) . "'";
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		$ppdata1=trim_($rs['payProvData1']);
		$ppdata2=trim_($rs['payProvData2']);
		$ppdata3=trim_($rs['payProvData3']);
		$ppdata4=trim_($rs['payProvData4']);
		$ppdata5=trim_($rs['payProvData5']);
		$ppdata6=trim_($rs['payProvData6']);
		$ppflag1=trim_($rs['payProvFlag1']);
		$ppflag2=trim_($rs['payProvFlag2']);
		$ppflag3=trim_($rs['payProvFlag3']);
		$ppbits=trim_($rs['payProvBits']);
		$ppdemo=((int)$rs['payProvDemo']==1);
		$ppmethod=(int)$rs['payProvMethod'];
		if($ppid==27){
			$ppdemo=FALSE;
		}
	}else
		return(FALSE);
	return(TRUE);
}
function writehiddenvar($hvname,$hvval){
print '<input type="hidden" name="' . $hvname . '" value="' . htmlspecials($hvval) . '">' . "\n";
}
function writehiddenidvar($hvname,$hvval){
print '<input type="hidden" name="' . $hvname . '" id="' . $hvname . '" value="' . htmlspecials($hvval) . '">' . "\n";
}
function ppsoapheader($username, $password, $signature){
return '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Header><RequesterCredentials xmlns="urn:ebay:api:PayPalAPI"><Credentials xmlns="urn:ebay:apis:eBLBaseComponents">' . (strpos($username,'@AB@')===FALSE ? '<Username>' . $username . '</Username><Password>' . $password . '</Password>' . ($signature!='' ? '<Signature>' . $signature . '</Signature>' : '') : '<Subject>'.strreplace('@AB@','',$username).'</Subject>') . '</Credentials></RequesterCredentials></soap:Header>';
}
function getoptpricediff($opd,$theid,$theexp,$pprice,&$pstock){
	global $WSP;
	$retval=(float)$opd;
	if($theexp!='' && substr($theexp, 0, 1)!='!'){
		$theexp=strreplace('%s', $theid, $theexp);
		if(strpos($theexp, ' ')!==FALSE){ // Search and replace
			$exparr=explode(' ', $theexp, 2);
			$theid=strreplace($exparr[0], $exparr[1], $theid);
		}else
			$theid=$theexp;
		$sSQL='SELECT '.$WSP."pPrice,pInStock FROM products WHERE pID='".escape_string($theid)."'";
		$result3=ect_query($sSQL) or ect_error();
		if($rs3=ect_fetch_assoc($result3)){ $retval=$rs3['pPrice']-$pprice; $pstock=$rs3['pInStock']; }
		ect_free_result($result3);
	}
	return($retval);
}
function addtoaltids($theexp, &$altidarr, &$altids){
	$theexp=trim_($theexp);
	if($theexp!='' && substr($theexp, 0, 1)!='!'){
		$GLOBALS['hasaltid']=TRUE;
		if(! is_array($altidarr)){
			$altidarr=explode(' ', trim_($altids));
			$altids='';
		}
		foreach($altidarr as $theid){
			if(strpos($altids,$theid.' ')===FALSE) $altids.=$theid . ' ';
			$theexpa=strreplace('%s', $theid, $theexp);
			if(strpos($theexpa, ' ')!==FALSE){ // Search and replace
				$exparr=explode(' ', $theexpa, 2);
				$theid=strreplace($exparr[0], $exparr[1], $theid);
			}else
				$theid=$theexpa;
			if(strpos($altids,$theid.' ')===FALSE) $altids.=$theid . ' ';
		}
	}
}
$optjsunique=',';
function addtooptionsjs(&$optionsjs, $isdetail, $origoptpricediff){
	global $rs2,$useStockManagement,$optjsunique,$magictoolboxproducts;
	if(strpos($optjsunique,','.$rs2['optID'].',')===FALSE){
		if($useStockManagement) $optionsjs.='oS['.$rs2['optID'].']='.$rs2['optStock'].';';
		if(($rs2['optRegExp']=='' || substr($rs2['optRegExp'],0,1)=='!') && $origoptpricediff!=0)$optionsjs.='op['.$rs2['optID'].']='.$origoptpricediff.';';
		if($rs2['optRegExp']!='' && substr($rs2['optRegExp'],0,1)!='!')$optionsjs.='or['.$rs2['optID']."]='".$rs2['optRegExp']."';";
		$optionsjs.='ot['.$rs2['optID'].']="'.jscheck($rs2[getlangid('optName',32)]).'";';
		if(trim_($rs2['optAlt'.($isdetail?'Large':'').'Image'])!='') $optionsjs.='aIM['.$rs2['optID']."]='".encodeimage($rs2['optAlt'.($isdetail?'Large':'').'Image'])."';";
		if(trim_($rs2['optDependants'])!='') $optionsjs.='dOP['.$rs2['optID'].']=['.$rs2['optDependants'].'];';
		if(@$magictoolboxproducts!='' && ! $isdetail && trim_($rs2['optAltLargeImage'])!='') $optionsjs.='aIML['.$rs2['optID']."]='".encodeimage($rs2['optAltLargeImage'])."';";
		$optionsjs.="\n";
		$optjsunique.=$rs2['optID'].',';
	}
}
function getoptionspricediff($thetax){
	global $rs,$rs2,$prodoptions,$WSP,$OWSP,$showtaxinclusive;
	$altidarr='';
	$optpricediff=$rowcounter=0;
	$altids=$rs['pId'];
	$maxindex=count($prodoptions)-1;
	while($rowcounter<=$maxindex){
		$theopt=$prodoptions[$rowcounter];
		$opthasstock=FALSE;
		$sSQL='SELECT optID,'.getlangid('optName',32).','.getlangid('optGrpName',16).',' . $OWSP . 'optPriceDiff,optType,optGrpSelect,optFlags,optTxtMaxLen,optTxtCharge,optStock,optPriceDiff AS optDims,optDefault,optAltImage,optAltLargeImage,optRegExp,'.getlangid('optPlaceholder',16).','.($theopt['isDepOpt']==1?"'' AS ":'').'optDependants,optTooltip,optClass FROM options LEFT JOIN optiongroup ON options.optGroup=optiongroup.optGrpID WHERE optGroup=' . $theopt['poOptionGroup'] . ' ORDER BY optID';
		$result=ect_query($sSQL) or ect_error();
		if($rs2=ect_fetch_assoc($result)){
			if(abs((int)$rs2['optType'])==5){ // Date Picker
			}elseif(abs((int)$rs2['optType'])==3){ // Text
			}elseif(abs((int)$rs2['optType'])==1){ // Checkbox / Radio
				do {
					$origoptpricediff=getoptpricediff($rs2['optPriceDiff'],$rs['pId'],trim_($rs2['optRegExp']),$rs['pPrice'],$stocknotused);
					addtoaltids($rs2['optRegExp'], $altidarr, $altids);
					if($rs2['optDefault']!=0 && $origoptpricediff!=0 && trim_($rs2['optRegExp'])==''){
						if(($rs2['optFlags']&1)==1)$pricediff=($rs['pPrice']*$origoptpricediff)/100.0;else$pricediff=$origoptpricediff;
						if(@$showtaxinclusive===2 && ($rs['pExemptions'] & 2)!=2) $pricediff+=($pricediff*$thetax/100.0);
						$optpricediff+=$pricediff;
					}
				} while($rs2=ect_fetch_assoc($result));
				unset($altidarr);
			}elseif(abs((int)$rs2['optType'])==4){ // Multi
			}else{ // Select
				$gotdefaultdiff=FALSE;
				$firstpricediff=0;
				$origoptpricediff=$rs2['optPriceDiff'];
				if((int)$rs2['optGrpSelect']==0)
					if(($rs2['optFlags']&1)==1)$firstpricediff=($rs['pPrice']*$origoptpricediff)/100.0;else $firstpricediff=$origoptpricediff;
				do {
					$origoptpricediff=getoptpricediff($rs2['optPriceDiff'],$rs['pId'],trim_($rs2['optRegExp']),$rs['pPrice'],$stocknotused);
					addtoaltids($rs2['optRegExp'], $altidarr, $altids);
					if($rs2['optDefault']!=0 && trim_($rs2['optRegExp'])==''){
						if($origoptpricediff!=0){
							if(($rs2['optFlags']&1)==1)$pricediff=($rs['pPrice']*$origoptpricediff)/100.0;else $pricediff=$origoptpricediff;
							if(@$showtaxinclusive===2 && ($rs['pExemptions'] & 2)!=2) $pricediff+=($pricediff*$thetax/100.0);
							$optpricediff+=$pricediff;
						}
						$gotdefaultdiff=TRUE;
					}
				} while($rs2=ect_fetch_assoc($result));
				unset($altidarr);
				if(! $gotdefaultdiff) $optpricediff+=$firstpricediff;
			}
		}
		ect_free_result($result);
		$rowcounter++;
	}
	return($optpricediff);
}
$GLOBALS['hasincludedpopcalendar']=FALSE;
$GLOBALS['mustincludepopcalendar']=FALSE;
function displayproductoptions(&$optpricediff,$thetax,$isdetail,&$hasmulti,&$optionsjs){
	global $rs,$rs2,$prodoptions,$useStockManagement,$hideoptpricediffs,$noprice,$WSP,$OWSP,$Count,$optionshavestock,$noshowoptionsinstock,$showinstock,$showtaxinclusive,$defimagejs,$multipurchasecolumns,$startlink,$endlink,$optjsunique,$tleft,$tright,$mobilebrowser;
	$optshtml=$optionsjs=$defjs=$altidarr=$dependantoptions='';
	$optpricediff=$numdependantoptions=$rowcounter=0;
	$altids=$rs['pId'];
	$hasmulti=FALSE;
	$saveoptionsjs=$optionsjs;
	$saveoptjsunique=$optjsunique;
	$maxindex=count($prodoptions)-1;
	$GLOBALS['hasaltid']=FALSE;
	while($rowcounter<=$maxindex){
		$theopt=$prodoptions[$rowcounter];
		$opthasstock=FALSE;
		$sSQL='SELECT optID,'.getlangid('optName',32).','.getlangid('optGrpName',16).',' . $OWSP . 'optPriceDiff,optType,optGrpSelect,optFlags,optTxtMaxLen,optTxtCharge,optStock,optPriceDiff AS optDims,optDefault,optAltImage,optAltLargeImage,optRegExp,'.getlangid('optPlaceholder',16).','.($theopt['isDepOpt']==1?"'' AS ":'').'optDependants,optTooltip,optClass FROM options LEFT JOIN optiongroup ON options.optGroup=optiongroup.optGrpID WHERE optGroup=' . $theopt['poOptionGroup'] . ' ORDER BY optID';
		$result=ect_query($sSQL) or ect_error();
		if($rs2=ect_fetch_assoc($result)){
			$opttooltip=trim_($rs2['optTooltip']);
			$optplaceholder=trim_($rs2[getlangid('optPlaceholder',16)]);
			if(trim_($rs2['optRegExp'])!='') $rs['pStockByOpts']=1;
			if($opttooltip!=''){
				if(substr($opttooltip,0,2)=='##')
					$opttooltip=substr($opttooltip,2);
				else
					$opttooltip='<div class="opttooltip" '.($mobilebrowser?'onclick="thisstyle=this.getElementsByTagName(\'div\')[0].style;thisstyle.display=thisstyle.display==\'inline\'?\'none\':\'inline\'"':'onmouseover="this.getElementsByTagName(\'div\')[0].style.display=\'inline\'" onmouseout="this.getElementsByTagName(\'div\')[0].style.display=\'none\'"').'><div class="tooltipcontent' . (@$GLOBALS['optionnameaspleaseselect']&&abs((int)$rs2['optType'])!=1?' tooltipright':'') . '">'.$opttooltip.'</div></div>';
			}
			if(abs((int)$rs2['optType'])==5){ // Date Picker
				if(@$GLOBALS['optionnameaspleaseselect']&&$optplaceholder=='') $optplaceholder=$rs2[getlangid('optGrpName',16)];
				$opthasstock=TRUE;
				$optclass=trim_($rs2['optClass']);
				$themask=@$GLOBALS['ectcaldateformat']!=''?$GLOBALS['ectcaldateformat']:'yyyy-mm-dd';
				if(!$GLOBALS['hasincludedpopcalendar']) $GLOBALS['mustincludepopcalendar']=TRUE;
				$optshtml.='<div class="optioncontainer ' . ($isdetail ? 'detail' : 'prod') . 'optioncontainer ectdpoption' . ($optclass!=''?' '.$optclass:'') . '"'.($theopt['isDepOpt']==1?' style="display:none" id="divc'.$Count.'x'.$rowcounter.'"':'').'>';
				if(!@$GLOBALS['optionnameaspleaseselect']) $optshtml.='<div class="optiontext' . ($isdetail ? ' detailoptiontext' : '') . '"><label class="ectlabel" for="optn'.$Count.'x'.$rowcounter.'">' . $rs2[getlangid('optGrpName',16)] . '</label>' . $opttooltip . '</div>';
				$optshtml.='<div class="option' . ($isdetail ? ' detailoption' : '') . '"> <input data-optgroup="'.$theopt['poOptionGroup'].'" '.($theopt['isDepOpt']==1?'data-isdep="1" ':'').'type="hidden" name="optn' . $rowcounter . '" value="' . $rs2['optID'] . '">';
				$optshtml.='<div class="popupcaldiv" style="position:relative;display:inline"><input onclick="ectremoveclass(this,\'ectwarning\');popUpCalendar(this,this,\''.$themask.'\')" data-optgroup="'.$theopt['poOptionGroup'].'" '.($theopt['isDepOpt']==1?'data-isdep="1" ':'').'type="text" class="ecttextinput prodoption'.($isdetail?' detailprodoption':'').'" maxlength="255" name="voptn' . $rowcounter . '" id="optn'.$Count.'x'.$rowcounter.'" size="' . (int)$rs2['optDims'] . '" value="' . htmldisplay($rs2[getlangid('optName',32)]) . '"' . ($optplaceholder!=''?' placeholder="' . $optplaceholder . '"' : '') . ($theopt['isDepOpt']==1?' disabled="disabled"':'').'></div>';
				$optshtml.=(@$GLOBALS['optionnameaspleaseselect']?$opttooltip:'').'</div></div>';
			}elseif(abs((int)$rs2['optType'])==3){ // Text
				if(@$GLOBALS['optionnameaspleaseselect']&&$optplaceholder=='') $optplaceholder=$rs2[getlangid('optGrpName',16)];
				$opthasstock=TRUE;
				$optclass=trim_($rs2['optClass']);
				$fieldHeight=round(((float)($rs2['optDims'])-(int)($rs2['optDims']))*100.0);
				$optshtml.='<div class="optioncontainer ' . ($isdetail ? 'detail' : 'prod') . 'optioncontainer ecttextoption' . ($optclass!=''?' '.$optclass:'') . '"'.($theopt['isDepOpt']==1?' style="display:none" id="divc'.$Count.'x'.$rowcounter.'"':'').'>';
				if(!@$GLOBALS['optionnameaspleaseselect']) $optshtml.='<div class="optiontext' . ($isdetail ? ' detailoptiontext' : '') . '"><label class="ectlabel" for="optn'.$Count.'x'.$rowcounter.'">' . $rs2[getlangid('optGrpName',16)] . '</label>' . $opttooltip . '</div>';
				$optshtml.='<div class="option' . ($isdetail ? ' detailoption' : '') . '"> <input data-optgroup="'.$theopt['poOptionGroup'].'" '.($theopt['isDepOpt']==1?'data-isdep="1" ':'').'type="hidden" name="optn' . $rowcounter . '" value="' . $rs2['optID'] . '">';
				if($fieldHeight!=1){
					$optshtml.='<textarea onkeydown="ectremoveclass(this,\'ectwarning\')" data-optgroup="'.$theopt['poOptionGroup'].'" '.($theopt['isDepOpt']==1?'data-isdep="1" ':'').'class="ecttextinput prodoption'.($isdetail?' detailprodoption':'').'" name="voptn' . $rowcounter . '" id="optn'.$Count.'x'.$rowcounter.'" cols="' . (int)$rs2["optDims"] . '" rows="' . $fieldHeight . '"' . ($optplaceholder!=''?' placeholder="' . $optplaceholder . '"' : '') . ($theopt['isDepOpt']==1?' disabled="disabled"':'') . '>';
					$optshtml.=$rs2[getlangid('optName',32)] . '</textarea>';
				}else
					$optshtml.='<input onkeydown="ectremoveclass(this,\'ectwarning\')" data-optgroup="'.$theopt['poOptionGroup'].'" '.($theopt['isDepOpt']==1?'data-isdep="1" ':'').'type="text" class="ecttextinput prodoption'.($isdetail?' detailprodoption':'').'" maxlength="255" name="voptn' . $rowcounter . '" id="optn'.$Count.'x'.$rowcounter.'" size="' . (int)$rs2['optDims'] . '" value="' . htmldisplay($rs2[getlangid('optName',32)]) . '"' . ($optplaceholder!=''?' placeholder="' . $optplaceholder . '"' : '') . ($theopt['isDepOpt']==1?' disabled="disabled"':'').'>';
				$optshtml.=(@$GLOBALS['optionnameaspleaseselect']?$opttooltip:'').'</div></div>';
			}elseif(abs((int)$rs2['optType'])==1){ // Checkbox / Radio
				$isdependent=$theopt['isDepOpt']==1;
				$optshtml.='<div class="optioncontainer ' . ($isdetail ? 'detail' : 'prod') . 'optioncontainer ectradiooption"'.($isdependent?' style="display:none" id="divc'.$Count.'x'.$rowcounter.'"':'') . '>';
				if(!@$GLOBALS['noradiooptionlabel']) $optshtml.='<div class="optiontext' . ($isdetail ? ' detailoptiontext' : '') . '"><label class="ectlabel" id="optn'.$Count.'x'.$rowcounter.'">' . $rs2[getlangid('optGrpName',16)] . $opttooltip . '</label></div>';
				$optshtml.='<div role="radiogroup" aria-labelledby="optn'.$Count.'x'.$rowcounter.'" class="option' . ($isdetail ? ' detailoption' : '') . '"> ';
				$defjs.='updateoptimage('.$Count.','.$rowcounter.',1);';
				$index=0;
				do {
					$optclass=trim_($rs2['optClass']);
					if(trim_($rs2['optDependants'])!='') $dependantoptions.=','.$rs2['optDependants'];
					$origoptpricediff=getoptpricediff($rs2['optPriceDiff'],$rs['pId'],trim_($rs2['optRegExp']),$rs['pPrice'],$stocknotused);
					addtoaltids($rs2['optRegExp'], $altidarr, $altids);
					$optshtml.='<div class="rcoption' . (($rs2['optFlags'] & 4)==4?' rcoptioninline':'') . ($optclass!=''?' '.$optclass:'') . '"><input type="'.(ect_num_rows($result)==1?'checkbox':'radio').'" data-optgroup="'.$theopt['poOptionGroup'].'" '.($isdependent?'data-isdep="1" ':'').'class="ect'.(ect_num_rows($result)==1?'checkbox':'radio').' prodoption'.($isdetail?' detailprodoption':'').'" onclick="updateoptimage('.$Count.','.$rowcounter.',1)" id="optn'.$Count.'x'.$rowcounter.'z'.$index.'" name="optn'.$Count.'x'.$rowcounter.'" ';
					if((int)$rs2['optDefault']!=0) $optshtml.='checked="checked" ';
					$optshtml.='value="' . $rs2['optID'] . '"><label id="optn'.$Count.'x'.$rowcounter.'y'.$index.'" for="optn'.$Count.'x'.$rowcounter.'z'.$index.'" class="ectlabel';
					if($useStockManagement && $rs['pStockByOpts']!=0 && $rs2['optStock']<=0 && trim_($rs2['optRegExp'])=='') $optshtml.=' oostock'; else $opthasstock=TRUE;
					$optshtml.='">' . $rs2[getlangid('optName',32)];
					if(!$isdependent && @$hideoptpricediffs!=TRUE && $origoptpricediff!=0 && trim_($rs2['optRegExp'])==''){
						$optshtml.=' (';
						if($origoptpricediff>0) $optshtml.='+';
						if(($rs2['optFlags']&1)==1)$pricediff=($rs['pPrice']*$origoptpricediff)/100.0;else$pricediff=$origoptpricediff;
						if(@$showtaxinclusive===2 && ($rs['pExemptions'] & 2)!=2) $pricediff+=($pricediff*$thetax/100.0);
						$optshtml.=FormatEuroCurrency($pricediff) . ')';
						if($rs2['optDefault']!=0) $optpricediff+=$pricediff;
					}
					if($useStockManagement && @$GLOBALS['showinstock'] && @$noshowoptionsinstock!=TRUE && (int)$rs['pStockByOpts']!=0) $optshtml.=strreplace('%s', $rs2['optStock'], $GLOBALS['xxOpSkTx']);
					$optshtml.="</label></div>\n";
					$index++;
					addtooptionsjs($optionsjs, $isdetail, $origoptpricediff);
				} while($rs2=ect_fetch_assoc($result));
				unset($altidarr);
				$optshtml.='</div></div>';
			}elseif(abs((int)$rs2['optType'])==4){ // Multi
				if(@$multipurchasecolumns=='') $multipurchasecolumns=2;
				$colwid=(int)(100/$multipurchasecolumns);
				if((int)$rs2['optGrpSelect']!=0 && ! $isdetail){
					$hasmulti=2;
					$optshtml='';
					$optionsjs='';
					$altids=$rs['pId'];
					$defjs='';
					$optionsjs=$saveoptionsjs;
					$optjsunique=$saveoptjsunique;
					$opthasstock=TRUE;
				}else{
					$optshtml.='<div class="multioptiontable"' . ($theopt['isDepOpt']==1?' style="display:none" id="divc'.$Count.'x'.$rowcounter.'"':'') . '>';
					$index=0;
					do {
						$optclass=trim_($rs2['optClass']);
						$stocklevel=$rs2['optStock'];
						$origoptpricediff=getoptpricediff($rs2['optPriceDiff'],$rs['pId'],trim_($rs2['optRegExp']),$rs['pPrice'],$stocklevel);
						addtoaltids($rs2['optRegExp'], $altidarr, $altids);
						if($useStockManagement && $rs['pStockByOpts']!=0 && $stocklevel<=0 && trim_($rs2['optRegExp'])=='' && $rs['pBackOrder']!=0) $oostock=TRUE; else $oostock=FALSE;
						$optshtml.='<div class="multioptiontext' . ($isdetail ? ' detailmultioptiontext' : '') . ($optclass!=''?' '.$optclass:'') . '">';
						if(trim_($rs2['optAlt'.($isdetail?'Large':'').'Image'])!='') $optshtml.='&nbsp;&nbsp;<img class="multiimage" src="'.trim_($rs2['optAlt'.($isdetail?'Large':'').'Image']).'" alt="">';
						$optshtml.='&nbsp;&nbsp;<input onkeydown="removemultiwarning(this.parentNode.parentNode)" data-optgroup="'.$theopt['poOptionGroup'].'" '.($theopt['isDepOpt']==1?'data-isdep="1" ':'').'type="tel" maxlength="5" name="optm'.$rs2['optID'].'" id="optm'.$Count.'x'.$rowcounter.'y'.$index.'"'.($oostock?' disabled':'').' class="ecttextinput'.($oostock?' oostock':'').'">';
						$optshtml.='<label for="optm'.$Count.'x'.$rowcounter.'y'.$index.'" id="optx'.$Count.'x'.$rowcounter.'y'.$index.'" class="ectlabel multioption';
						if($oostock) $optshtml.=' oostock'; else $opthasstock=TRUE;
						$optshtml.='"> - ' . $rs2[getlangid('optName',32)];
						if(@$hideoptpricediffs!=TRUE && $origoptpricediff!=0){
							$optshtml.=' (';
							if($origoptpricediff > 0) $optshtml.='+';
							if(($rs2['optFlags']&1)==1 && trim_($rs2['optRegExp'])=='')$pricediff=($rs['pPrice']*$origoptpricediff)/100.0;else $pricediff=$origoptpricediff;
							if(@$showtaxinclusive===2 && ($rs['pExemptions'] & 2)!=2) $pricediff+=($pricediff*$thetax/100.0);
							$optshtml.=FormatEuroCurrency($pricediff) . ')';
						}
						$optshtml.='</label></div>';
						$index++;
						addtooptionsjs($optionsjs, $isdetail, $origoptpricediff);
					} while($rs2=ect_fetch_assoc($result));
					$hasmulti=1;
					$optshtml.='</div>';
				}
			}else{ // Select
				$optshtml.='<div class="optioncontainer ' . ($isdetail ? 'detail' : 'prod') . 'optioncontainer ectselectoption"'.($theopt['isDepOpt']==1?' style="display:none" id="divc'.$Count.'x'.$rowcounter.'"':'') . '>';
				if(!@$GLOBALS['noselectoptionlabel'] && !@$GLOBALS['optionnameaspleaseselect']) $optshtml.='<div class="optiontext' . ($isdetail ? ' detailoptiontext' : '') . '"><label class="ectlabel" for="optn'.$Count.'x'.$rowcounter.'">' . $rs2[getlangid('optGrpName',16)] . '</label>' . $opttooltip . '</div>';
				$optshtml.='<div class="option' . ($isdetail ? ' detailoption' : '') . '"><select data-optgroup="'.$theopt['poOptionGroup'].'" '.($theopt['isDepOpt']==1?'data-isdep="1" ':'').'class="prodoption'.($isdetail?' detailprodoption':'').'" onchange="updateoptimage('.$Count.','.$rowcounter.')" name="optn' . $rowcounter . '" id="optn'.$Count.'x'.$rowcounter.'" '.($theopt['isDepOpt']==1?'disabled="disabled" ':'').'size="1">';
				$defjs.="ectById('optn".$Count.'x'.$rowcounter."').onchange();";
				$gotdefaultdiff=FALSE;
				$firstpricediff=0;
				$origoptpricediff=$rs2['optPriceDiff'];
				if((int)$rs2['optGrpSelect']!=0){
					if(@$GLOBALS['optionpleaseselecttemplate']=='') $GLOBALS['optionpleaseselecttemplate']='Please Select: %s...';
					$optshtml.='<option value="">' . (@$GLOBALS['optionnameaspleaseselect']?strreplace('%s',$rs2[getlangid('optGrpName',16)],$GLOBALS['optionpleaseselecttemplate']):$GLOBALS['xxPlsSel']) . '</option>';
				}else
					if(($rs2['optFlags']&1)==1)$firstpricediff=($rs['pPrice']*$origoptpricediff)/100.0;else $firstpricediff=$origoptpricediff;
				do {
					if(trim_($rs2['optDependants'])!='') $dependantoptions.=','.$rs2['optDependants'];
					$origoptpricediff=getoptpricediff($rs2['optPriceDiff'],$rs['pId'],trim_($rs2['optRegExp']),$rs['pPrice'],$stocknotused);
					addtoaltids($rs2['optRegExp'], $altidarr, $altids);
					$optshtml.='<option ';
					$optclass=trim_($rs2['optClass']);
					if($useStockManagement && $rs['pStockByOpts']!=0 && $rs2['optStock'] <= 0 && trim_($rs2['optRegExp'])=='') $optclass=trim_($optclass.' oostock'); else $opthasstock=TRUE;
					if($optclass!='') $optshtml.='class="' . $optclass . '" ';
					$optshtml.='value="' . $rs2['optID'] . '"'.((int)$rs2['optDefault']!=0?' selected="selected"':'').'>' . $rs2[getlangid('optName',32)];
					if(@$hideoptpricediffs!=TRUE && trim_($rs2['optRegExp'])==''){
						if($origoptpricediff!=0){
							$optshtml.=' (';
							if($origoptpricediff>0) $optshtml.='+';
							if(($rs2['optFlags']&1)==1)$pricediff=($rs['pPrice']*$origoptpricediff)/100.0;else $pricediff=$origoptpricediff;
							if(@$showtaxinclusive===2 && ($rs['pExemptions'] & 2)!=2) $pricediff+=($pricediff*$thetax/100.0);
							$optshtml.=FormatEuroCurrency($pricediff) . ')';
							if($rs2['optDefault']!=0)$optpricediff+=$pricediff;
						}
						if($rs2['optDefault']!=0)$gotdefaultdiff=TRUE;
					}
					if($useStockManagement && @$GLOBALS['showinstock'] && @$noshowoptionsinstock!=TRUE && (int)$rs['pStockByOpts']!=0) $optshtml.=strreplace('%s', $rs2['optStock'], $GLOBALS['xxOpSkTx']);
					$optshtml.="</option>\n";
					addtooptionsjs($optionsjs, $isdetail, $origoptpricediff);
				} while($rs2=ect_fetch_assoc($result));
				unset($altidarr);
				if(@$hideoptpricediffs!=TRUE && ! $gotdefaultdiff) $optpricediff+=$firstpricediff;
				$optshtml.='</select>' . ((@$GLOBALS['noselectoptionlabel'] || @$GLOBALS['optionnameaspleaseselect']) && $opttooltip!=''?$opttooltip:'') . '</div>';
				$optshtml.='</div>';
			}
		}
		ect_free_result($result);
		$optionshavestock=$optionshavestock && ($opthasstock||$theopt['isDepOpt']==1);
		$dependantoptions=commaseplist($dependantoptions);
		if($hasmulti==2) break;
		if($dependantoptions!=''){
			$sSQL="SELECT optGrpID AS poOptionGroup,optType,optFlags,optTxtMaxLen,optAcceptChars,1 AS isDepOpt FROM optiongroup WHERE optGrpID IN (".$dependantoptions.") ORDER BY FIND_IN_SET(optGrpID,'".$dependantoptions."')";
			$result2=ect_query($sSQL) or ect_error();
			if(($numsuboptions=ect_num_rows($result2))>0){
				$itemstomove=$maxindex-$rowcounter;
				$maxindex+=$numsuboptions;
				for($soindex=0;$soindex<$itemstomove;$soindex++){
					$moveto=$maxindex-$soindex;
					$movefrom=$rowcounter+$itemstomove-$soindex;
					$prodoptions[$moveto]=$prodoptions[$movefrom];
				}
				for($soindex=1;$soindex<=$numsuboptions;$soindex++){
					$rs2=ect_fetch_assoc($result2);
					$prodoptions[$rowcounter+$soindex]=$rs2;
				}
			}
			ect_free_result($result2);
			$dependantoptions='';
		}
		$rowcounter++;
	}
	$oneoptionhasstock=FALSE;
	$sSQL='SELECT pID,'.$WSP."pPrice,pListPrice,pInStock FROM products WHERE pID IN ('".strreplace(' ', "','", $altids)."')";
	$result=ect_query($sSQL) or ect_error();
	while($rs2=ect_fetch_assoc($result)){
		$sSQL="SELECT imageSrc FROM productimages WHERE imageProduct='".escape_string($rs2['pID'])."' AND imageNumber=0 AND imageType=".($isdetail?'1':'0').' LIMIT 0,1';
		$result3=ect_query($sSQL) or ect_error();
		if($rs3=ect_fetch_assoc($result3)) $pi=encodeimage($rs3['imageSrc']); else $pi='';
		ect_free_result($result3);
		if($pi!=''){
			$sSQL="SELECT imageSrc FROM productimages WHERE imageProduct='".escape_string($rs2['pID'])."' AND imageNumber=0 AND imageType=".($isdetail?'2':'1').' LIMIT 0,1';
			$result3=ect_query($sSQL) or ect_error();
			if($rs3=ect_fetch_assoc($result3)) $pi.='*'.encodeimage($rs3['imageSrc']);
			ect_free_result($result3);
		}
		$optionsjs.="sz('".$rs2['pID']."',".$rs2['pPrice'].",".$rs2['pListPrice'].",'".jsescapel($pi)."'";
		if($useStockManagement){
			$optionsjs.=','.($rs['pId']==$rs2['pID']&&$rs['pStockByOpts']?0:$rs2['pInStock']);
			if($rs['pId']!=$rs2['pID']&&$rs2['pInStock']>0&&$GLOBALS['hasaltid'])$oneoptionhasstock=TRUE;
		}
		$optionsjs.=");\n";
	}
	ect_free_result($result);
	if($GLOBALS['hasaltid']&&!$oneoptionhasstock) $optionshavestock=FALSE;
	if($hasmulti!=2) $defimagejs.='updateprice'.$Count.'();'.$defjs;
	if(count($prodoptions)>0){
		$optionsjs.='function setvals'.$Count."(){\n";
		foreach($prodoptions as $rowcounter => $theopt){
			$optionsjs.='optacpc[' . $rowcounter . "]='" . jsescape($theopt['optAcceptChars']) . "';optmaxc[" . $rowcounter . ']=' . $theopt['optTxtMaxLen'] . ';opttype['.$rowcounter.']=' . (int)$theopt['optType'] . ';optperc['.$rowcounter.']=' . (($theopt['optFlags'] & 1)==1 ? 'true' : 'false') . ";\n";
		}
		$optionsjs.="}\n";
		$optionsjs.='function updateprice'.$Count."(){\n";
		$optionsjs.='setvals'.$Count.'();';
		$optionsjs.='dependantopts('.$Count.');';
		$optionsjs.='updateprice('.count($prodoptions).','.$Count.','.$rs['pPrice'].','.$rs['pListPrice'].",'".$rs['pId']."',".$thetax.','.($useStockManagement && $rs['pStockByOpts']!=0 ? 'true' : 'false').','.(($rs['pExemptions'] & 2)==2 ? 'true' : 'false').','.($rs['pBackOrder']!=0 ? 'true' : 'false').');';
		$optionsjs.="}\n";
	}
	return($optshtml);
}
function displayformvalidator(){
	global $optjs,$Count,$prodoptions,$useStockManagement,$rs;
	$optjs.='function formvalidator'.$Count."(theForm){\n" .
				"var fvsuccess=true;\n";
	if(count($prodoptions)>0){
		$optjs.='setvals'.$Count.'();';
		$optjs.='fvsuccess=ectvalidate(theForm,'.count($prodoptions).','.$Count.','.($useStockManagement && $rs['pStockByOpts']!=0 ? 'true' : 'false').','.($rs['pBackOrder']!=0 ? 'true' : 'false').');';
	}
	if(@$GLOBALS['googletagid']!=''){
		$optjs.='if(fvsuccess) gtag("event","add_to_cart",{ currency:"' . $GLOBALS['countryCurrency'] . '",value:' . $rs['pPrice'] . ",items:[{item_id:'" . jsescapel($rs['pId']) . "'," .
			"item_name:'" . jsescapel($rs[getlangid('pName',1)]) . "',index:" . $Count . ',';
		if($GLOBALS['wantmanufacturer'])
			if(trim_($rs[getlangid('scName',131072)])!='') $optjs.="item_brand:'" . jsescapel($rs[getlangid('scName',131072)]) . "',";
		if(@$GLOBALS['catname']!='') $optjs.="item_category:'" . jsescapel($GLOBALS['catname']) . "',";
		$optjs.='price:' . jsescapel($rs['pPrice']) . ",quantity:1}]});\n";
	}
	$optjs.="return(fvsuccess);}\n";
}
function CalcHmacSha1($data, $key){
	$blocksize=64;
	$hashfunc='sha1';
	if (strlen($key) > $blocksize){
		$key=pack('H*', $hashfunc($key));
	}
	$key=str_pad($key, $blocksize, chr(0x00));
	$ipad=str_repeat(chr(0x36), $blocksize);
	$opad=str_repeat(chr(0x5c), $blocksize);
	$hmac=pack('H*', $hashfunc(($key^$opad).pack('H*', $hashfunc(($key^$ipad).$data))));
	return $hmac;
}
function encodeemailsubject($in_str, $charset){
	$out_str=$in_str;
	if($out_str && $charset){
		// define start delimimter, end delimiter and spacer
		$end="?=";
		$start="=?" . $charset . "?B?";
		$spacer=$end . "\r\n " . $start;
		// determine length of encoded text within chunks and ensure length is even
		$length=75 - strlen($start) - strlen($end);
		$length=floor($length/2) * 2;
		// encode the string and split it into chunks with spacers after each chunk
		$out_str=base64_encode($out_str);
		$out_str=chunk_split($out_str, $length, $spacer);
		// remove trailing spacer and add start and end delimiters
		$spacer=preg_quote($spacer);
		$out_str=preg_replace("/" . $spacer . "$/", "", $out_str);
		$out_str=$start . $out_str . $end;
	}
	return $out_str;
}
if(@$GLOBALS['enableclientlogin']){
	if(@$_SESSION['clientID']!=''){
	}elseif(@$_POST['checktmplogin']!='' && @$_POST['sessionid']!=''){
		$sSQL="SELECT tmploginname FROM tmplogin WHERE tmploginid='" . escape_string(@$_POST['sessionid']) . "' AND tmploginchk='" . escape_string(@$_POST['checktmplogin']) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			$_SESSION['clientID']=$rs['tmploginname'];
			ect_free_result($result);
			$sSQL="SELECT clUserName,clPW,clActions,clLoginLevel,clPercentDiscount,avalaraentityuse FROM customerlogin WHERE clID='" . escape_string($_SESSION['clientID']) . "'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				$_SESSION['clientPW']=$rs['clPW'];
				$_SESSION['clientUser']=$rs['clUserName'];
				$_SESSION['clientActions']=$rs['clActions'];
				$_SESSION['clientLoginLevel']=$rs['clLoginLevel'];
				$_SESSION['clientPercentDiscount']=(100.0-(float)$rs['clPercentDiscount'])/100.0;
				$_SESSION['avalaraentityuse']=$rs['avalaraentityuse'];
			}
		}
		ect_free_result($result);
	}elseif(@$_COOKIE['WRITECLL']!=''){
		$clientEmail=strreplace("'",'',@$_COOKIE['WRITECLL']);
		$clientPW=strreplace("'",'',@$_COOKIE['WRITECLP']);
		$sSQL="SELECT clID,clUserName,clActions,clLoginLevel,clPercentDiscount,avalaraentityuse FROM customerlogin WHERE (clEmail<>'' AND clEmail='" . escape_string($clientEmail) . "' AND clPW='" . escape_string($clientPW) . "') OR (clEmail='' AND clUserName='" . escape_string($clientEmail) . "' AND clPW='" . escape_string($clientPW) . "')";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			$_SESSION['clientID']=$rs['clID'];
			$_SESSION['clientUser']=$rs['clUserName'];
			$_SESSION['clientActions']=$rs['clActions'];
			$_SESSION['clientLoginLevel']=$rs['clLoginLevel'];
			$_SESSION['clientPercentDiscount']=(100.0-(float)$rs['clPercentDiscount'])/100.0;
			$_SESSION['avalaraentityuse']=$rs['avalaraentityuse'];
		}
		ect_free_result($result);
	}
	if(@$requiredloginlevel!=''){
		if((int)$requiredloginlevel > @$_SESSION['clientLoginLevel']){
			ob_end_clean();
			if(@$_SERVER['HTTPS']=='on' || @$_SERVER['SERVER_PORT']=='443')$prot='https://';else $prot='http://';
			$_SESSION['clientloginref']=@$_SERVER['PHP_SELF'].(@$_SERVER['QUERY_STRING']!=''?'?'.@$_SERVER['QUERY_STRING']:'');
			header('Location: '.$GLOBALS['customeraccounturl']);
			exit;
		}
	}
	if((@$_SESSION['clientActions'] & 2)==2) $GLOBALS['showtaxinclusive']=0;
}
function getsessionsql(){
	global $thesessionid;
	return(@$_SESSION['clientID']!='' ? 'cartClientID=' . escape_string($_SESSION['clientID']) : "cartSessionID='" . escape_string($thesessionid) . "'");
}
function getordersessionsql(){
	global $thesessionid;
	return("ordDate>'" . date('Y-m-d', time()-(3*60*60*24)) . "' AND ".(@$_SESSION['clientID']!='' ? 'ordClientID=' . escape_string($_SESSION['clientID']) : "ordSessionID='" . escape_string($thesessionid) . "'"));
}
function htmldisplay($thestr){
	return(strreplace(array('>','<','"'), array('&gt;','&lt;','&quot;'), $thestr));
}
function htmlspecials($thestr){
	return(strreplace(array('&','>','<','"'), array('&amp;','&gt;','&lt;','&quot;'), $thestr));
}
function htmlspecialsid($thestr){
	return(strreplace(array('&','>','<','"',"'"), '', $thestr));
}
function htmlspecialsucode($thestr){
	//return(strreplace(array('&','>','<','"','&amp;#','&#47;','&#92;','&#45;'), array('&amp;','&gt;','&lt;','&quot;','&#','&amp;#47;','&amp;#92;','&amp;#45;'), $thestr));
	return htmlspecialchars(is_null($thestr)?'':$thestr);
}
function jsspecials($thestr){
	return(strreplace(array('\\','\'',"\r","\n"),array('\\\\','\\\'','','\\n'), htmldisplay($thestr)));
}
function jsescape($thestr){
	return(strreplace(array('\\','\'','<'),array('\\\\','\\\'',''), $thestr));
}
function jsescapel($thestr){
	return(strreplace(array('\\','\'',"\r","\n"),array('\\\\','\\\'','','\\n'), $thestr));
}
function addtomailinglist($theemail,$thename){
	global $storeurl,$emailAddr,$noconfirmationemail,$htmlemails,$uspsUser,$upsUser,$origZip,$checksumtext,$warncheckspamfolder,$errormsg,$adminSecret;
	$isspam=FALSE;
	$theemail=trim_(strtolower(strip_tags(strreplace('"','',$theemail))));
	if(strpos($theemail, '@')!==FALSE && strpos($theemail, '.')!==FALSE && strlen($theemail)>5){
		if(@$GLOBALS['mailchimpapikey']!=''&&@$GLOBALS['mailchimplist']!=''){
			splitname($thename,$firstname,$lastname);
			$json_data='{"email_address":' . json_encode($theemail);
			$json_data.=', "ip_signup":' . json_encode(getipaddress());
			$json_data.=', "status": "pending","merge_fields":{"FNAME":' . json_encode($firstname) .',"LNAME":' . json_encode($lastname);

			$hasaddress=FALSE;
			$sSQL="SELECT clID,addAddress,addAddress2,addCity,addState,addZip,addCountry FROM customerlogin INNER JOIN address ON clID=addCustID WHERE clEmail='" . escape_string($theemail) . "' ORDER BY addIsDefault DESC LIMIT 0,1";
			$result2=ect_query($sSQL) or ect_error();
			if($rs2=ect_fetch_assoc($result2)){
				$hasaddress=TRUE;
				$addAddress=$rs2['addAddress'];
				$addAddress2=$rs2['addAddress2'];
				$addCity=$rs2['addCity'];
				$addState=$rs2['addState'];
				$addZip=$rs2['addZip'];
				$addCountry=$rs2['addCountry'];
			}
			if(!$hasaddress){
				$sSQL="SELECT ordID,ordAddress,ordAddress2,ordCity,ordState,ordZip,ordCountry FROM orders WHERE ordEmail='" . escape_string($theemail) . "' ORDER BY ordID DESC LIMIT 0,1";
				$result2=ect_query($sSQL) or ect_error();
				if($rs2=ect_fetch_assoc($result2)){
					$hasaddress=TRUE;
					$addAddress=$rs2['ordAddress'];
					$addAddress2=$rs2['ordAddress2'];
					$addCity=$rs2['ordCity'];
					$addState=$rs2['ordState'];
					$addZip=$rs2['ordZip'];
					$addCountry=$rs2['ordCountry'];
				}
			}
			if($hasaddress)
				$json_data.=',"ADDRESS":{"addr1":' . json_encode($addAddress) . ',"addr2":' . json_encode($addAddress2) . ',"city":' . json_encode($addCity) . 
					',"state":' . json_encode($addState) . ',"zip":' . json_encode($addZip) . ',"country":' . json_encode($addCountry) . '}';

			$json_data.='}}';
			$GLOBALS['xmlfnuser']='anystr'; $GLOBALS['xmlfnpassword']=@$GLOBALS['mailchimpapikey'];
			$mcpwarray=explode('-',$GLOBALS['xmlfnpassword']);
			$xmlfnheaders=array('Content-Type: application/json');
			callcurlfunction('https://'.$mcpwarray[1].'.api.mailchimp.com/3.0/lists/'.$GLOBALS['mailchimplist'].'/members',$json_data,$res,'',$errormsg,FALSE);
		}else{
			$confirmdate=date('Y-m-d', time()-(60*60*24));
			$sSQL="SELECT email,isconfirmed,mlConfirmDate FROM mailinglist WHERE email='" . escape_string($theemail) . "'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				$confirmdate=$rs['mlConfirmDate'];
				$emailexists=TRUE;
				$isconfirmed=$rs['isconfirmed'];
			}else
				$emailexists=$isconfirmed=FALSE;
			ect_free_result($result);
			$emailarr=explode('@',$theemail);
			if(is_numeric($emailarr[0])) $isspam=TRUE;
			if(! $emailexists && ! $isspam){
				$sSQL="SELECT COUNT(*) AS thecnt FROM mailinglist WHERE mlConfirmDate='".date('Y-m-d', time())."' AND mlIPAddress='".escape_string(getipaddress())."'";
				$result=ect_query($sSQL) or ect_error();
				if($rs=ect_fetch_assoc($result)) $thecnt=$rs['thecnt']; else $thecnt=0;
				ect_free_result($result);
				if($thecnt<3) ect_query("INSERT INTO mailinglist (email,mlName,isconfirmed,mlConfirmDate,mlIPAddress) VALUES ('" . escape_string($theemail) . "','" . escape_string($thename) . "'," . (@$noconfirmationemail?1:0) . ",'".date('Y-m-d', time())."','".escape_string(getipaddress())."')"); else $isspam=TRUE;
			}
			if(! $isconfirmed && ! @$noconfirmationemail && ! $isspam){
				$warncheckspamfolder=TRUE;
				if($confirmdate!=date('Y-m-d', time())){
					ect_query("UPDATE mailinglist SET mlConfirmDate='".date('Y-m-d', time())."' WHERE email='" . escape_string($theemail) . "'") or ect_error();
					if(@$htmlemails) $emlNl='<br>'; else $emlNl="\r\n";
					$thelink=$storeurl . 'cart' . $GLOBALS['extension'] . '?emailconf='.urlencode($theemail).'&check='.substr(md5($origZip.':'.$checksumtext.':'.$theemail.':'.$adminSecret), 0, 12);
					if(@$htmlemails) $thelink='<a href="' . $thelink . '">' . $thelink . '</a>';
					dosendemail($theemail, $emailAddr, '',@$GLOBALS['xxEMConf']!=''?$GLOBALS['xxEMConf']:$GLOBALS['xxMLConf'], $GLOBALS['xxConfEm'] . $emlNl . $emlNl . $thelink);
				}
			}
		}
	}
}
function getipaddress(){
	$tip='';
	if(trim_(@$_SERVER['HTTP_X_FORWARDED_FOR'])!=''){
		$ip=explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
		$tip=trim_($ip[0]);
	}else
		$tip=@$_SERVER['REMOTE_ADDR'];	
	if(strlen($tip)>100) $tip='unknown';
	return($tip);
}
function escape_string($estr){
	return(@$GLOBALS['ectdatabase']?$GLOBALS['ectdatabase']->real_escape_string(is_null($estr) ? '' : trim($estr)):mysql_real_escape_string($estr));
}
function rethuni($tnum){
	return('\\u'.str_pad(dechex($tnum[1]),4,'0',STR_PAD_LEFT));
}
function jscheck($thetxt){
	if(is_null($thetxt))$thetxt='';
	return strreplace('"','\\"',preg_replace_callback('/&#(\d+);/m','rethuni',$thetxt));
}
function imageorlink($theimg,$thetext,$theclass,$thelink,$isjs){
	$isabsolute=strpos($thelink,'http://')!==FALSE||strpos($thelink,'https://')!==FALSE;
	if($theimg=='button')
		return '<input type="button" value="'.$thetext.'" class="'.trim_('ectbutton '.$theclass).'" onclick="'.($isjs ? '' : "ectgo" . ($isabsolute?'':"no") . "abs('") . $thelink . ($isjs ? '' : "')").'">';
	elseif($theimg!='')
		return '<img style="cursor:pointer" src="'.$theimg.'" '.($theclass!=''?'class="'.$theclass.'" ':'').'onclick="'.($isjs ? '' : "ectgo" . ($isabsolute?'':"no") . "abs('") . $thelink . ($isjs ? '' : "')").'" alt="'.$thetext.'">';
	else
		return '<a class="ectlink'.($theclass!=''?' '.$theclass:'').'" href="'.($isjs ? '#" onclick="' : '') . $thelink . '">'.$thetext.'</a>';
}
function imageorbuttontag($theimg,$thetext,$theclass,$thelink,$isjs,$newtab=FALSE,$extraparams=''){
	$isabsolute=strpos($thelink,'http://')!==FALSE||strpos($thelink,'https://')!==FALSE;
	$arialabel=(@$GLOBALS['aria']!=''?' aria-label="' . htmlspecials($GLOBALS['aria']) . '"':'');
	$GLOBALS['aria']='';
	if($theimg=='link')
		return '<a class="ectlink'.($theclass!=''?' '.$theclass:'').'" href="'.($isjs ? '#" onclick="return ' : '') . $thelink . '"'.$arialabel.'>'.$thetext.'</a>';
	elseif($theimg!='' && $theimg!='button')
		return '<img style="cursor:pointer" src="'.$theimg.'" '.($theclass!=''?'class="'.$theclass.'" ':'').'onclick="'.($isjs ? '' : "ectgo" . ($isabsolute?'':"no") . "abs('") . $thelink . ($isjs ? '' : "')").'" alt="'.$thetext.'"'.$arialabel.'>';
	else
		return '<button type="button" class="'.trim_('ectbutton '.$theclass).'" onclick="'.($isjs ? '' : "ectgo" . ($newtab?'newtab':($isabsolute?'':"no")) . "abs('") . $thelink . ($isjs ? '' : "')").'"'.$arialabel.($extraparams!=''?' '.$extraparams:'').'>'.$thetext.'</button>';
}
function imageorbutton($theimg,$thetext,$theclass,$thelink,$isjs){
	$isabsolute=strpos($thelink,'http://')!==FALSE||strpos($thelink,'https://')!==FALSE;
	$arialabel=(@$GLOBALS['aria']!=''?' aria-label="' . htmlspecials($GLOBALS['aria']) . '"':'');
	$GLOBALS['aria']='';
	if($theimg=='link')
		return '<a class="ectlink'.($theclass!=''?' '.$theclass:'').'" href="'.($isjs ? '#" onclick="return ' : '') . $thelink . '"'.$arialabel.'>'.$thetext.'</a>';
	elseif($theimg!='' && $theimg!='button')
		return '<img style="cursor:pointer" src="'.$theimg.'" '.($theclass!=''?'class="'.$theclass.'" ':'').'onclick="'.($isjs ? '' : "ectgo" . ($isabsolute?'':"no") . "abs('") . $thelink . ($isjs ? '' : "')").'" alt="'.$thetext.'"'.$arialabel.'>';
	else
		return '<input type="button" value="'.$thetext.'" class="'.trim_('ectbutton '.$theclass).'" onclick="'.($isjs ? '' : "ectgo" . ($isabsolute?'':"no") . "abs('") . $thelink . ($isjs ? '' : "')").'"'.$arialabel.'>';
}
function imageorsubmittag($theimg,$thetext,$theclass,$extraparams=''){
	$arialabel=(@$GLOBALS['aria']!=''?' aria-label="' . htmlspecials($GLOBALS['aria']) . '"':'');
	$GLOBALS['aria']='';
	if($theimg!='' && $theimg!='button')
		return '<input type="image" src="'.$theimg.'" alt="'.$thetext.'" '.($theclass!=''?'class="'.$theclass.'" ':'').'>';
	else
		return '<button type="submit" class="'.trim_('ectbutton '.$theclass).'"'.$arialabel.($extraparams!=''?' '.$extraparams:'').'>'.$thetext.'</button>';
}
function imageorsubmit($theimg,$thetext,$theclass){
	if($theimg!='' && $theimg!='button')
		return '<input type="image" src="'.$theimg.'" alt="'.$thetext.'" '.($theclass!=''?'class="'.$theclass.'" ':'').'>';
	else
		return '<input type="submit" value="'.$thetext.'" class="'.trim_('ectbutton '.$theclass).'">';
}
function stripos_array($haystack, $needles){
	foreach($needles as $needle) {
		if(stripos($haystack, $needle)!==FALSE) return TRUE;
	}
	return FALSE;
}
function dosendemail($doseto, $dosefrom, $dosereplyto, $dosesubject, $dosebody){
	global $doencodeemailsubject,$customheaders,$emailencoding,$htmlemails,$debugmode,$usemailer,$smtphost,$smtpusername,$smtppassword,$smtpport,$smtpsecure,$emailflags,$emailcr,$emailfromname,$sendemailerrnum,$sendemailerrdesc;
	$sSQL='SELECT emailfromname,usemailer,smtpserver,emailUser,emailPass,smtpport,smtpsecure FROM admin WHERE adminID=1';
	$result=ect_query($sSQL) or ect_error();
	$rs=ect_fetch_assoc($result);
	$GLOBALS['emailfromname']=$rs['emailfromname'];
	if(@$GLOBALS['oremailfromname']!='')$GLOBALS['emailfromname']=$GLOBALS['oremailfromname'];
	$GLOBALS['usemailer']=$rs['usemailer'];
	$GLOBALS['smtphost']=$rs['smtpserver'];
	$GLOBALS['smtpusername']=$rs['emailUser'];
	$GLOBALS['smtppassword']=$rs['emailPass'];
	$GLOBALS['smtpport']=$rs['smtpport'];
	$GLOBALS['smtpsecure']=$rs['smtpsecure'];
	ect_free_result($result);
	if(@$GLOBALS['isectstore']){
		if($GLOBALS['usemailer']!='none'&&($GLOBALS['usemailer']==''||(@$GLOBALS['smtpusername']==''&&@$GLOBALS['smtppassword']==''))){
			$GLOBALS['usemailer']='phpmailer';
			$GLOBALS['smtphost']=$GLOBALS['defaultsmtpserver'];
			$GLOBALS['smtpusername']=@$GLOBALS['defaultsmtpusername'];
			$GLOBALS['smtppassword']=@$GLOBALS['defaultsmtppassword'];
			$GLOBALS['smtpport']=$GLOBALS['defaultsmtpport'];
			$GLOBALS['smtpsecure']=$GLOBALS['defaultsmtpsecure'];
		}
	}
	$sendemailerrnum=0;
	$sendemailerrdesc='';
	$issiteroot=FALSE;
	if(@$doencodeemailsubject) $dosesubject='=?'.$emailencoding.'?B?'.base64_encode($dosesubject).'?=';
	if(@$GLOBALS['ectdemostore']||@$usemailer=='none'){
	}elseif(@$usemailer=='phpmailer'){
		if(!class_exists('phpmailerException')&&!@$GLOBALS['usewordpressphpmailer']){
			if(file_exists('./vsadmin/inc/PHPMailer.php')) $issiteroot=TRUE;
			if($issiteroot){
				include_once('./vsadmin/inc/PHPMailer.php');
				@include_once('./vsadmin/inc/SMTP.php');
				include_once('./vsadmin/inc/Exception.php');
			}else{
				include_once('./inc/PHPMailer.php');
				@include_once('./inc/SMTP.php');
				include_once('./inc/Exception.php');
			}
		}
		$mail=new PHPMailer\PHPMailer\PHPMailer;
		if($issiteroot) $mail->SetLanguage('en', './vsadmin/inc/'); else $mail->SetLanguage('en', './inc/');
		$mail->CharSet=$emailencoding;
		$mail->IsSMTP();
		if(@$debugmode) $mail->SMTPDebug=2;
		$mail->Host=$smtphost;
		$mail->SMTPAuth=(@$smtpusername!='' && @$smtppassword!='');
		if(@$smtpusername!='' && @$smtppassword!=''){
			$mail->Username=$smtpusername;
			$mail->Password=$smtppassword;
		}
		if(@$smtpport!='') $mail->Port=$smtpport;
		if(@$smtpsecure!='') $mail->SMTPSecure=$smtpsecure;
		$senders=explode(',',trim_($dosefrom));
		$mail->From=trim_($senders[0]);
		if(@$emailfromname!='')$mail->FromName=$emailfromname;
		$recipients=explode(',',trim_($doseto));
		foreach($recipients as $recipemail){
			$mail->AddAddress(trim_($recipemail));
		}
		if($dosereplyto!='') $mail->AddReplyTo($dosereplyto);
		// $mail->WordWrap=50;
		$mail->IsHTML(@$htmlemails);
		$mail->Subject=$dosesubject;
		$mail->Body=$dosebody;
		// $mail->AltBody="Plain Text";
		if(!$mail->Send()){
			$sendemailerrdesc=$mail->ErrorInfo;
			if(@$debugmode) echo 'Failed to send mail: ' . $sendemailerrdesc;
			$sendemailerrnum=1;
		}
	}else{
		if(@$customheaders==''){
			$headers='MIME-Version: 1.0'.$emailcr;
			if(@$emailfromname!='') $headers.='From: %fromname% <%from%>'.$emailcr; else $headers.='From: %from%'.$emailcr;
			if($dosereplyto!='') $headers.='Reply-To: %replyto%'.$emailcr;
			if(@$htmlemails)
				$headers.='Content-type: text/html; charset='.$emailencoding.$emailcr;
			else
				$headers.='Content-type: text/plain; charset='.$emailencoding.$emailcr;
		}else{
			$headers=$customheaders;
			if($dosereplyto==''){
				if(($startpos=strpos(strtolower($headers), 'reply-to'))!==FALSE){
					if(($endpos=strpos($headers,"\n",$startpos+1))!==FALSE){
						$headers=substr_replace($headers,'',$startpos,($endpos-$startpos)+1);
					}
				}
			}
		}
		$senders=explode(',',trim_($dosefrom));
		$headers=strreplace('%from%',$senders[0],$headers);
		$headers=strreplace('%fromname%',@$emailfromname,$headers);
		$headers=strreplace('%to%',$doseto,$headers);
		$headers=strreplace('%replyto%',$dosereplyto,$headers);
		$emailflags=strreplace('%from%',$senders[0],@$emailflags);
		if($emailflags!=''){
			if(@$debugmode==TRUE)
				$sendemailerrnum=(mail($doseto, $dosesubject, $dosebody, $headers, $emailflags)?0:1);
			else
				$sendemailerrnum=(@mail($doseto, $dosesubject, $dosebody, $headers, $emailflags)?0:1);
		}else{
			if(@$debugmode==TRUE)
				$sendemailerrnum=(mail($doseto, $dosesubject, $dosebody, $headers)?0:1);
			else
				$sendemailerrnum=(@mail($doseto, $dosesubject, $dosebody, $headers)?0:1);
		}
	}
}
function getgcchar(){
	$tc='';
	while($tc=='' || $tc=='O' || $tc=='I' || $tc=='Q')
		$tc=chr(rand(65, 90));
	return($tc);
}
function getrndchar(){
	return(chr(rand(65, 90)));
}
function replaceemailtxt($thestr, $txtsearch, $txtreplace, &$didreplace){
	$inbrackets=FALSE;
	$countinscope=1;
	if($thestr=='') $i=FALSE; else $i=strpos($thestr, $txtsearch);
	$didreplace=($i!==FALSE);
	if($i!==FALSE){
		$t1=$i;
		$bcount=0;
		while($t1>=0 && ($bcount!=0 || $thestr[$t1]!='{')){
			if($thestr[$t1]=='{') $bcount++;
			if($thestr[$t1]=='}') $bcount--;
			$t1--;
		}
		if($t1<0) $t1=FALSE;
		
		$t4=$i;
		$bcount=0;
		while($t4<strlen($thestr) && ($bcount!=0 || $thestr[$t4]!='}')){
			if($thestr[$t4]=='{') $bcount++;
			if($thestr[$t4]=='}') $bcount--;
			$t4++;
		}
		if($t4>=strlen($thestr)) $t4=FALSE;
		$inbrackets=($t1!==FALSE && $t4!==FALSE);
	}
	if($i===FALSE){
		return($thestr);
	}elseif($txtreplace==''){ // want to replace all of txtsearch OR {...txtsearch...}
		if($inbrackets) return(substr($thestr, 0, $t1) . substr($thestr, $t4+1)); else return(strreplace($txtsearch, '', $thestr));
	}else{ // Want to remove the { AND }
		if($txtreplace=='%ectpreserve%') $txtreplace='';
		if($inbrackets) $thestr=substr($thestr, 0, $t1) . substr($thestr, $t1+1, ($t4-$t1)-1) . substr($thestr, $t4+1);
		if(($txtsearch=='%trackingnum%' && $inbrackets) || substr($txtsearch,0,9)=='%statusid'){
			if($txtsearch=='%trackingnum%')
				$countinscope=substr_count(substr($thestr, $t1+1, ($t4-$t1)-1), '%trackingnum%');
			return(preg_replace('/'.$txtsearch.'/', $txtreplace, $thestr, $countinscope));
		}else
			return(strreplace($txtsearch, $txtreplace, $thestr));
	}
}
function showproductreviews($disptype, $classname){
	global $rs,$thedetailslink;
	$therating=(int)($rs['pTotRating']/$rs['pNumRatings']);
	$spr='<div class="smallreviewstars '.$classname.'" aria-label="Rating ' . round($therating/2,1) . ' out of 5 stars"><a href="'.$thedetailslink.'#reviews" aria-label="All reviews">';
	if(@$GLOBALS['imgreviewcart']=='') displayreviewicons();
	for($index=1; $index <= (int)($therating / 2); $index++){
		if(@$GLOBALS['imgreviewcart']!='')
			$spr.='<img class="'.$classname.'" src="images/s'.$GLOBALS['imgreviewcart'].'" alt="">';
		else
			$spr.='<svg viewBox="0 0 24 24" class="icon" style="max-width:30px"><use xlink:href="#review-icon-full"></use></svg>';
	}
	$ratingover=$therating;
	if($ratingover / 2 > (int)($ratingover / 2)){
		if(@$GLOBALS['imgreviewcart']!='')
			$spr.='<img class="'.$classname.'" src="images/s'.strreplace('.','hg.',$GLOBALS['imgreviewcart']).'" alt="">';
		else
			$spr.='<svg viewBox="0 0 24 24" class="icon" style="max-width:30px"><use xlink:href="#review-icon-half"></use></svg>';
		$ratingover++;
	}
	for($index=(int)($ratingover / 2) + 1; $index <= 5; $index++){
		if(@$GLOBALS['imgreviewcart']!='')
			$spr.='<img class="'.$classname.'" src="images/s'.strreplace('.','g.',$GLOBALS['imgreviewcart']).'" alt="">';
		else
			$spr.='<svg viewBox="0 0 24 24" class="icon" style="max-width:30px"><use xlink:href="#review-icon-empty"></use></svg>';
	}
	$spr.='</a><div class="' . $classname . 'text">';
	if($disptype==2) $spr.=($GLOBALS['xxBasRat']!=''?' <a class="ectlink prodratinglink" href="'.$thedetailslink.'#reviews">' . strreplace('%s', $rs['pNumRatings'], $GLOBALS['xxBasRat']) . '</a>':''); elseif($disptype==1) $spr.=($GLOBALS['xxBasRat']!=''?' ' . strreplace('%s', $rs['pNumRatings'], $GLOBALS['xxBasRat']):'') . ($GLOBALS['xxView']!=''?' (<a class="ectlink prodratinglink" href="' . $thedetailslink . '#reviews">' . $GLOBALS['xxView'] . '</a>)':'');
	return($spr . '</div></div>');
}
function splitfirstlastname($thename,&$firstfull,&$lastname){
	if(@$GLOBALS['usefirstlastname']&&strpos($thename, ' ')!==FALSE){
		$namearr=explode(' ',$thename,2);
		$firstfull=$namearr[0];
		$lastname=$namearr[1];
	}else{
		$firstfull=$thename;
		$lastname='';
	}
}
function getcatid($sid,$snam,$seopattern){
	global $usecategoryname,$seocategoryurls,$detlinkspacechar;
	if(@$seocategoryurls) return(strpos($snam,'://')!==FALSE ? $snam : strreplace('%s',rawurlencode(strreplace(' ',$detlinkspacechar,$snam)),$seopattern));
	if(@$usecategoryname && $snam!='') return(urlencode($snam)); else return($sid);
}
function cleanupemail($theemail){
	$tmpstr='';$gotat=FALSE;
	if(strlen($theemail)<60){
		$theemail=strreplace(array('"',' ',"'",'(',')'),'',$theemail);
		$theemail=strip_tags($theemail);
		for($i=0; $i < strlen($theemail); $i++){
			$ch=substr($theemail,$i,1);
			if(!($ch=='@'&&$gotat)) $tmpstr.=substr($theemail,$i,1);
			if($ch=='@')$gotat=TRUE;
		}
		if(!$gotat) $tmpstr='';
		$tmpstr=strtolower($tmpstr);
	}
	return($tmpstr);
}
function getfullurl($pagepart){
	$gfu='';
	if(substr($pagepart,0,5)!="http:" && substr($pagepart,0,6)!='https:'){
		$temp_php_self=strreplace('"','',strip_tags(@$_SERVER['PHP_SELF']));
		$gfu='http'.(@$_SERVER['HTTPS']=='on' || @$_SERVER['SERVER_PORT']=='443' || strtolower(substr($pagepart,0,6))=='https:'?'s':'').'://'.$_SERVER['HTTP_HOST'];
		if(substr($pagepart,0,1)!='/') $gfu.=(strrpos($temp_php_self,'/')>1?substr($temp_php_self,0,strrpos($temp_php_self,'/')+1):'/');
	}
	return($gfu.$pagepart);
}
function get_wholesaleprice_sql(){
	global $WSP,$OWSP,$TWSP,$wholesaleoptionpricediff,$nowholesalediscounts,$nodiscounts;
	if(@$_SESSION['clientUser']!=''){
		if(($_SESSION['clientActions'] & 8)==8){
			$WSP='pWholesalePrice AS ';
			$TWSP='pWholesalePrice';
			if(@$wholesaleoptionpricediff==TRUE) $OWSP='optWholesalePriceDiff AS ';
			if(@$nowholesalediscounts==TRUE) $nodiscounts=TRUE;
		}
		if(($_SESSION['clientActions'] & 16)==16){
			$WSP=$_SESSION['clientPercentDiscount'] . '*'.(($_SESSION['clientActions'] & 8)==8?'pWholesalePrice':'pPrice').' AS ';
			$TWSP=$_SESSION['clientPercentDiscount'] . '*'.(($_SESSION['clientActions'] & 8)==8?'pWholesalePrice':'pPrice');
			$OWSP=$_SESSION['clientPercentDiscount'] . '*'.((($_SESSION['clientActions'] & 8)==8)&&@$wholesaleoptionpricediff?'optWholesalePriceDiff':'optPriceDiff').' AS ';
			if(@$nowholesalediscounts==TRUE) $nodiscounts=TRUE;
		}
	}
}
function writepagebar($CurPage,$iNumPages,$sprev,$snext,$sLink,$nofirstpage){
	if(@$GLOBALS['numpagenumbers']==''||@$GLOBALS['ectadminfunctionsdefined']) $GLOBALS['numpagenumbers']=10;
	$startPage=max(1,round(floor((float)$CurPage/$GLOBALS['numpagenumbers'])*$GLOBALS['numpagenumbers']));
	$endPage=min($iNumPages,round(floor((float)$CurPage/$GLOBALS['numpagenumbers'])*$GLOBALS['numpagenumbers'])+$GLOBALS['numpagenumbers']);
	if($CurPage > 1)
		$sStr=$sLink . '1"><span class="pagebarquo pagebarlquo">&laquo;</span></a> ' . $sLink . ($CurPage-1) . '"'.($CurPage>2?' rel="prev"':'').'><span class="pagebarprevnext pagebarprev">'.$sprev.'</span></a><span class="pagebarsep"></span>';
	else
		$sStr='<span class="pagebarquo pagebarlquo">&laquo;</span> <span class="pagebarprevnext pagebarprev">'.$sprev.'</span><span class="pagebarsep"></span>';
	for($i=$startPage;$i <= $endPage; $i++){
		if($i==$CurPage)
			$sStr.='<span class="pagebarnum currpage" aria-current="page">' . $i . '</span><span class="pagebarsep"></span>';
		else{
			$sStr.=$sLink . $i . '"><span class="pagebarnum">';
			if($i==$startPage && $i > 1) $sStr.='...';
			$sStr.=$i;
			if($i==$endPage && $i < $iNumPages) $sStr.='...';
			$sStr.='</span></a><span class="pagebarsep"></span>';
		}
	}
	if($CurPage < $iNumPages)
		$sStr.=$sLink . ($CurPage+1) . '" rel="next"><span class="pagebarprevnext pagebarnext">'.$snext.'</span></a> ' . $sLink . $iNumPages . '"><span class="pagebarquo pagebarrquo">&raquo;</span></a>';
	else
		$sStr.=' <span class="pagebarprevnext pagebarnext">'.$snext.'</span> <span class="pagebarquo pagebarrquo">&raquo;</span>';
	if($nofirstpage) $sStr=strreplace(array('&amp;pg=1"','?pg=1"'),'" rel="start"',$sStr);
	return($sStr);
}
function addtag($tagname, $strValue){
	return('<' . $tagname . '>' . strreplace('<', '&lt;', strreplace('&', '&amp;', $strValue)) . '</' . $tagname . '>');
}
function whv($hvname,$hvval){
return('<input type="hidden" name="' . $hvname . '" value="' . htmlspecials($hvval) . '">' . "\n");
}
function getsessionid(){
	global $persistentcart;
	if(is_numeric(@$persistentcart)&&(int)@$persistentcart>0){
		if(@$_COOKIE['ectcartcookie']!=''){
			return(strreplace("'",'',$_COOKIE['ectcartcookie']));
		}else{
			$gotunique=FALSE;
			while(! $gotunique){
				$sequence=substr(md5(uniqid('',TRUE).session_id()),0,26);
				$sSQL="SELECT cartSessionID FROM cart WHERE cartSessionID='" . $sequence . "'";
				$result=ect_query($sSQL) or ect_error();
				if(ect_num_rows($result)==0) $gotunique=TRUE;
				ect_free_result($result);
			}
			$_COOKIE['ectcartcookie']=$sequence;
			setacookie('ectcartcookie', $sequence, $persistentcart);
			return($sequence);
		}
	}else
		return(session_id());
}
function dohashpw($thepw){
	if(trim_($thepw)=='') return(''); else return(md5('ECT IS BEST'.trim_($thepw)));
}
function logevent($userid,$eventtype,$eventsuccess,$eventorigin,$areaaffected,$eventtext=''){
	if(is_null($eventorigin)) $eventorigin='';
	if(@$GLOBALS['padssfeatures']||$eventtext!=''){
		$sSQL='INSERT INTO auditlog (userID,eventType,eventDate,eventSuccess,eventOrigin,areaAffected,eventText) VALUES (' .
			"'" . escape_string(substr($userid,0,48)) . "','" . escape_string(substr($eventtype,0,50)) . "'," .
			"'" . date('Y-m-d H:i:s') . "'," . ($eventsuccess?1:0) . "," .
			"'" . escape_string(substr($eventorigin,0,48)) . "','" . escape_string(substr($areaaffected,0,48)) . "','" . escape_string($eventtext) . "')";
		ect_query($sSQL) or ect_error();
		ect_query("DELETE FROM auditlog WHERE eventDate<'" . date('Y-m-d H:i:s',time()-60*60*24*365) . "'") or ect_error();
	}
}
function splitname($thename, &$firstname, &$lastname){
	if(strstr($thename,' ')){
		list($firstname,$lastname)=explode(' ',$thename,2);
	}else{
		$firstname='';
		$lastname=trim_($thename);
	}
}
function replace($str,$fnd,$rep){
	return(strreplace($fnd,$rep,$str));
}
function detectmobilebrowser(){
	$uagent=strtolower(is_null(@$_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT']);
	$dmb=FALSE;
	if(strpos($uagent,'android')!==FALSE||strpos($uagent,'blackberry')!==FALSE||strpos($uagent,'iemobile')!==FALSE||strpos($uagent,'iphone')!==FALSE||strpos($uagent,'mobile')!==FALSE||strpos($uagent,'nokia')!==FALSE||strpos($uagent,'opera mini')!==FALSE||strpos($uagent,'pocketpc')!==FALSE||strpos($uagent,'samsung')!==FALSE||strpos($uagent,'symbian')!==FALSE||strpos($uagent,'smartphone')!==FALSE) $dmb=TRUE;
	return($dmb);
}
function getget($tval){
	if(is_array(@$_GET[$tval])) return @$_GET[$tval];
	return(gettype(@$_GET[$tval])=='string'?unstripslashes(@$_GET[$tval]):'');
}
function getpost($tval){
	if(is_array(@$_POST[$tval])) return @$_POST[$tval];
	return(gettype(@$_POST[$tval])=='string'?unstripslashes(@$_POST[$tval]):'');
}
function getpostint($tval){
	$tval=@$_POST[$tval];
	if(! is_numeric($tval)) $tval=0; else $tval=(int)$tval;
	if($tval<-2147483648) $tval=-2147483648;
	if($tval>2147483647) $tval=2147483647;
	return($tval);
}
function getrequest($tval){
	return(getget($tval)!=''?getget($tval):getpost($tval));
}
function debugwritefilelimit($tracetxt,$clearfile){
	$fhandle=fopen('debugtrace.txt',$clearfile?'w':'a');
	$fstat=fstat($fhandle);
	if($fstat['size']<(1024*1024*10))
		fwrite($fhandle,$tracetxt);
	fclose($fhandle);
}
function debugparametertrace(){
	if(@$GLOBALS['parametertrace']||@$_SESSION['parametertrace']){
		$tracetxt='';
		foreach($_GET as $key => $val){
			if(gettype($val)=='string')
				$tracetxt.=date('Y-m-d H:i') . ' : ' . $_SERVER['REMOTE_ADDR'] . ' : GET: ' . $key . ' : ' . $val . "\r\n";
		}
		foreach($_POST as $key => $val){
			if(gettype($val)=='string')
				$tracetxt.=date('Y-m-d H:i') . ' : ' . $_SERVER['REMOTE_ADDR'] . ' : POST: ' . $key . ' : ' . $val . "\r\n";
		}
		if($tracetxt!='') debugwritefilelimit("========\r\n".$tracetxt,FALSE);
	}
}
debugparametertrace();
function debugsqltrace($txt){
	$bt=debug_backtrace();
	$caller=$bt[1];
	debugwritefilelimit(date('Y-m-d H:i') . ' : ' . $_SERVER['REMOTE_ADDR'] . ' : ' . basename($caller['file']) . ' - ' . $caller['line'] . ' : ' . $txt . "\r\n",FALSE);
}
$GLOBALS['sqldebug']='';
function ect_query($ectsql){
	global $sqldebug;
	if(@$GLOBALS['sqltrace']||@$_SESSION['sqltrace']){
		$sqldebug.=$ectsql.'<br>';
		list($usec, $sec) = explode(' ', microtime());
		$sqlstarttime=((float)$usec + (float)$sec);
		debugsqltrace($ectsql);
	}
	if(@$GLOBALS['ectdatabase'])mysqli_report(MYSQLI_REPORT_OFF);
	$ectretval=@$GLOBALS['ectdatabase']?@$GLOBALS['ectdatabase']->query($ectsql):mysql_query($ectsql);
	if(@$GLOBALS['debugmode']&&$ectretval==FALSE){
		$bt=debug_backtrace();
		$caller=array_shift($bt);
		echo '<strong>DATABASE ERROR:</strong> '.$caller['file'].' on line '.$caller['line'].'<br>'.$ectsql,'<br>';
		if(@$GLOBALS['sqltrace']||@$_SESSION['sqltrace']) debugsqltrace('DATABASE ERROR: '.$caller['file'].' on line '.$caller['line']);
	}
	if(@$GLOBALS['sqltrace']||@$_SESSION['sqltrace']){
		list($usec, $sec) = explode(' ', microtime());
		$sqlendtime=((float)$usec + (float)$sec);
		$sqldebug.='Query Took: ' . round(($sqlendtime-$sqlstarttime)*1000,2) . 'ms<br>';
	}
	return($ectretval);
}
function ect_fetch_assoc($ectres){
	return(@$GLOBALS['ectdatabase']?$ectres->fetch_assoc():mysql_fetch_assoc($ectres));
}
function ect_num_rows($ectres){
	return(@$GLOBALS['ectdatabase']?$ectres->num_rows:mysql_num_rows($ectres));
}
function ect_insert_id(){
	return(@$GLOBALS['ectdatabase']?$GLOBALS['ectdatabase']->insert_id:mysql_insert_id());
}
function ect_free_result($ectres){
	@$GLOBALS['ectdatabase']?$ectres->free_result():mysql_free_result($ectres);
}
function ect_error(){
	print(@$GLOBALS['ectdatabase']?$GLOBALS['ectdatabase']->error:mysql_error());
}
function jsurlencode($tstr){
	return rawurlencode($tstr);
}
function jsenc($tstr){
	global $adminencoding;
	if(strtolower(@$adminencoding)!='utf-8') $tstr=utf8_encode($tstr);
//	$tstr=mb_convert_encoding($tstr,'utf-8','euc-jp');
	return($tstr);
}
function getdetailsurl($gdid,$gdstatic,$gdname,$gdurl,$gdqs,$gdpathtohere){
	global $seodetailurls,$detlinkspacechar,$usepnamefordetaillinks;
	$gdname=($gdurl!=''?$gdurl:$gdname);
	$replacecharsinname=strreplace(' ',@$detlinkspacechar,$gdname);
	if(@$GLOBALS['autoencodeslashes']) $replacecharsinname=strreplace(array('/','\\'),array('&#47;','&#92;'),$replacecharsinname);
	if(@$GLOBALS['seodetailurlpattern']!='')
		return(strpos($gdname,'://')!==FALSE ? $gdname : strreplace('%s',rawurlencode($replacecharsinname),$GLOBALS['seodetailurlpattern']).($gdqs!=''?'?'.$gdqs:''));
	elseif(@$seodetailurls)
		return(strpos($gdname,'://')!==FALSE ? $gdname : $gdpathtohere.rawurlencode($replacecharsinname).($gdqs!=''?'?'.$gdqs:''));
	elseif($gdurl!='')
		return($gdpathtohere.$gdurl.($gdqs!=''?'?'.$gdqs:''));
	elseif($gdstatic!=0&&!@$GLOBALS['iswordpress'])
		return($gdpathtohere.cleanforurl($gdname).$GLOBALS['extension'].($gdqs!=''?'?'.$gdqs:''));
	return($gdpathtohere.'proddetail'.$GLOBALS['extension'].'?prod='.urlencode(@$usepnamefordetaillinks?$replacecharsinname:$gdid).($gdqs!=''?'&amp;'.$gdqs:''));
}
function commaseplist($inlist){
	$inlist=preg_replace('/[^,\d]/','',$inlist);
	$inlist=preg_replace('/,+/',',',$inlist);
	return(preg_replace('/,$|^,/','',$inlist));
}
function getperproductdiscounts(){
	global $rs,$topcpnids,$topsectionids,$isrootsection,$alldiscounts,$catid,$maxglobaldiscounts,$globaldiscounts,$noapplydiscounts,$hascheckedperproductdiscounts;
	if(@$_SESSION['clientID']!='' && @$_SESSION['clientLoginLevel']!='') $minloglevel=$_SESSION['clientLoginLevel']; else $minloglevel=0;
	if(@$GLOBALS['noshowdiscounts']!=TRUE&&!@$hascheckedperproductdiscounts&&($rs['pExemptions']&64)!=64){
		$isglobaldiscount=FALSE; $localdiscounts=','; $lastcouponname=$attributelist=''; $hascheckedperproductdiscounts=TRUE;
		$sSQL="SELECT mSCscID FROM multisearchcriteria WHERE mSCpID='".escape_string($rs['pId'])."'";
		$result2=ect_query($sSQL) or ect_error();
		while($rs2=ect_fetch_assoc($result2)) $attributelist.=$rs2['mSCscID'].' ';
		ect_free_result($result2);
		$attributelist=strreplace(' ',"','",trim_($attributelist));
		$sSQL='SELECT DISTINCT cpnID,'.getlangid('cpnName',1024)." FROM coupons LEFT OUTER JOIN cpnassign ON coupons.cpnID=cpnassign.cpaCpnID WHERE (cpnSitewide=0 OR cpnSitewide=3 OR cpnSitewide=4) AND cpnNumAvail>0 AND cpnStartDate<='" . date('Y-m-d',time()) ."' AND cpnEndDate>='" . date('Y-m-d',time()) ."' AND cpnIsCoupon=0 AND ((cpaType=2 AND cpaAssignment='" . escape_string($rs['pId']) . "')";
		if(! $isrootsection) $sSQL.=" OR (cpaType=1 AND cpaAssignment IN ('" . strreplace(',',"','",$topcpnids) . "') AND NOT cpaAssignment IN ('" . strreplace(',',"','",$topsectionids) . "'))";
		if($attributelist!='') $sSQL.=" OR (cpaType=3 AND cpaAssignment IN ('".$attributelist."'))";
		$sSQL.=') AND ((cpnLoginLevel>=0 AND cpnLoginLevel<='.$minloglevel.') OR (cpnLoginLevel<0 AND -1-cpnLoginLevel='.$minloglevel.')) ORDER BY '.getlangid('cpnName',1024);
		$result2=ect_query($sSQL) or ect_error();
		while($rs2=ect_fetch_assoc($result2)){
			for($index=0;$index<$maxglobaldiscounts;$index++){
				if($globaldiscounts[$index][0]==$rs2['cpnID']){ $isglobaldiscount=TRUE; $localdiscounts.=$rs2['cpnID'].','; }
			}
			if(! $isglobaldiscount && $rs2[getlangid('cpnName',1024)]!=$lastcouponname) $alldiscounts.='<div>' . ($lastcouponname=$rs2[getlangid('cpnName',1024)]) . '</div>';
		}
		ect_free_result($result2);
		if($catid!='0' && $topsectionids!=''){
			if(strpos(','.$topsectionids.',',','.$rs['pSection'].',')===FALSE){
				for($index=0;$index<$maxglobaldiscounts;$index++){
					if(strpos($localdiscounts,','.$globaldiscounts[$index][0].',')===FALSE){
						if($globaldiscounts[$index][2]=='xxx'){
							$rowcounter=0;
							$otherassignments='';
							$sSQL='SELECT cpaAssignment FROM cpnassign WHERE cpaCpnID='.$globaldiscounts[$index][0].' AND cpaType=1';
							$result2=ect_query($sSQL) or ect_error();
							while($rs2=ect_fetch_assoc($result2)){
								$otherassignments.=$rs2['cpaAssignment'].',';
								$rowcounter++;
							}
							ect_free_result($result2);
							if($rowcounter>1) $otherassignments=','.getsectionids(substr($otherassignments,-1),FALSE).','; else $otherassignments='';
							$globaldiscounts[$index][2]=$otherassignments;
						}
						if(strpos($globaldiscounts[$index][2],','.$rs['pSection'].',')===FALSE&&strpos($noapplydiscounts,'<div>' . $globaldiscounts[$index][1] . '</div>')===FALSE) $noapplydiscounts.='<div>' . $globaldiscounts[$index][1] . '</div>';
					}
				}
			}
		}
	}
}
function displaybmlbanner($pubid,$bannerdims){ ?>
<div class="billmelaterbanner" style="text-align:center"><script data-pp-pubid="<?php print $pubid?>" data-pp-placementtype="<?php print $bannerdims?>"> (function (d, t) {
"use strict";
var s=d.getElementsByTagName(t)[0], n=d.createElement(t);
n.src="//paypal.adtag.where.com/merchant.js";
s.parentNode.insertBefore(n, s);
}(document, "script"));
</script></div><?php
}
function labeltxt($lbltxt,$lblid){
	return '<label class="ectlabel" for="'.$lblid.'">'.$lbltxt.'</label>';
}
function quantitymarkup($isquickbuy,$Count,$isdetail,$placeholder,$addonchange){
global $quantityupdown,$quantitydefault;
if(!@isset($quantitydefault))$quantitydefault=1;
if(@$GLOBALS['quantityupdown']===2)
return '<div class="'.$placeholder.'quantity2div' . ($isdetail?' detail':' prod') . 'quantity2div"><div onclick="quantup(\''.($isquickbuy?'qb':'').$Count.'\',0)">-</div><input type="text"'.($isquickbuy?'':' name="quant"').' id="w'.($isquickbuy?'qb':'').$Count.'quant" maxlength="5" value="' . $quantitydefault . '" title="'.$GLOBALS['xxQuant'].'" ' . ($addonchange?'onchange="ectById(\'qnt'.$Count.'x\').value=this.value" ':'') . 'class="quantity2input' . ($isdetail?' detail':' prod') . 'quantity2input"><div onclick="quantup(\''.($isquickbuy?'qb':'').$Count.'\',1)">+</div></div>'."\n";
elseif(@$GLOBALS['quantityupdown'])
return '<div class="'.$placeholder.'quantity1div' . ($isdetail?' detail':' prod') . 'quantity1div"><input type="text"'.($isquickbuy?'':' name="quant"').' id="w'.($isquickbuy?'qb':'').$Count.'quant" size="2" maxlength="5" value="' . $quantitydefault . '" title="'.$GLOBALS['xxQuant'].'" ' . ($addonchange?'onchange="ectById(\'qnt'.$Count.'x\').value=this.value" ':'') . 'class="quantity1input' . ($isdetail?' detail':' prod') . 'quantity1input"><div onclick="quantup(\''.($isquickbuy?'qb':'').$Count.'\',1)">+</div><div onclick="quantup(\''.($isquickbuy?'qb':'').$Count.'\',0)">-</div></div>'."\n";
else
return '<div class="'.$placeholder.'quantity0div' . ($isdetail?' detail':' prod') . 'quantity0div"><input type="text"'.($isquickbuy?'':' name="quant"').' id="w'.($isquickbuy?'qb':'').$Count.'quant" size="2" maxlength="5" value="' . $quantitydefault . '" title="'.$GLOBALS['xxQuant'].'" ' . ($addonchange?'onchange="ectById(\'qnt'.$Count.'x\').value=this.value" ':'') . 'class="ecttextinput quantity0input' . ($isdetail?' detail':' prod') . 'quantity0input"></div>'."\n";
}
function displaydiscountexemptions(){
	global $rs,$hasshippingdiscount,$hasproductdiscount;
	if(($rs['pExemptions']&80)==80 && ($hasshippingdiscount || $hasproductdiscount)){
		if($GLOBALS['xxNoDisc']!='') print '<div class="ectwarning proddiscountexempt">'.$GLOBALS['xxNoDisc'].'</div>';
	}else{
		if(($rs['pExemptions']&16)==16&&$hasshippingdiscount&&@$GLOBALS['xxNoFrSh']!='') print '<div class="ectwarning freeshippingexempt">'.$GLOBALS['xxNoFrSh'].'</div>';
		if(($rs['pExemptions']&64)==64&&$hasproductdiscount&&@$GLOBALS['xxNoDsPr']!='') print '<div class="ectwarning proddiscountexempt">'.$GLOBALS['xxNoDsPr'].'</div>';
	}
}
function ectisvideoext($fileext){
	return($fileext=='avi'||$fileext=='mov'||$fileext=='mpe'||$fileext=='mpg'||$fileext=='mpeg'||$fileext=='mp4'||$fileext=='webm'||$fileext=='wmv');
}
function displaylayoutarray($layoutarray,$isquickbuy){
	global $Count,$rs,$startlink,$endlink,$shortdesc,$cs,$atcmu,$atcmuqb,$showproductid,$hascustomlayout,$usecsslayout,$showproductsku,$allimages,$alllgimages,$numallimages,$numalllgimages,$thumbnailsonproducts,$hasformvalidator,
	$magictoolboxproducts,$magictooloptionsproducts,$magicscrollthumbnailsproducts,$thumbnailstyleproducts,$alldiscounts,$noapplydiscounts,$hasshippingdiscount,$ratingsonproductspage,$useStockManagement,$showinstock,$giftcertificateid,$optionshtml,
	$donationid,$noprice,$plargeimage,$thedetailslink,$extraimages,$imgdetaillink,$pricezeromessage,$nosellzeroprice,$hasmultipurchase,$isinstock,$isbackorder,$quantityupdown,$imgquickbuybutton,$quickbuylayoutarray,
	$currRate1,$currSymbol1,$currFormat1,$currRate2,$currSymbol2,$currFormat2,$currRate3,$currSymbol3,$currFormat3,$currencyseparator,$prodcustomlabel1,$prodcustomlabel2,$prodcustomlabel3,$thetax,$WSP,$optionshavestock;
	$dlasavecs=$cs;
	if($isquickbuy) $cs='';
	foreach($layoutarray as $layoutoption){
		$layoutoptioncase=trim_($layoutoption);
		$layoutoption=strtolower($layoutoptioncase);
		if($layoutoption=='minquantity'){
			if($rs['pMinQuant']>0) print '<div class="prodminquant">' . strreplace('%quant%',$rs['pMinQuant']+1,$GLOBALS['xxMinQua']) . '</div>';
		}elseif($layoutoption=='productid'){
			if(@$showproductid || $hascustomlayout) print (! @$usecsslayout ? '<tr><td>' : '') . '<div class="'.$cs.'prodid">' . ($GLOBALS['xxPrId']!=''?'<span class="'.$cs.'prodidlabel">' . $GLOBALS['xxPrId'] . '</span> ':'') . $rs['pId'] . '</div>' . (! @$usecsslayout ? '</td></tr>' : '') . "\n";
		}elseif($layoutoption=='manufacturer'){
			if(! is_null($rs[getlangid('scName',131072)])) print (! @$usecsslayout ? '<tr><td>' : '') . '<div class="'.$cs.'prodmanufacturer">' . (@$GLOBALS['xxManLab']!=''?'<span class="'.$cs.'prodmanufacturerlabel">' . $GLOBALS['xxManLab'] . '</span> ':'') . $rs[getlangid('scName',131072)] . '</div>' . (! @$usecsslayout ? '</td></tr>' : ''). "\n";
		}elseif($layoutoption=='sku'){
			if((@$showproductsku!='' || $hascustomlayout) && $rs['pSKU']!='') print (! @$usecsslayout ? '<tr><td>' : '') . '<div class="'.$cs.'prodsku">' . ($showproductsku!=''?'<span class="'.$cs.'prodskulabel">' . $showproductsku . '</span> ':'') . $rs['pSKU'] . '</div>' . (! @$usecsslayout ? '</td></tr>' : ''). "\n";
		}elseif($layoutoption=='productimage'){
			if(! @$usecsslayout) print '<tr><td width="100%" align="center" class="'.$cs.'prodimage allprodimages">';
			if($numallimages==0){
				if(@$usecsslayout){
					print '<div class="'.$cs.'prodimage allprodimages">';
					if(@$GLOBALS['defaultproductimage']=='') print '&nbsp;'; else print $startlink . '<img id="' . ($isquickbuy?'qb':'prod') . 'image'.$Count.'" class="'.@$cs.'prodimage allprodimages" src="' . $GLOBALS['defaultproductimage'] . '" alt="'.strreplace('"', '&quot;', strip_tags($rs[getlangid('pName',1)])).'">' . $endlink;
					print '</div>';
				}else
					print '&nbsp;';
			}else{
				if(@$usecsslayout)
					print '<div class="'.$cs.'prodimage allprodimages">';
				elseif($numallimages>1 && !@$thumbnailsonproducts)
					print '<table border="0" cellspacing="1" cellpadding="1"><tr><td colspan="3">';
				if(($magictoolboxproducts=='MagicSlideshow' || $magictoolboxproducts=='MagicScroll') && $numallimages>1){
					print '<div class="' . $magictoolboxproducts . '" ' . @$magictooloptionsproducts . '>';
					for($index=0;$index<$numallimages;$index++){
						if($index<$numalllgimages) $largeimage=$alllgimages[$index]['imageSrc']; else $largeimage='';
						print '<img' . (@$GLOBALS['noschemamarkup']?'':' itemprop="image"') . ' src="' . $allimages[$index]['imageSrc'] . '" alt="" '.($largeimage!=''&&$magictoolboxproducts=='MagicSlideshow'?'data-fullscreen-image="'.$largeimage.'" ':'').'>';
					}
					print '</div>';
				}else{
					$imgextension=strtolower(pathinfo($allimages[0]['imageSrc'],PATHINFO_EXTENSION));
					$isvideo=ectisvideoext($imgextension);
					$relid=@$magictooloptionsproducts;
					if(@$magictoolboxproducts=='MagicThumb'){
						if(@$magictooloptionsproducts=='') $relid='rel="group:g'.$Count.'" '; else $relid=strreplace('rel="','rel="group:g'.$Count.';',$magictooloptionsproducts) . ' ';
					}
					print (@$magictoolboxproducts!='' && @$magictoolboxproducts!='MagicSlideshow' && @$magictoolboxproducts!='MagicScroll' && $plargeimage!=''?'<a id="mz' . ($isquickbuy?'qb':'prod') . 'image'.$Count.'" '.$relid.' href="'.$plargeimage.'" class="' . $magictoolboxproducts . '">':$startlink).'<' . ($isvideo?'video controls ':'img ') . 'id="' . ($isquickbuy?'qb':'prod') . 'image'.$Count.'" class="'.@$cs.'prodimage allprodimages" src="'.strreplace('%s','',$allimages[0]['imageSrc']).'" alt="'.strreplace('"', '&quot;', strip_tags($rs[getlangid('pName',1)])).'">' . ($isvideo?'</video>':'') . (@$magictoolboxproducts!='' && $plargeimage!=''?'</a>':$endlink);
					if($numallimages>1 && !@$thumbnailsonproducts)
						print (@$usecsslayout ? '<div class="'.$cs.'imagenavigator prodimagenavigator">' : '</td></tr><tr><td class="'.$cs.'imagenavigator prodimagenavigator" align="left">') . imageorbutton(@$GLOBALS['imgprevimg'],@$GLOBALS['xxPrImTx'],'previmg','updateprodimage2(' . ($isquickbuy?'true,':'false,') . $Count.',false)',TRUE) . (@$usecsslayout ? '' : '</td><td align="center">') . '<span class="extraimage extraimagenum" id="' . ($isquickbuy?'qb':'extra') . 'imcnt' . $Count . '">1</span> <span class="extraimage">' . $GLOBALS['xxOf'] . ' ' . $extraimages . '</span>' . (@$usecsslayout ? '' : '</td><td align="right">') . imageorbutton(@$GLOBALS['imgnextimg'],@$GLOBALS['xxNeImTx'],'nextimg','updateprodimage2(' . ($isquickbuy?'true,':'false,') . $Count.',true)',TRUE) . (@$usecsslayout ? '</div>' : '</td></tr></table>');
				}
				if(@$usecsslayout) print '</div>';
				if(@$magictoolboxproducts!='' && $numallimages>1 && @$thumbnailsonproducts){
					if($magictoolboxproducts=='MagicThumb') $relid=' rel="thumb-id:mz' . ($isquickbuy?'qb':'prod') . 'image'.$Count.'"'; else $relid='';
					if($magictoolboxproducts=='MagicZoom' || $magictoolboxproducts=='MagicZoomPlus') $relid=' data-zoom-id="mz' . ($isquickbuy?'qb':'prod') . 'image'.$Count.'"';
					if(@$thumbnailstyleproducts=='') $thumbnailstyleproducts='width:50px;padding:2px';
					if(@$usecsslayout) print '<div class="thumbnailimage productsthumbnail">'; else print '</td></tr><tr><td class="thumbnailimage productsthumbnail" align="center">';
					if(@$magicscrollthumbnailsproducts) print '<div class="MagicScroll">';
					for($index=0;$index<$numallimages;$index++){
						if($index < $numalllgimages) print '<a href="' . $alllgimages[$index]['imageSrc'] . '" rev="' . $allimages[$index]['imageSrc'] . '"' . $relid . '><img src="' . $allimages[$index]['imageSrc'] . '" style="' . $thumbnailstyleproducts . '" alt=""></a>';
					}
					if(@$magicscrollthumbnailsproducts) print '</div>';
					if(@$usecsslayout) print '</div>'; else print '</td></tr></table>';
				}
			}
			if(! @$usecsslayout) print '</td></tr>';
			print "\n";
		}elseif($layoutoption=='productname'){
			if(! @$usecsslayout) print '<tr><td width="100%">';
			print '<div class="'.$cs.'prodname">' . $startlink . $rs[getlangid("pName",1)] . $endlink . $GLOBALS['xxDot'] . '</div>' . "\n";
		}elseif($layoutoption=='discounts'){
			$savenoshowdiscounts=@$GLOBALS['noshowdiscounts'];
			if($hascustomlayout) $GLOBALS['noshowdiscounts']=FALSE;
			getperproductdiscounts();
			if($alldiscounts!='') print ($GLOBALS['xxDsApp']!=''?'<div class="eachproddiscountsapply eachproddiscount">' . $GLOBALS['xxDsApp'] . '</div>':'') . '<div class="proddiscounts '.$cs.'eachproddiscount">' . $alldiscounts . '</div>'. "\n";
			if($noapplydiscounts!='') print '<div class="ectwarning discountsnotapply">' . $GLOBALS['xxDsNoAp'] . '</div><div class="'.$cs.'prodnoapplydiscounts">' . $noapplydiscounts . '</div>'. "\n";
			displaydiscountexemptions();
			$GLOBALS['noshowdiscounts']=$savenoshowdiscounts;
		}elseif($layoutoption=='reviewstars'){
			if(@$ratingsonproductspage==TRUE || $hascustomlayout){
				if($rs['pNumRatings']>0) print showproductreviews(2, $cs.'prodrating'); else print @$GLOBALS['prodreviewnoratings'];
			}
		}elseif($layoutoption=='instockmsg'){
			if($useStockManagement && (($rs['pStockByOpts']==0 && $rs['pInStock']>0) || ($rs['pStockByOpts']!=0 && $optionshavestock))) print '<div class="'.$cs.'prodinstock">' . str_replace('%s',max(0,$rs['pInStock']),$GLOBALS['xxInStoc']) . "</div>\n";
		}elseif($layoutoption=='instock'){
			if($useStockManagement && (@$showinstock || $hascustomlayout) && ($rs['pInStock']<=@$GLOBALS['stockdisplaythreshold'] || @$GLOBALS['stockdisplaythreshold']=='')){ if((int)$rs['pStockByOpts']==0) print '<div class="'.$cs.'prodinstock">' . ($GLOBALS['xxInStoc']!=''?'<span class="prodinstocklabel">' . $GLOBALS['xxInStoc'] . '</span> ':'') . max(0,$rs['pInStock']) . "</div>\n"; }
		}elseif($layoutoption=='description'){
			if($shortdesc!='') print '<div class="'.$cs.'proddescription">' . $shortdesc . "</div>\n"; else print '<br>';
		}elseif($layoutoption=='options'){
			if($hasformvalidator) print 'DUPLICATE OPTIONS'; else print $optionshtml;
			$hasformvalidator=TRUE;
		}elseif($layoutoption=='listprice'){
			if($rs['pId']!=$giftcertificateid && $rs['pId']!=$donationid && @$noprice!=TRUE){
				if((float)$rs['pListPrice']!=0.0){
					$plistprice=(@$GLOBALS['showtaxinclusive']===2 && ($rs['pExemptions'] & 2)!=2?$rs['pListPrice']+($rs['pListPrice']*$thetax/100.0):$rs['pListPrice']);
					$yousaveprice=$plistprice-(@$GLOBALS['showtaxinclusive']===2 && ($rs['pExemptions'] & 2)!=2 ? $rs['pPrice']+($rs['pPrice']*$thetax/100.0) : $rs['pPrice']);
					print '<div class="listpricediv '.$cs.'listprice" id="'.($isquickbuy?'qb':'').'listdivec' . $Count . '"' . ($yousaveprice<=0?' style="display:none"':'') . '>' . strreplace('%s', FormatEuroCurrency($plistprice), $GLOBALS['xxListPrice']) . (@$GLOBALS['yousavetext']!=''&&$yousaveprice>0?strreplace('%s', FormatEuroCurrency($yousaveprice), $GLOBALS['yousavetext']):'') . '</div>';
				}
			}
		}elseif($layoutoption=='price'){
			if($rs['pId']!=$giftcertificateid && $rs['pId']!=$donationid && @$noprice!=TRUE){
				$displayprice=@$GLOBALS['showtaxinclusive']===2 && ($rs['pExemptions'] & 2)!=2 ? $rs['pPrice']+($rs['pPrice']*$thetax/100.0) : $rs['pPrice'];
				print '<div class="'.$cs.'prodprice"><span class="prodpricelabel">' . $GLOBALS['xxPrice'] . '</span><span class="price" id="'.($isquickbuy?'qb':'').'pricediv' . $Count . '">' . ($rs['pPrice']==0 && @$pricezeromessage!='' ? $pricezeromessage : FormatEuroCurrency($displayprice)) . '</span> ';
				if(@$GLOBALS['showtaxinclusive']==1 && ($rs['pExemptions'] & 2)!=2) printf('<span class="inctax" id="'.($isquickbuy?'qb':'').'taxmsg' . $Count . '"' . ($rs['pPrice']==0 ? ' style="display:none"' : '') . '>' . $GLOBALS['ssIncTax'] . '</span>','<span id="'.($isquickbuy?'qb':'').'pricedivti' . $Count . '">' . ($rs['pPrice']==0 ? '-' : FormatEuroCurrency($rs['pPrice']+($rs['pPrice']*$thetax/100.0))) . '</span> ');
				if($isquickbuy ? (($GLOBALS['adminPayLater'] & 256)==256) : (($GLOBALS['adminPayLater'] & 1)==1)){
					print '<div data-pp-message data-pp-amount="' . $displayprice . '" class="paylaterquote prodpaylaterquote"></div>'."\n";
				}
				print "</div>\n";
			}
		}elseif($layoutoption=='currency'){
			if($rs['pId']!=$giftcertificateid && $rs['pId']!=$donationid && @$noprice!=TRUE){
				$extracurr='';
				if($currRate1!=0 && $currSymbol1!='') $extracurr=strreplace('%s',number_format($rs['pPrice']*$currRate1,checkDPs($currSymbol1),$GLOBALS['currDecimalSep'],$GLOBALS['currThousandsSep']),$currFormat1) . $currencyseparator;
				if($currRate2!=0 && $currSymbol2!='') $extracurr.=strreplace('%s',number_format($rs['pPrice']*$currRate2,checkDPs($currSymbol2),$GLOBALS['currDecimalSep'],$GLOBALS['currThousandsSep']),$currFormat2) . $currencyseparator;
				if($currRate3!=0 && $currSymbol3!='') $extracurr.=strreplace('%s',number_format($rs['pPrice']*$currRate3,checkDPs($currSymbol3),$GLOBALS['currDecimalSep'],$GLOBALS['currThousandsSep']),$currFormat3);
				if($extracurr!='') print '<div class="'.$cs.'prodcurrency"><span class="extracurr" id="'.($isquickbuy?'qb':'').'pricedivec' . $Count . '">' . ($rs['pPrice']==0 ? '' : $extracurr) . "</span></div>\n";
			}
		}elseif($layoutoption=='quantity'){
			if(! ($rs['pPrice']==0 && @$nosellzeroprice==TRUE) && $hasmultipurchase==0 && ($isinstock || $isbackorder) && $rs['pSchemaType']!=1){
				print (@$usecsslayout ? '' : '<table><tr><td align="center">') . quantitymarkup($isquickbuy,$Count,FALSE,'',FALSE) . (@$usecsslayout ? '' : '</td><td align="center">');
			}
		}elseif($layoutoption=='addtocart'){
			if(! @$usecsslayout) print '</td></tr>';
			if($rs['pSchemaType']==1){
			}elseif($hasmultipurchase==2)
				print '<div class="'.$cs.'addtocart prodaddtocart">' . imageorbuttontag(@$imgconfigoptions,$GLOBALS['xxConfig'],$cs.'configbutton'.($isbackorder?' configbackorder':($isinstock?'':' confignostock')),$thedetailslink, FALSE) . '</div>';
			else
				print strreplace('XXXECTCSPLACEHOLDERXXX',$cs,$isquickbuy?$atcmuqb:$atcmu);
		}elseif($layoutoption=='addtocartquant'){
			print '<div class="'.$cs.'addtocartquant prodaddtocartquant">';
			if($rs['pSchemaType']==1){
			}elseif($hasmultipurchase==2)
				print imageorbuttontag(@$imgconfigoptions,$GLOBALS['xxConfig'],$cs.'configbutton'.($isbackorder?' configbackorder':($isinstock?'':' confignostock')),$thedetailslink, FALSE);
			else
				print ($hasmultipurchase==0 ? '<div class="prodquantity">' . quantitymarkup($isquickbuy,$Count,FALSE,'',FALSE) . '</div>' : '') . strreplace('XXXECTCSPLACEHOLDERXXXaddtocart',$cs.'addtocart',$isquickbuy?$atcmuqb:$atcmu);
			print '</div>';
		}elseif(substr($layoutoption,0,6)=='custom'){
			if(trim_($rs['pCustom'.substr($layoutoption,6)])!='') print '<div class="'.$cs.'prodcustom'.substr($layoutoption,6).'">' . @$prodcustomlabel1 . $rs['pCustom'.substr($layoutoption,6)] . "</div>\n";
		}elseif(substr($layoutoption,0,7)=='include') pddinclude($layoutoption);
		elseif($layoutoption=='detaillink'){
			$GLOBALS['aria']=$GLOBALS['xxAriDet'] . $rs[getlangid("pName",1)];
			print '<div class="'.$cs.'detaillink ' . ($isquickbuy?'qb':'prod') . 'detaillink">' . imageorbutton(@$imgdetaillink,$rs['pSchemaType']==1 && @$GLOBALS['xxArDets']!='' ? $GLOBALS['xxArDets'] : $GLOBALS['xxPrDets'],$cs.'detaillink',$thedetailslink,FALSE) . "</div>\n";
		}elseif($layoutoption=='dateadded'){
			if(trim_($rs['pDateAdded'])!='') print '<div class="'.$cs.'proddateadded">' . (@$GLOBALS['xxDatLab']!=''?'<div class="'.$cs.'proddateaddedlabel">' . $GLOBALS['xxDatLab'] . '</div>':'') . '<div class="'.$cs.'proddateaddeddate">' . date($GLOBALS['dateformatstr'],strtotime($rs['pDateAdded'])) . "</div></div>\n";
		}elseif($layoutoption=='quickbuy'){
			if($hasmultipurchase==2)
				print '<div class="'.$cs.'qbuybutton">' . imageorbuttontag(@$imgconfigoptions,$GLOBALS['xxConfig'],$cs.'configbutton'.($isbackorder?' configbackorder':($isinstock?'':' confignostock')),$thedetailslink, FALSE) . '</div>';
			else{
				print '<div class="qbopaque" style="display:none" id="qbopaque'.$Count.'" onclick="if(event.target==this)closequickbuy('.$Count.')" tabindex="0">';
				print '<div class="qbuywrapper"><div class="scart scclose" role="img" onclick="closequickbuy('.$Count.')" title="'.$GLOBALS['xxClsWin'].'"></div>';
				displaylayoutarray($quickbuylayoutarray,TRUE);
				print '</div>';
				print '</div>';
				print '<div class="'.$cs.'qbuybutton">' . imageorbutton(@$imgquickbuybutton,$GLOBALS['xxQuiBuy'],$cs.'qbuybutton','displayquickbuy('.$Count.')',TRUE) . "</div>\n";
			}
		}elseif($layoutoption=='quantitypricing'){
			$numquantprices=0;
			$sSQL='SELECT '.$WSP.'pPrice,pbQuantity,'.($WSP!=''?'pbWholesalePercent AS ':'')."pbPercent FROM pricebreaks WHERE pbProdID='".escape_string($rs['pId'])."' ORDER BY pbQuantity";
			$result2=ect_query($sSQL) or ect_error();
			if(ect_num_rows($result2)>0){
				print '<div class="prodquantpricingwrap"><div class="prodquantpricing" style="display:table">';
				if(@$GLOBALS['xxQuaPri']!='') print '<div class="prodqpheading" style="display:table-caption">' . $GLOBALS['xxQuaPri'] . '</div>';
				print '<div class="prodqpheaders" style="display:table-row"><div class="prodqpheadquant" style="display:table-cell">' . $GLOBALS['xxQuanti'] . '</div><div class="prodqpheadprice" style="display:table-cell">' . $GLOBALS['xxPriQua'] . '</div></div>';
				while($rs2=ect_fetch_assoc($result2))
					$quantpricearray[$numquantprices++]=$rs2;
				for($index=0;$index<$numquantprices;$index++){
					if($index<$numquantprices-1){
						$nextquant=$quantpricearray[$index+1]['pbQuantity']-1;
						$nextquant=$nextquant>$quantpricearray[$index]['pbQuantity']?'-'.$nextquant:'';
					}else
						$nextquant='+';
					print '<div class="prodqprow" style="display:table-row"><div class="prodqpquant" style="display:table-cell">' . $quantpricearray[$index]['pbQuantity'] . $nextquant . '</div><div class="prodqpprice" style="display:table-cell">' . FormatEuroCurrency($quantpricearray[$index]['pbPercent']!=0?$rs['pPrice']-(($rs['pPrice']*$quantpricearray[$index]['pPrice'])/100):$quantpricearray[$index]['pPrice']) . '</div></div>';
				}
				print "</div></div>\n";
			}
			ect_free_result($result2);
		}elseif(trim_($layoutoption)!=''&&trim_($layoutoption)[0]=='<'){
			$layoutoption=str_replace(array('%pid%','%sku%'),array($rs['pId'],$rs['pSKU']),$layoutoptioncase);
			if($GLOBALS['wantmanufacturer']) $layoutoption=str_ireplace('%brand%',trim_($rs[getlangid('scName',131072)]),$layoutoption);
			if(preg_match('/%custom(\d+)%/',$layoutoption,$matchnum)){
				if($rs['pCustom' . $matchnum[1]]!='')$layoutoption=preg_replace('/%custom(\d+)%/',$rs['pCustom' . $matchnum[1]],$layoutoption);else continue;
			}
			print $layoutoption;
		}elseif(trim_($layoutoption)!='')
			print 'UNKNOWN LAYOUT OPTION:'.$layoutoption.'<br>';
	}
	$cs=$dlasavecs;
}
function displaysoftlogin(){
	global $redstar;
	$location='';
	if(strpos(@$_SERVER['REQUEST_URI'],'/cart'.$GLOBALS['extension'])!==FALSE||strpos(@$_SERVER['REQUEST_URI'],'/thanks'.$GLOBALS['extension'])!==FALSE) $location='cart'.$GLOBALS['extension'];
	if(strpos(@$_SERVER['REQUEST_URI'],$GLOBALS['customeraccounturl'])!==FALSE) $location=$GLOBALS['customeraccounturl'];
		if(@$GLOBALS['displaysoftlogindone']==''){ ?>
<script>
var sfextensionabs='php',
	xxPlsEntr="<?php print jscheck($GLOBALS['xxPlsEntr'])?>",xxValEm="<?php print jscheck($GLOBALS['xxValEm'])?>",xxRecapt="<?php print jscheck($GLOBALS['xxRecapt'])?>",xxEFEm="<?php print jscheck($GLOBALS['xxEFEm'])?>",
	xxEFNam="<?php print jscheck($GLOBALS['xxEFNam'])?>",xxEFCmt="<?php print jscheck($GLOBALS['xxEFCmt'])?>",xxContUs="<?php print jscheck($GLOBALS['xxContUs'])?>",xxAskQue="<?php print jscheck($GLOBALS['xxAskQue'])?>",xxCUBlur="<?php print jscheck($GLOBALS['xxCUBlur'])?>",
	xxEmFrnd="<?php print jscheck($GLOBALS['xxEmFrnd'])?>",xxEFBlr="<?php print jscheck($GLOBALS['xxEFBlr'])?>",xxAccSuc="<?php print jscheck($GLOBALS['xxAccSuc'])?>",xxMinLen="<?php print jscheck(strreplace('%s',6,$GLOBALS['xxMinLen']))?>",
	xxAQBlr="<?php print jscheck($GLOBALS['xxAQBlr'])?>",xxPwd="<?php print jscheck($GLOBALS['xxPwd'])?>",xxNow="<?php print jscheck($GLOBALS['xxNow'])?>",xxInSecs="<?php print jscheck($GLOBALS['xxInSecs'])?>",xxName="<?php print jscheck($GLOBALS['xxName'])?>",
	xxFulNam="<?php print jscheck($GLOBALS['xxFulNam'])?>",xxLOSuc="<?php print jscheck($GLOBALS['xxLOSuc'])?>",xxLISuc="<?php print jscheck($GLOBALS['xxLISuc'])?>",xxMesSuc="<?php print jscheck($GLOBALS['xxMesSuc'])?>";
var clientaddressoncreateacct=<?php print @$GLOBALS['clientaddressoncreateacct']?'true':'false'?>,extraclientfield1="<?php print jscheck(@$GLOBALS['extraclientfield1'])?>",extraclientfield2="<?php print jscheck(@$GLOBALS['extraclientfield2'])?>",
	extraclientfield1required=<?php print @$GLOBALS['extraclientfield1required']?'true':'false'?>,extraclientfield2required=<?php print @$GLOBALS['extraclientfield2required']?'true':'false'?>,
	loginhash='<?php print hash('sha256',$GLOBALS['adminSecret'] . 'ect admin login' . session_id())?>',
	customeraccounturl="<?php print jscheck($location)?>",
	recaptchasitekey='<?php print $GLOBALS['reCAPTCHAsitekey']?>',nacaptchawidgetid='',nacaptchaok=false,nacaptcharesponse=false,contactcaptchawidgetid='',contactcaptchaok=false,contactcaptcharesponse=false,askqproductid='',
	lastloginattempt,checkedfullname=false,contactusthanks="<?php print jscheck(@$GLOBALS['contactusthanks'])?>",emailfriendthanks="<?php print jscheck(@$GLOBALS['emailfriendthanks'])?>",askaquestionthanks="<?php print jscheck(@$GLOBALS['askaquestionthanks'])?>",
	recaptchaenabled2=<?php print recaptchaenabled(2)?'true':'false'?>,recaptchaenabled8=<?php print recaptchaenabled(8)?'true':'false'?>,nocustomerloginpwlimit=<?php print @$GLOBALS['nocustomerloginpwlimit']?'true':'false'?>,
	nomailinglist=<?php print @$GLOBALS['nomailinglist']?'true':'false'?>,
	storeurlssl="<?php print @$GLOBALS['storeurlssl']!=$GLOBALS['storeurl'] && ! (@$_SERVER['HTTPS']=='on' || @$_SERVER['SERVER_PORT']=='443') ? $GLOBALS['storeurlssl'] : ""?>",checkoutmode="<?php print jscheck(strip_tags(getpost('mode')))?>",
	clientloginref="<?php print jscheck(@$GLOBALS['clientloginref'])?>",clientloginref_sess="<?php print jscheck(@$_SESSION['clientloginref'])?>",
	loginrefurl=[];<?php
	for($index=0;$index<=10;$index++){
		eval('$lirefs=@$GLOBALS["clientloginref' . $index . '"];');
		if($lirefs!=''&&$lirefs!='referer') print 'loginrefurl[' . $index . "]='" . jsescape($lirefs) . "';";
	} ?>
</script>
<?php	print '<div id="softopaquediv" class="ectopaque" style="display:none" onclick="if(event.target==this)hideaccounts()" tabindex="0">';
			print '<div class="ectsoftwrapper"><div class="scart scclose" role="img" onclick="hideaccounts()" title="' . htmlspecials($GLOBALS['xxClsWin']) . '"></div>'."\n";
				print '<div style="display:none;text-align:center" id="ectsoftpreload"><img style="margin:30px" src="images/preloader.gif" alt="Loading" id="ectloadinggif" class="ectpreloader"><br><br><input style="font-size:16px" class="ectbutton" type="button" value="Pause" onclick="document.getElementById(\'ectloadinggif\').src=\'images/preloader.png\'"></div>'."\n";
				print '<div id="ectsfsuccess" class="ectsfsuccess"></div>'."\n";
				// ***** Contact Us / Ask a Question / Email Friend
				if(@$GLOBALS['useemailfriend']||@$GLOBALS['useaskaquestion']||@$GLOBALS['usecontactus']){
					print '<div class="sfcontact" id="ectcontactdiv" style="display:none">'."\n";
						print '<div class="softformheader" id="cuheader"></div>'."\n";
						print '<div id="contactblurb" class="contactblurb"></div>'."\n";
						print '<div class="ectsf2col"><div class="redstar">' . labeltxt($GLOBALS['xxEFNam'],'yourname') . '</div><div><input type="text" id="yourname" placeholder="' . placeholder($GLOBALS['xxEFNam']) . '" aria-required="true"></div></div>'."\n";
						print '<div class="ectsf2col"><div class="redstar">' . labeltxt($GLOBALS['xxEFEm'],'youremail') . '</div><div><input type="text" id="youremail" placeholder="' . placeholder($GLOBALS['xxEFEm']) . '" aria-required="true"></div></div>'."\n";
						// Only Email Friend
						if(@$GLOBALS['useemailfriend'])
							print '<div class="ectsf2col emfonly"><div class="redstar">' . labeltxt($GLOBALS['xxEFFEm'],'friendsemail') . '</div><div><input type="text" id="friendsemail" placeholder="' . placeholder($GLOBALS['xxEFFEm']) . '" aria-required="true"></div></div>'."\n";
						// Only Ask a Question
						if(@$GLOBALS['useaskaquestion']){
							for($index=1;$index<=9;$index++){
								eval('$askquestionparam=@$GLOBALS["askquestionparam'.$index.'"];');
								eval('$askquestionrequired=@$GLOBALS["askquestionrequired'.$index.'"];');
								eval('$askquestionhtml=@$GLOBALS["askquestionhtml'.$index.'"];');
								if($askquestionparam!=''){
									print '<div class="ectsf2col asqonly"><div' . ($askquestionrequired?' class="redstar"':'') . '>'."\n";
									if($askquestionrequired) print '<input type="hidden" id="asqreq'.$index.'" value="1">'."\n";
									print '<label id="asqtxt'.$index.'" for="askquestionparam'.$index.'" class="ectlabel">' . $askquestionparam . '</label></div><div>'."\n";
									if($askquestionhtml!='') print strreplace('ectfield','askquestionparam'.$index,$askquestionhtml); else print '<input type="text" id="askquestionparam'.$index.'" placeholder="' . placeholder($askquestionparam) . '"' . ($askquestionrequired?' aria-required="true"':'') . '>'."\n";
									print '</div></div>'."\n";
								}
							}
						}
						// Only Contact Us
						if(@$GLOBALS['usecontactus']){
							for($index=1;$index<=9;$index++){
								eval('$contactusparam=@$GLOBALS["contactusparam'.$index.'"];');
								eval('$contactusrequired=@$GLOBALS["contactusrequired'.$index.'"];');
								eval('$contactushtml=@$GLOBALS["contactushtml'.$index.'"];');
								if($contactusparam!=''){
									print '<div class="ectsf2col couonly"><div' . ($contactusrequired?' class="redstar"':'') . '>';
									if($contactusrequired) print '<input type="hidden" id="coureq'.$index.'" value="1">';
									print '<label id="coutxt'.$index.'" for="contactusparam'.$index.'" class="ectlabel">' . $contactusparam . '</label></div><div>'."\n";
									if($contactushtml!='') print strreplace('ectfield','contactusparam'.$index,$contactushtml); else print '<input type="text" id="contactusparam'.$index.'" placeholder="' . placeholder($contactusparam) . '"' . ($contactusrequired?' aria-required="true"':'') . '>'."\n";
									print '</div></div>'."\n";
								}
							}
						}
						// Comments
						print '<div class="ectsf2col"><div class="redstar">' . labeltxt($GLOBALS['xxEFCmt'],'yourcomments') . '</div><div><textarea class="softcomments" id="yourcomments" placeholder="' . placeholder($GLOBALS['xxEFCmt']) . '" aria-required="true"></textarea></div></div>'."\n";
						if(recaptchaenabled(2)){
							print '<div class="ectsf2col"><div></div><div id="contactcaptcha"></div>'."\n";
							displayrecaptchajs('contactcaptcha',FALSE,FALSE);
							print "</div>\n";
						}
						print '<div class="softformsend">' . imageorbuttontag('',$GLOBALS['xxSend'],'" id="contactsend','',TRUE) . imageorbuttontag('',$GLOBALS['xxClsWin'],'',"hideaccounts()",TRUE) . "</div>\n";
					print "</div>\n";
				}
				// ***** Login
				if(@$GLOBALS['enableclientlogin']){
					print '<div class="sflogin" id="loginacctdiv" style="display:none">'."\n";
						print '<div class="softformheader" id="liaccterrordiv">' . $GLOBALS['xxLiDets'] . "</div>\n";
						print '<div class="ectsf2col"><div class="redstar">' . labeltxt($GLOBALS['xxEmail'],'liemail') . '</div><div><input type="email" id="liemail" placeholder="' . placeholder($GLOBALS['xxEmail']) . '" aria-required="true" disabled></div></div>'."\n";
						print '<div class="ectsf2col"><div class="redstar">' . labeltxt($GLOBALS['xxPwd'],'lipass') . '</div><div><input type="password" id="lipass" placeholder="' . placeholder($GLOBALS['xxPwd']) . '" aria-required="true" autocomplete="off"></div></div>'."\n";
						print '<div class="ectsf2col"><div class="softformjright"><input type="checkbox" class="ectcheckbox" id="licook"></div><div>' . labeltxt($GLOBALS['xxRemLog'],'licook') . '</div></div>'."\n";
						print '<div class="softformsend">' . imageorbutton(@$GLOBALS['imgcartaccountlogin'],$GLOBALS['xxSubmt'],'cartaccountlogin" id="cartaccountlogin','checkloginaccount()',TRUE);
						if(@$GLOBALS['allowclientregistration']) print imageorbutton(@$GLOBALS['imgnewaccount'],$GLOBALS['xxNewAcc'],'newaccount',"displaynewaccount()",TRUE);
						print imageorbutton(@$GLOBALS['imgforgotpassword'],$GLOBALS['xxForPas'],'forgotpassword',$GLOBALS['customeraccounturl'].'?mode=lostpassword',FALSE) . "</div>\n";
					print "</div>\n";
				}
				// ***** New Account
				if(@$GLOBALS['allowclientregistration']){
					print '<div class="sfnewaccount" id="newacctdiv" style="display:none">'."\n";
						print '<div class="softformheader" id="accounterrordiv">' . $GLOBALS['xxNewAcc'] . "</div>\n";
						print '<div class="ectsf2col"><div class="redstar">' . labeltxt($GLOBALS['xxName'],'naname') . '</div><div><input type="text" id="naname" placeholder="' . placeholder($GLOBALS['xxName']) . '" aria-required="true"></div></div>'."\n";
						print '<div class="ectsf2col"><div class="redstar">' . labeltxt($GLOBALS['xxEmail'],'naemail') . '</div><div><input type="email" id="naemail" placeholder="' . placeholder($GLOBALS['xxEmail']) . '" aria-required="true"></div></div>'."\n";
						print '<div class="ectsf2col"><div class="redstar">' . labeltxt($GLOBALS['xxPwd'],'pass') . '</div><div><input type="password" id="pass" placeholder="' . placeholder($GLOBALS['xxPwd']) . '" autocomplete="off" aria-required="true"></div></div>'."\n";
						if(@$GLOBALS['extraclientfield1']!='' || @$GLOBALS['extraclientfield2']!=''){
							if(trim_(@$GLOBALS['extraclientfield1'])!='')
								print '<div class="ectsf2col"><div' . (@$GLOBALS['extraclientfield1required']?' class="redstar"':'') . '>' . labeltxt(@$GLOBALS['extraclientfield1'],"extraclientfield1") . '</div><div><input type="text" id="extraclientfield1" placeholder="' . placeholder($GLOBALS['extraclientfield1']) . '"' . (@$GLOBALS['extraclientfield1required']?' aria-required="true"':'') . '></div></div>'."\n";
							if(trim_(@$GLOBALS['extraclientfield2'])!='')
								print '<div class="ectsf2col"><div' . (@$GLOBALS['extraclientfield2required']?' class="redstar"':'') . '>' . labeltxt(@$GLOBALS['extraclientfield2'],"extraclientfield2") . '</div><div><input type="text" id="extraclientfield2" placeholder="' . placeholder($GLOBALS['extraclientfield2']) . '"' . (@$GLOBALS['extraclientfield2required']?' aria-required="true"':'') . '></div></div>'."\n";
						}
						if(!@$GLOBALS['nomailinglist']){
							print '<div class="ectsf2col">'."\n";
								print '<div class="softformjright"><input type="checkbox" class="ectcheckbox" id="allowemail" value="ON"' . (@$GLOBALS['allowemaildefaulton'] || getpost('allowemail')=='ON' ? ' checked="checked"' : '') . '></div>'."\n";
								print '<div>' . labeltxt($GLOBALS['xxAlPrEm'],'allowemail') . '<div class="cartacclogineverdivulge">' . $GLOBALS['xxNevDiv'] . '</div></div>'."\n";
							print "</div>\n";
						}
						if(recaptchaenabled(8)){
							print '<div class="ectsf2col"><div></div><div id="nacaptcha"></div>'."\n";
							displayrecaptchajs('nacaptcha',FALSE,FALSE);
							print "</div>\n";
						}
						print '<div class="softformsend">' . imageorbutton(@$GLOBALS['imgcreateaccount'],$GLOBALS['xxCrNwAc'],'createaccount','checknewaccount()',TRUE) . "</div>\n";
					print "</div>\n";
				}
			print "</div>\n";
		print "</div>\n";
		print '<script>document.body.appendChild(ectById("softopaquediv"));</script>';
	}
	$GLOBALS['displaysoftlogindone']=TRUE;
}
function checkrecaptcha(&$recaptchaerr){
	$_checkrecaptcha=FALSE;
	if(callcurlfunction('https://www.google.com/recaptcha/api/siteverify','secret=' . $GLOBALS['reCAPTCHAsecret'] . "&remoteip=" . $GLOBALS['REMOTE_ADDR'] . "&response=" . getpost("g-recaptcha-response"),$res,'',$recaptchaerr,FALSE)){
		$trcaptchaarray=json_decode($res);
		$_checkrecaptcha=@$trcaptchaarray->{'success'}=='true';
		$_recaptchaerr=@$trcaptchaarray->{'error-codes'};
		if($_recaptchaerr!='') $recaptchaerr='<div>' . implode('</div><div>',$_recaptchaerr) . '</div>';
		$recaptchaerr=strreplace('invalid-input-secret','Your reCaptcha Secret key is incorrect',$recaptchaerr);
		$recaptchaerr=strreplace('timeout-or-duplicate','The reCaptcha either timed out or was submitted twice. Please refresh the page and try again.',$recaptchaerr);
	}
	if(!$_checkrecaptcha && $recaptchaerr=='') $recaptchaerr=$GLOBALS['xxRecapt'];
	return($_checkrecaptcha);
}
$GLOBALS['hasdisplayedrecaptcha']=FALSE;
$GLOBALS['recaptchaunique']=1;
function displayrecaptchajs($recapid,$loadimmediately,$addunique){
	if($addunique){ $recapid.=$GLOBALS['recaptchaunique']; $GLOBALS['recaptchaunique']++; }
	if(! $GLOBALS['hasdisplayedrecaptcha']){
		print '<script>var recaptchaids=[];function recaptchaonload(){for(var recapi in recaptchaids){';
		print 'var restr=recaptchaids[recapi]+"widgetid=grecaptcha.render(\'"+recaptchaids[recapi]+"\',{\'sitekey\' : \'' . $GLOBALS['reCAPTCHAsitekey'] . '\',\'expired-callback\' : function(){"+recaptchaids[recapi]+"ok=false;},\'callback\' : function(response){"+recaptchaids[recapi]+"response=response;"+recaptchaids[recapi]+"ok=true;}});";';
		print 'eval(restr);';
		print '}}</script>';
		print '<script src="https://www.google.com/recaptcha/api.js?render=explicit&amp;onload=recaptchaonload"></script>';
	}
	$recaptchajs='var ' . $recapid . 'ok=false;function ' . $recapid . 'done(){' . $recapid . 'ok=true;}function ' . $recapid . 'expired(){' . $recapid . 'ok=false;}';
	if($loadimmediately) $recaptchajs.="recaptchaids.push('" . $recapid . "');";
	print '<script>' . $recaptchajs . '</script>';
	$GLOBALS['hasdisplayedrecaptcha']=TRUE;
}
function recaptchaenabled($recapid){
	return(($GLOBALS['reCAPTCHAuseon'] & $recapid)==$recapid && $GLOBALS['reCAPTCHAsitekey']!='' && $GLOBALS['reCAPTCHAsecret']!='');
}
function getcategoryurl($gcusectionid,$gcusectionname,$gcusectionurl,$gcurootsection){
	global $seocategoryurls,$seoprodurlpattern,$seocaturlpattern,$seomanufacturerpattern,$manufacturers;
	if(trim_($gcusectionurl)!=''){
		$saveseocategoryurls=$seocategoryurls;
		if(@$GLOBALS['noseostaticurls']) $seocategoryurls=FALSE;
		$thecatid=getcatid($gcusectionurl,@$seocategoryurls?$gcusectionurl:'',$gcurootsection==1?($manufacturers?$seomanufacturerpattern:$seoprodurlpattern):$seocaturlpattern);
		$seocategoryurls=$saveseocategoryurls;
		return $thecatid;
	}elseif($gcurootsection==1)
		return (!@$seocategoryurls?'products'.$GLOBALS['extension'].'?' . (@$manufacturers?'man':'cat') . '=':'') . getcatid($gcusectionid,$gcusectionname,$manufacturers?$seomanufacturerpattern:$seoprodurlpattern);
	else
		return (!@$seocategoryurls?'categories'.$GLOBALS['extension'].'?cat=':'') . getcatid($gcusectionid,$gcusectionname,$seocaturlpattern);
}
function getcarrierfromtrack($trackno,&$thelink){
	$carrier=$thelink='';
	$trackno=strreplace(' ','',trim_($trackno));
	if(preg_match('/^((\d{30})|(9\d{21})|(82\d{8})|(\w\w\d{9}US))$/', $trackno)>0)
		$carrier='usps';
	elseif(preg_match('/^1Z\w{16}$/', $trackno)>0)
		$carrier='ups';
	elseif(preg_match('/^((\d{12})|(\d{15})|(\d{20})|(\d{22}))$/', $trackno)>0)
		$carrier='fedex';
	elseif(preg_match('/^(\d{10})$/', $trackno)>0)
		$carrier='dhl';
	elseif(preg_match('/^\w\w\d{9}GB$/i', $trackno)>0)
		$carrier='royalmail';
	elseif(preg_match('/^\w\w\d{9}FR$/i', $trackno)>0)
		$carrier=@$GLOBALS['tracklapostewithswisspost']?'swisspost':'laposte';
	elseif(preg_match('/^\w\w\d{9}CH$/i', $trackno)>0)
		$carrier='swisspost';
	elseif(preg_match('/^\w\w\d{9}DE$/i', $trackno)>0)
		$carrier='deutschepost';
	elseif(preg_match('/^((\d{16})|(\w\w\d{9}\w\w)|(\w{13}CA))$/i', $trackno)>0)
		$carrier='canadapost';
	elseif(preg_match('/^(\d{14})$/', $trackno)>0){
		if($GLOBALS['origCountryID']==201)
			$carrier='dpdlocal';
		else
			$carrier='auspost';
	}
	if(@$GLOBALS['useinternaltrackinglink'])
		$thelink='tracking'.$GLOBALS['extension'].'?trackno=';
	else{
		if($carrier=='usps') $thelink='https://tools.usps.com/go/TrackConfirmAction.action?tRef=fullpage&tLc=1&text28777=&tLabels=';
		elseif($carrier=='ups') $thelink='https://wwwapps.ups.com/WebTracking/track?trackNums=';
		elseif($carrier=='fedex') $thelink='https://www.fedex.com/apps/fedextrack/?action=track&trackingnumber=';
		elseif($carrier=='dhl') $thelink=(@$GLOBALS['tracklink10digit']!=''?$GLOBALS['tracklink10digit']:'http://www.dhl.com/en/express/tracking.shtml?AWB=');
		elseif($carrier=='canadapost') $thelink='http://www.canadapost.ca/cpotools/apps/track/personal/findByTrackNumber?trackingNumber=';
		elseif($carrier=='auspost') $thelink='http://auspost.com.au/track/track.html?id=';
		elseif($carrier=='royalmail') $thelink='http://www.royalmail.com/portal/rm/track?trackNumber=';
		elseif($carrier=='laposte') $thelink='https://www.laposte.fr/outils/suivre-vos-envois?code=';
		elseif($carrier=='swisspost') $thelink='https://www.ordertracker.com/track/';
		elseif($carrier=='deutschepost') $thelink='https://www.ordertracker.com/track/';
		elseif($carrier=='dpdlocal') $thelink='https://www.dpdlocal.co.uk/apps/tracking/?reference=';
	}
	return($carrier);
}
function checkpricebreaks($cpbpid,$origprice,$hasoriginalid=FALSE,$cpb_orig_pid=''){
	global $WSP;
	$newprice='';
	if(!$hasoriginalid){
		$cpb_orig_pid='';
		$sSQL='SELECT cartOrigProdID FROM cart WHERE cartCompleted=0 AND ' . getsessionsql() . " AND cartProdID='".escape_string($cpbpid)."' AND cartOrigProdID<>'' AND cartOrigProdID IS NOT NULL";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			if(trim_($rs['cartOrigProdID'])!='') $cpb_orig_pid=trim_($rs['cartOrigProdID']);
		}
	}
	$sSQL='SELECT SUM(cartQuantity) AS totquant FROM cart WHERE cartCompleted=0 AND ' . getsessionsql() . " AND (cartProdID='".escape_string($cpbpid)."'" . ($cpb_orig_pid!=''?" OR cartOrigProdID='".escape_string($cpb_orig_pid)."'":'') . ")";
	$result=ect_query($sSQL) or ect_error();
	$rs=ect_fetch_assoc($result);
	if(is_null($rs['totquant'])) $thetotquant=0; else $thetotquant=$rs['totquant'];
	$sSQL='SELECT '.$WSP.'pPrice,'.($WSP!=''?'pbWholesalePercent AS ':'').'pbPercent FROM pricebreaks WHERE '.$thetotquant.">=pbQuantity AND (pbProdID='".escape_string($cpbpid)."'" . ($cpb_orig_pid!=''?" OR pbProdID='".escape_string($cpb_orig_pid)."'":'') . ") ORDER BY pbQuantity DESC";
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)) $thepricebreak=($rs['pbPercent']!=0?$origprice-(($origprice*$rs['pPrice'])/100):$rs['pPrice']); else $thepricebreak=$origprice;
	ect_free_result($result);
	$sSQL='UPDATE cart SET cartProdPrice='.round($thepricebreak,2).' WHERE cartCompleted=0 AND ' . getsessionsql() . " AND (cartProdID='".escape_string($cpbpid)."' OR cartOrigProdID='".escape_string($cpbpid)."') AND cartProdID<>'" . escape_string(@$GLOBALS['donationid']) . "' AND cartProdID<>'" . escape_string(@$GLOBALS['giftcertificateid']) . "'";
	ect_query($sSQL) or ect_error();
	$sSQL='SELECT cartID FROM cart WHERE cartCompleted=0 AND ' . getsessionsql() . " AND (cartProdID='".escape_string($cpbpid)."' OR cartOrigProdID='".escape_string($cpbpid)."')";
	$result2=ect_query($sSQL) or ect_error();
	while($rs2=ect_fetch_assoc($result2)){
		$sSQL='SELECT coCartOption FROM cartoptions WHERE coMultiply<>0 AND coCartID=' . $rs2['cartID'];
		$result3=ect_query($sSQL) or ect_error();
		if(ect_num_rows($result3)>0){
			$totaloptmultiplier=1;
			while($rs3=ect_fetch_assoc($result3)){
				if(is_numeric($rs3['coCartOption'])) $totaloptmultiplier*=(float)$rs3['coCartOption']; else $totaloptmultiplier=0;
			}
			$sSQL="UPDATE cart SET cartProdPrice=".round($thepricebreak*$totaloptmultiplier,2).' WHERE cartID=' . $rs2['cartID'] . " AND cartProdID<>'" . escape_string(@$GLOBALS['donationid']) . "' AND cartProdID<>'" . escape_string(@$GLOBALS['giftcertificateid']) . "'";
			ect_query($sSQL) or ect_error();
		}
		ect_free_result($result3);
	}
	ect_free_result($result2);
	return($thepricebreak);
}
function ipv6to4($theip){
	if(strpos($theip,':')===FALSE) return $theip;
	while(strpos($theip,'::')!==FALSE&&substr_count($theip,':')<7) $theip=preg_replace('/::/',':::',$theip,1);
	$iparr=explode(':',$theip);
	$iparr[0]=(hexdec(@$iparr[0]) ^ hexdec(@$iparr[2]) ^ hexdec(@$iparr[4]) ^ hexdec(@$iparr[6]));
	$iparr[1]=(hexdec(@$iparr[1]) ^ hexdec(@$iparr[3]) ^ hexdec(@$iparr[5]) ^ hexdec(@$iparr[7]));
	$ipv4=(((@$iparr[1]>>8)|240)&255).'.'.((@$iparr[0]>>8)&255).'.'.(@$iparr[1]&255).'.'.(@$iparr[0]&255);
	return $ipv4;
}
function dumpxmlout($sentxml,$recvdxml){
	print strreplace('<','<br>&lt;',strreplace('</','&lt;/',$sentxml)) . "\n<hr>\n";
	print strreplace('<','<br>&lt;',strreplace('</','&lt;/',$recvdxml)) . "<br>\n";
}
function breadcrumbselect($currlevel,$tlevel){
	if(@$_SESSION['clientID']!='' && @$_SESSION['clientLoginLevel']!='') $mll=$_SESSION['clientLoginLevel']; else $mll=0;
	$sSQL='SELECT sectionID,'.getlangid('sectionName',256).',rootSection,'.getlangid('sectionurl',2048).' AS sectionurl,'.getlangid('sectionHeader',524288)." FROM sections WHERE sectionDisabled<=" . $mll . " AND topSection='" . escape_string($tlevel) . "' ORDER BY ".(@$GLOBALS['sortcategoriesalphabetically']?getlangid('sectionName',256):'sectionOrder');
	$result2=ect_query($sSQL) or ect_error();
	$bcs='<select class="breadcrumbcats ectselectinput" size="1" onchange="ectgocheck(this[this.selectedIndex].value)">';
	while($rs2=ect_fetch_assoc($result2)){
		$caturl=getcategoryurl($rs2['sectionID'],$rs2[getlangid('sectionName',256)],$rs2['sectionurl'],$rs2['rootSection']);
		$bcs.='<option value="'.$caturl.'"';
		if($currlevel==$rs2['sectionID']){ $bcs.=' selected="selected"'; if(@$GLOBALS['currcaturl']=='') $GLOBALS['currcaturl']=$caturl; }
		$bcs.='>' . $rs2[getlangid('sectionName',256)] . '</option>';
	}
	ect_free_result($result2);
	return $bcs."</select>\n";
}
function stripnspecials($sptxt){
	return(htmlspecials(strip_tags($sptxt)));
}
function placeholder($sptxt){
	return(strip_tags($sptxt));
}
function microtime_ect_float(){
	list($usec, $sec) = explode(" ", microtime());
	return ((float)$usec + (float)$sec);
}
function notification_err_msg($tmsg){
	$sSQL="UPDATE admin SET adminDeviceNotifAlert='" . escape_string(trim_(substr($tmsg,0,200))) . "' WHERE adminID=1";
	ect_query($sSQL) or ect_error();
}
function ip2signedlong($ip){
	if(!$r=ip2long($ip)) return 0;
	if($r>2147483647) $r-=4294967296;
	return($r);
}
function ectsetcookie($name,$value='',$expires=0,$path='',$domain=''){ // deprecated
	if(headers_sent())
		print '<script src="vsadmin/savecookie.php?' . urlencode(htmlspecialsid($name)) . '=' . urlencode(htmlspecialsid($value)) . ($name=='PARTNER'?'&EXPIRES=' . $expires:'') . '"></script>';
	else
		setcookie($name,$value,$expires==0?0:time()+(60*60*24*(int)$expires),$path,$domain,@$_SERVER['HTTPS']=='on');
}
function setacookie($cname,$cval,$cdays){
	$thetimelim=$cdays!=0?time()+(60*60*24*$cdays):0;
	setcookie($cname,trim_($cval),$thetimelim,'/','',@$_SERVER['HTTPS']=='on',TRUE);
/*	if(PHP_VERSION_ID<70300){
		setcookie($cname,trim_($cval),$thetimelim,'/; samesite=strict','',@$_SERVER['HTTPS']=='on');
	}else{
		$options=array(
			"expires" => $thetimelim,
			"path" => '/',
			"secure" => @$_SERVER['HTTPS']=='on',
			"samesite" => "Strict");
		setcookie($cname,trim_($cval),$options);
	} */
}
if(@$_SESSION['httpreferer']=='' && @$_SERVER['HTTP_REFERER']!=''){
	$httpreferer=substr($_SERVER['HTTP_REFERER'], 0, 255);	
	if(strlen($httpreferer)>=255){
		$andpos=strrpos($httpreferer, '&');
		if($andpos > 0) $httpreferer=substr($httpreferer, 0, $andpos);
	}
	$_SESSION['httpreferer']=$httpreferer;
}
function stripUrlPath($url){
	$urlParts = parse_url($url);
	$newUrl = $urlParts['scheme'] . "://" . $urlParts['host'] . "/";
	return $newUrl;
}
function vrxmltag($tagname,$tagdata){
	return '<' . $tagname . '>' . htmlspecialchars($tagdata) . '</' . $tagname . '>';
}
function getstateorabbreviation($statename){
	$sSQL='SELECT stateAbbrev FROM states WHERE (stateCountryID=1 OR stateCountryID=2) AND ' . (is_numeric($statename) ? "stateID=" . $statename : "(stateName='" . escape_string($statename) . "' OR stateAbbrev='" . escape_string($statename) . "')");
	$result2=ect_query($sSQL) or ect_error();
	if($rs2=ect_fetch_assoc($result2)) $statename=$rs2['stateAbbrev'];
	ect_free_result($result2);
	return($statename);
}
function updateorderstatus($iordid, $ordstatus, $emailchanges){
	global $htmlemails,$yyTrackT,$ordstatusemail,$dateformatstr,$emlNl,$emailAddr,$ordstatussubject,$storeurl,$adminlangsettings,$languageid,$loyaltypoints,$giftcertificateid,$yyManAut;
	$ordauthno='';
	$oldordstatus=999;
	$payprovider=0;
	$ordClientID=0;
	$loyaltypointtotal=0;
	$savelangid=@$languageid;
	$replaceone=FALSE;
	if(is_numeric($iordid) && is_numeric($ordstatus)){
		$result=ect_query("SELECT ordStatus,ordAuthNumber,ordEmail,ordDate,".getlangid("statPublic",64).",ordStatusInfo,ordName,ordLastName,ordTrackNum,ordShipType,ordPayProvider,ordLang,ordClientID,loyaltyPoints,ordTotal,ordDiscount,ordInvoice,pointsRedeemed FROM orders INNER JOIN orderstatus ON orders.ordStatus=orderstatus.statID WHERE ordID=" . $iordid) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			$oldordstatus=$rs['ordStatus'];
			$ordauthno=$rs['ordAuthNumber'];
			$ordemail=$rs['ordEmail'];
			$orddate=strtotime($rs['ordDate']);
			$oldstattext=$rs[getlangid('statPublic',64)];
			$ordstatinfo=$rs['ordStatusInfo'];
			if(@$htmlemails==TRUE) $ordstatinfo=strreplace("\r\n", '<br>', $ordstatinfo);
			$ordername=trim_($rs['ordName'] . ' ' . $rs['ordLastName']);
			$trackingnum=trim_($rs['ordTrackNum']);
			$payprovider=$rs['ordPayProvider'];
			$languageid=$rs['ordLang']+1;
			$ordClientID=$rs['ordClientID'];
			$loyaltypointtotal=$rs['loyaltyPoints'];
			$ordTotal=$rs['ordTotal'];
			$ordDiscount=$rs['ordDiscount'];
			$ordInvoice=$rs['ordInvoice'];
			$pointsredeemed=$rs['pointsRedeemed'];
			$shipmethod=$rs['ordShipType'];
		}
		ect_free_result($result);
		$result=ect_query("SELECT ".getlangid("statPublic",64)." FROM orders INNER JOIN orderstatus ON orders.ordStatus=orderstatus.statID WHERE ordID=" . $iordid) or ect_error();
		if($rs=ect_fetch_assoc($result))
			$oldstattext=$rs[getlangid('statPublic',64)];
		ect_free_result($result);

		ect_query('UPDATE cart SET cartCompleted='.($ordstatus==2?0:1).' WHERE cartOrderID='.$iordid) or ect_error();
		if((@$GLOBALS['loyaltypointsnowholesale'] || @$GLOBALS['loyaltypointsnopercentdiscount']) && $ordClientID!=0){
			$sSQL="SELECT clActions FROM customerlogin WHERE clID=" . $ordClientID;
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				if(@$GLOBALS['loyaltypointsnowholesale'] && ($rs['clActions'] & 8)==8) $ordClientID=0;
				if(@$GLOBALS['loyaltypointsnopercentdiscount'] && ($rs['clActions'] & 16)==16) $ordClientID=0;
			}
			ect_free_result($result);
		}
		if($oldordstatus!=999 && ($oldordstatus<3 && $ordstatus>=3)){
			if($ordauthno=='') ect_query("UPDATE orders SET ordAuthNumber='". escape_string($yyManAut) . "' WHERE ordID=" . $iordid) or ect_error();
			$sSQL="SELECT cartProdId,cartProdName,cartProdPrice,cartQuantity,cartID FROM cart LEFT JOIN products ON cart.cartProdId=products.pID WHERE cartOrderID='" . escape_string($iordid) . "'";
			$result=ect_query($sSQL) or ect_error();
			while($rs=ect_fetch_assoc($result)){
				if($rs['cartProdId']==$giftcertificateid){
					$sSQL='UPDATE giftcertificate SET gcAuthorized=1,gcOrigAmount='.$rs['cartProdPrice'].',gcRemaining='.$rs['cartProdPrice'].' WHERE gcAuthorized=0 AND gcCartID=' . $rs['cartID'];
					ect_query($sSQL) or ect_error();
				}
			}
			ect_free_result($result);
			if(@$loyaltypoints!=''){
				$loyaltypointtotal=(int)(($ordTotal-$ordDiscount)*$loyaltypoints);
				ect_query("UPDATE orders SET loyaltyPoints=" . $loyaltypointtotal . " WHERE ordID=" . $iordid) or ect_error();
				if($ordClientID!=0) ect_query("UPDATE customerlogin SET loyaltyPoints=loyaltyPoints+" . $loyaltypointtotal . " WHERE clID=" . $ordClientID);
			}
		}elseif($oldordstatus!=999 && ($oldordstatus>=3 && $ordstatus<3)){
			ect_query("UPDATE giftcertificate SET gcAuthorized=0 WHERE gcOrderID=" . $iordid) or ect_error();
			if($ordClientID!=0 && @$loyaltypoints!='') ect_query("UPDATE customerlogin SET loyaltyPoints=loyaltyPoints-" . $loyaltypointtotal . " WHERE clID=" . $ordClientID);
		}
		if($oldordstatus!=999 && ($oldordstatus<2 && $ordstatus>=2)){
			if($ordClientID!=0) ect_query("UPDATE customerlogin SET loyaltyPoints=loyaltyPoints-" . $pointsredeemed . " WHERE clID=" . $ordClientID);
		}elseif($oldordstatus!=999 && ($oldordstatus>=2 && $ordstatus<2)){
			if($ordClientID!=0) ect_query("UPDATE customerlogin SET loyaltyPoints=loyaltyPoints+" . $pointsredeemed . " WHERE clID=" . $ordClientID);
		}
		if($oldordstatus!=999 && ($oldordstatus<=1 && $ordstatus>1) && (time()-$orddate) < (86400*365)) stock_subtract($iordid);
		if($oldordstatus!=999 && ($oldordstatus>1 && $ordstatus<=1) && (time()-$orddate) < (86400*365)){
			release_stock($iordid);
			if(@$GLOBALS['avalarastate']!=0&&@$GLOBALS['avalaraacctno']!=''&&$GLOBALS['avalaralicensekey']!=''){
				$avalarajson='{"refundTransactionCode":' . json_encode($iordid) . ',"refundDate":"' . gmdate("Y-m-d\TH:i:s+00:00") . '","refundType":"Full","referenceCode":"Refund"}';
				if(trim_($GLOBALS['avalaracompanyname'])=='') $GLOBALS['avalaracompanyname']='DEFAULT';
				$endpoint='https://' . (abs(@$GLOBALS['avalarastate'])!=2?'sandbox-':'') . 'rest.avatax.com/api/v2/companies/' . $GLOBALS['avalaracompanyname'] . '/transactions/' . $iordid . '/refund';
				avalaraheaders();
				if($success=callcurlfunction($endpoint,$avalarajson,$jres,'',$errormsg,FALSE)){
					if($GLOBALS['http_status']!=201){
						$jsarray=json_decode($jres);
						if(@$jsarray->{'error'}!=''){
							print '<div style="color:#F00;margin:20px;text-align:center">AvaTax Error: ' . @$jsarray->{'error'}->{'details'}[0]->{'description'} . '</div>';
						}
					}
				}
			}
		}
		if($oldordstatus!=(int)$ordstatus && $emailchanges && $ordstatus!=1){
			$result=ect_query("SELECT ".getlangid('statPublic',64).",emailstatus FROM orderstatus WHERE statID=" . $ordstatus);
			if($rs=ect_fetch_assoc($result)){
				$newstattext=$rs[getlangid('statPublic',64)];
				$emailstatus=($rs['emailstatus']!=0);
			}else
				$emailstatus=FALSE;
			ect_free_result($result);
			if(($adminlangsettings & 4096)==0) $languageid=1;
			if(@$ordstatussubject[$languageid]!='') $emailsubject=$ordstatussubject[$languageid]; else $emailsubject='Order status updated';
			$ose=$ordstatusemail[$languageid];
			$timestest=0;
			for($uoindex=0; $uoindex<=18; $uoindex++){
				$replaceone=TRUE;
				while($replaceone && $timestest++ < 30){
					$ose=replaceemailtxt($ose, '%statusid' . $uoindex . '%', $uoindex==$ordstatus ? '%ectpreserve%' : '', $replaceone);
				}
			}
			$ose=strreplace('%orderid%', $iordid, $ose);
			$ose=strreplace('%orderdate%', date($dateformatstr, $orddate) . ' ' . date('H:i', $orddate), $ose);
			$ose=strreplace('%oldstatus%', $oldstattext, $ose);
			$ose=strreplace('%newstatus%', $newstattext, $ose);
			$thetime=time() + ($GLOBALS['dateadjust']*60*60);
			$ose=strreplace('%date%', date($dateformatstr, $thetime) . ' ' . date('H:i', $thetime), $ose);
			$ose=strreplace('%ordername%', $ordername, $ose);
			$ose=strreplace('%shipmethod%', $shipmethod, $ose);
			$ose=replaceemailtxt($ose, '%statusinfo%', $ordstatinfo, $replaceone);
			if(strpos($ose, '%trackingnum%')!==FALSE){
				$sSQL="SELECT cartTrackNum FROM cart WHERE cartOrderID=".$iordid." AND cartTrackNum<>'' AND NOT (cartTrackNum IS NULL)";
				$result2=ect_query($sSQL) or ect_error();
				while($rs2=ect_fetch_assoc($result2)){
					$trackingnum.=($trackingnum!=''?',':'').$rs2['cartTrackNum'];
				}
				ect_free_result($result2);
			}
			$tracknumarr=explode(',', $trackingnum);
			foreach($tracknumarr as $key => $value){
				$ose=replaceemailtxt($ose, '%trackingnum%', $value, $replaceone);
			}
			while(strpos($ose, '%trackingnum%')!==FALSE){
				$ose=replaceemailtxt($ose, '%trackingnum%', '', $replaceone);
			}
			$ose=replaceemailtxt($ose, '%hastrackingnum%', $trackingnum!=''?'%ectpreserve%':'', $replaceone);
			$ose=replaceemailtxt($ose, '%invoicenum%', $ordInvoice, $replaceone);
			$reviewlinks=$norepeatlinks='';
			if(strpos($ose, '%reviewlinks%')!==FALSE){
				$sSQL="SELECT cartProdID,cartOrigProdID FROM cart WHERE cartOrderID=".$iordid;
				$result2=ect_query($sSQL) or ect_error();
				while($rs2=ect_fetch_assoc($result2)){
					if(trim_($rs2['cartOrigProdID'])!='') $cartprodid=$rs2['cartOrigProdID']; else $cartprodid=$rs2['cartProdID'];
					if(strpos($norepeatlinks,",'".$cartprodid."'")===FALSE){
						$norepeatlinks.=",'".$cartprodid."'";
						$sSQL="SELECT pID,".getlangid('pName',1).",pStaticPage,".getaltlang('pStaticURL',8388608).",pDisplay FROM products WHERE pDisplay<>0 AND pID='".escape_string($cartprodid)."'";
						$result=ect_query($sSQL) or ect_error();
						if($rs=ect_fetch_assoc($result)){
							$thelink=(@$GLOBALS['seodetailurls'] ? stripUrlPath($storeurl) : $storeurl) . getdetailsurl($rs['pID'],$rs['pStaticPage'],$rs[getlangid('pName',1)],$rs['pStaticURL'],'review=true','');
							if(@$htmlemails==TRUE) $thelink='<a href="' . $thelink . '">' . $GLOBALS['xxClkRep'] . $rs[getlangid('pName',1)] . '</a>';
							$reviewlinks.=$thelink . $emlNl;
						}
						ect_free_result($result);
					}
				}
				ect_free_result($result2);
			}
			$ose=replaceemailtxt($ose, '%reviewlinks%', $reviewlinks, $replaceone);
			$ose=strreplace(array('%nl%','<br>'), $emlNl, $ose);
			if($emailstatus!=0) dosendemail($ordemail, $emailAddr, '', strreplace('%orderid%',$iordid,$emailsubject), $ose);
		}
		if($oldordstatus!=(int)$ordstatus) ect_query("UPDATE orders SET ordStatus=" . $ordstatus . ",ordStatusDate='" . date("Y-m-d H:i:s", time() + ($GLOBALS['dateadjust']*60*60)) . "' WHERE ordID=" . $iordid) or ect_error();
	}
	$languageid=$savelangid;
}
function getstatetext($cntid){
	$gst=$GLOBALS['xxStaPro'];
	if($cntid==1)
		$gst=$GLOBALS['xxStateD'];
	elseif($cntid==2 || $cntid==175)
		$gst=$GLOBALS['xxProvin'];
	elseif($cntid==142 || $cntid==201)
		$gst=$GLOBALS['xxCounty'];
	return $gst;
}
$GLOBALS['hasdisplayedsvgicons']=FALSE;
function displayreviewicons(){
	if(! $GLOBALS['hasdisplayedsvgicons']){ ?>
	<svg style="display:none">
		<defs>
			<g id="review-icon-full"><svg xmlns="http://www.w3.org/2000/svg" shape-rendering="geometricPrecision" image-rendering="optimizeQuality" fill-rule="evenodd"><path d="M12 1.2l2.67 8.28 8.7-.02-7.04 5.1 2.7 8.27L12 17.68 4.98 22.8l2.7-8.27-7.04-5.1 8.7.02z"/></svg></g>
			<g id="review-icon-half"><svg xmlns="http://www.w3.org/2000/svg" shape-rendering="geometricPrecision" image-rendering="optimizeQuality" fill-rule="evenodd"><path d="M12 1.2l2.67 8.28 8.7-.02-7.04 5.1 2.7 8.27L12 17.68 4.98 22.8l2.7-8.27-7.04-5.1 8.7.02L12 1.2zm0 3.25v12l5.12 3.73-1.97-6.02 5.13-3.7-6.34.01L12 4.44z"/></svg></g>
			<g id="review-icon-empty"><svg xmlns="http://www.w3.org/2000/svg" shape-rendering="geometricPrecision" image-rendering="optimizeQuality" fill-rule="evenodd"><path d="M12 1.2l2.67 8.28 8.7-.02-7.04 5.1 2.7 8.27L12 17.68 4.98 22.8l2.7-8.27-7.04-5.1 8.7.02L12 1.2zm1.72 8.58L12 4.44l-1.94 6.02-6.34-.01 5.13 3.7-1.97 6.02L12 16.45l5.12 3.73-1.97-6.02 5.13-3.7-6.34.01-.22-.7z"/></svg></g>
		</defs>
	</svg>
<?php	$GLOBALS['hasdisplayedsvgicons']=TRUE;
	}
}
function addtogoogleanalyticsplist($dbrs,&$ao,$index){
	if($ao!='') $ao.=',';
	$ao.="{item_id:'" . jsescapel($dbrs['pId']) . "'," .
		"item_name:'" . jsescapel($dbrs[getlangid('pName',1)]) . "'," .
		'index:' . $index . ',';
	if($GLOBALS['wantmanufacturer'])
		if(trim_($dbrs[getlangid('scName',131072)])!='') $ao.="item_brand:'" . jsescapel($dbrs[getlangid('scName',131072)]) . "',";
	if(@$GLOBALS['catname']!='') $ao.="item_category:'" . jsescapel($GLOBALS['catname']) . "',";
		$ao.='price:' . jsescapel($dbrs['pPrice']) . '}';
}
function pddinclude($option){
	$incfile=explode(':',$option);
	include $incfile[1];
}
function strreplace($arg1,$arg2,$val){
	return str_replace($arg1,is_null($arg2) ? '' : $arg2,is_null($val) ? '' : $val);
}
function trim_($val){
	return is_null($val) ? '' : trim($val);
}
function substr_($val,$arg1,$arg2=null){
	return is_null($val) ? '' : substr($val,$arg1,$arg2);
}
function notfoundmarkup($notfoundtext,$isdetail){
	global $disabledsection,$prodid,$sSQL1,$sSQL2,$newqs,$usepnamefordetaillinks;
	if(!@$GLOBALS['nothrow404']) header('HTTP/1.1 404 Not Found');
	print '<form method="post" id="stextform" action="search' . $GLOBALS['extension'] . '"><input type="hidden" name="posted" value="1">';
	print '<div class="prodnoexist"><h1>'.$notfoundtext.'</h1></div>';
	print '<div class="notfoundremoved">' . $GLOBALS['xxPagNoA'] . '</div>';
	if($isdetail && $prodid!='' && ! $disabledsection){
		$sSQLx=$sSQL1.$sSQL2." OR ".getlangid('pStaticURL',8388608)."='".escape_string($prodid)."')";
		$result2=ect_query($sSQLx) or ect_error();
		if($rs2=ect_fetch_assoc($result2)){
			ob_end_clean();
			header('HTTP/1.1 301 Moved Permanently');
			header('Location: '.getfullurl(getdetailsurl($rs2['pId'],$rs2['pStaticPage'],$rs2[getlangid('pName',1)],$rs2['pStaticURL'],$newqs,@$GLOBALS['pathtohere'])));
			ect_free_result($result2);
			exit;
		}
		ect_free_result($result2);
		if(@$usepnamefordetaillinks&&getget('prod')!=''){
			$sSQL='SELECT pID,'.getlangid('pName',1).",pStaticPage,".getaltlang('pStaticURL',8388608)." FROM products WHERE pID='".escape_string(getget('prod'))."'";
			$result2=ect_query($sSQL) or ect_error();
			if($rs2=ect_fetch_assoc($result2)){
				ob_end_clean();
				header('HTTP/1.1 301 Moved Permanently');
				header('Location: '.getfullurl(getdetailsurl($rs2['pID'],$rs2['pStaticPage'],$rs2[getlangid('pName',1)],$rs2['pStaticURL'],$newqs,@$GLOBALS['pathtohere'])));
				ect_free_result($result2);
				exit;
			}
			ect_free_result($result2);
		}
		$sSQL='SELECT pId,pSection,'.getlangid('sectionName',256).','.getlangid('sectionurl',2048).',rootSection,sectionImage FROM products INNER JOIN sections ON products.pSection=sections.sectionID WHERE (' . (@$usepnamefordetaillinks && trim_(@$explicitid)==''?getlangid('pName',1):'pId') . "='" . escape_string($prodid) . "'" . (@$seodetailurls?" OR ".getlangid('pStaticURL',8388608)."='".escape_string($prodid)."'":'') . ')';
		$result2=ect_query($sSQL) or ect_error();
		if($rs2=ect_fetch_assoc($result2)){
			print '<div class="prodnoexistaltcat">';
				$caturl=getcategoryurl($rs2['pSection'],$rs2[getlangid('sectionName',256)],$rs2[getlangid('sectionurl',2048)],$rs2['rootSection']);
				if(trim_($rs2['sectionImage'])!=''){
					print '<div class="prodnoexistcatimg"><a class="ectlink" href="' . $caturl . '"><img src="' . $rs2['sectionImage'] . '" alt="' . $rs2[getlangid('sectionName',256)] . '" /></a></div>';
				}
				print '<div class="prodnoexistcat"><a class="ectlink" href="' . $caturl . '">' . $GLOBALS['xxSimPro'] . '</a></div>';
			print '</div>';
		}
		ect_free_result($result2);
	}
	print '<div class="notfoundtrysearch">' . $GLOBALS['xxSeSoEl'] . '</div>';
	print '<div class="notfoundinputcntnr"><div class="notfoundinput" style="position:relative"><input type="text" name="stext" id="stext" autocomplete="off" class="ecttextinput notfoundinput" size="20" maxlength="1024" value=""';
	if(!@$GLOBALS['noautosearch']) print 'onkeydown="return ectAutoSrchKeydown(this,event,\'php\')" onblur="ectAutoHideCombo(this)" autocapitalize="off" autocomplete="off" spellcheck="false" autocorrect="off"';
	print '>';
	if(@$GLOBALS['imgnotfoundsubmit']=='') $GLOBALS['imgnotfoundsubmit']='&#128269;';
	print '<button type="submit" class="notfoundsubmit">' . $GLOBALS['imgnotfoundsubmit'] . '</button>';
	if(!@$GLOBALS['noautosearch']) print '<div class="autosearch" style="position:absolute;display:none;" id="selectstext"></div>';
	print '</div></div>';
	if(@$GLOBALS['usecontactus']){
		displaysoftlogin();
		print '<div class="notfoundcontact">' . $GLOBALS['xxStNoFo'] . '</div>';
		print '<div class="notfoundcontactbutton">' . imageorbuttontag(@$GLOBALS['imgminicsscontact'],$GLOBALS['xxMCCoUs'],'notfoundcontactbutton',"displayectcontact('contactus','')",TRUE) . '</div>';
	}
	print '</form>';
}
function checkcrossentity($ischecked){
	if($ischecked) return '&check;';
	return '&cross;';
}
function paypalaccesstoken($ppuser,$pppass,$ppdemomode,$currtoken,&$errormsg){
	$access_token='';
	$expires_in='';
	if(trim_($currtoken)!=''){
		$token_arr=explode(':',$currtoken);
		$access_token=$token_arr[0];
		$expires_in=(int)$token_arr[1];
	}
	if($access_token!=''&&is_numeric($expires_in)){
		if($expires_in>time()){
			return $access_token;
		}else
			$access_token='';
	}
	$GLOBALS['xmlfnheaders']=array("Authorization: Basic ".base64_encode($ppuser.':'.$pppass),'Content-Type: application/json','PayPal-Partner-Attribution-Id: EcommerceTemplates_Ecom_PPCP');
	$GLOBALS['callxmlfunctionforcemethod']='POST';
	if(callcurlfunction('https://api-m.' . ($ppdemomode?'sandbox.':'') . 'paypal.com/v1/oauth2/token','grant_type=client_credentials',$jres,'',$errormsg,FALSE)){
		$jsarray=json_decode((string)$jres);
		$access_token=@$jsarray->{'access_token'};
		$expires_in=@$jsarray->{'expires_in'};
		$sSQL="UPDATE payprovider SET payProvData6='" . escape_string($access_token . ':' . (time()+$expires_in)) . "' WHERE payProvID=27";
		ect_query($sSQL) or ect_error();
	}
	return $access_token;
}
function avalaraheaders(){
	$GLOBALS['xmlfnheaders']=array("Authorization: Basic " . base64_encode($GLOBALS['avalaraacctno'].":".$GLOBALS['avalaralicensekey']),"Content-Type: application/json", "X-Avalara-Client: Ecommerce Templates;a0oUz00000036SHIAY");
}
function checkminicssuserblock(){
	$multiemfblocked=FALSE;
	$theip=$GLOBALS['REMOTE_ADDR'];
	if($theip=='') $theip='none';
	if($GLOBALS['blockcontactemails']!=0){
		ect_query("DELETE FROM multibuyblock WHERE lastaccess<'" . date('Y-m-d H:i:s', time()-(60*60*24)) . "'") or ect_error();
		$sSQL="SELECT ssdenyid,sstimesaccess FROM multibuyblock WHERE ssdenyip='EMF " . trim(escape_string($theip)) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			ect_query("UPDATE multibuyblock SET sstimesaccess=sstimesaccess+1,lastaccess='" . date('Y-m-d H:i:s', time()) . "' WHERE ssdenyid=" . $rs['ssdenyid']) or ect_error();
			if($rs['sstimesaccess']>=$GLOBALS['blockcontactemails']) $multiemfblocked=TRUE;
		}else{
			ect_query("INSERT INTO multibuyblock (ssdenyip,lastaccess) VALUES ('EMF " . trim(escape_string($theip)) . "','" . date('Y-m-d H:i:s', time()) . "')") or ect_error();
		}
		ect_free_result($result);
	}
	if($theip=='none' || ip2long($theip)==FALSE)
		$sSQL='SELECT dcid FROM ipblocking LIMIT 0,1';
	else
		$sSQL='SELECT dcid FROM ipblocking WHERE (dcip1=' . ip2long($theip) . ' AND dcip2=0) OR (dcip1 <= ' . ip2long($theip) . ' AND ' . ip2long($theip) . ' <= dcip2 AND dcip2 <> 0)';
	$result=ect_query($sSQL) or ect_error();
	if(ect_num_rows($result) > 0)
		$multiemfblocked=TRUE;
	return($multiemfblocked);
}
?>