<?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
if(!@$GLOBALS['incfunctionsdefined']){print 'No incfunctions.php file';exit;}
global $grandtotal,$packdims,$estimateshipping,$splitUSZones,$adminLocale,$countryCurrency,$countryNumCurrency,$useEuro,$storeurl,$storeurlssl,$useStockManagement,$adminProdsPerPage,$stateTax,$countryTax,$stateTaxRate,$countryTaxRate,$delccafter,$homeCountryTaxRate,
$handling,$handlingchargepercent,$adminCanPostUser,$packtogether,$origZip,$destZip,$shipType,$adminIntShipping,$origCountry,$origCountryCode,$origCountryID,$uspsUser,$upsUser,$upsPw,$upsAccess,$upsAccount,$upsnegdrates,$fedexaccount,$paypalcheckoutexpress,
$fedexmeter,$fedexuserkey,$fedexuserpwd,$adminUnits,$emailAddr,$sendEmail,$adminTweaks,$adminlanguages,$adminlangsettings,$currRate1,$currSymbol1,$currRate2,$currSymbol2,$currRate3,$currSymbol3,$currConvUser,$currConvPw,$data1,$data2,$data3,$data4,$data5,$data6,$ppmethod,$demomode,
$currLastUpdate,$adminSecret,$cardinalprocessor,$cardinalmerchant,$cardinalpwd,$catalogroot,$adminAltRates,$prodfilter,$prodfiltertext,$dosortby,$sortoptions,$DHLSiteID,$DHLSitePW,$DHLAccountNo,$adminShipping,$storelang,$multipurchaseblockmessage,
$numaddresses,$addresses,$maxshipoptions,$somethingToShip,$fromshipselector,$willpickup_,$intShipping,$shipcountry,$shipstate,$shipStateAbbrev,$splitUSZones,$shiphomecountry,$shipCountryID,$returntocustomerdetails,$errormsg,$success,$redstar,
$hasstates,$allcountries,$numallcountries,$zipoptional,$forceloginonhttps,$quantity,$outofstockarr,$discountarray,$numdiscountarray,$giftcertificateid,$donationid,$giftwrappingid,$loyaltypointsavailable,$loyaltypointvalue,$minloglevel,$addedprods,$numaddedprods,$thepprice,$nocarrierinsurancerates,
$theid,$customeraccounturl,$thesessionid,$showtaxinclusive,$totalgoods,$shipping,$totaldiscounts,$freeshipamnt,$loyaltypointdiscount,$ordPayProvider,$selectedshiptype,$shipselectoraction,$altrate,$checkoutmode,$multipleoptions,$shipinsurancemin,
$numshiprate,$ordName,$ordLastName,$ordAddress,$ordAddress2,$ordCity,$ordState,$ordZip,$ordCountry,$countryCode,$ordEmail,$ordEmail2,$ordPhone,$ordShipName,$ordShipLastName,$ordShipAddress,$ordShipAddress2,$ordShipCity,$ordShipState,$optarray,$estimate,$packnumber,
$ordShipZip,$ordShipCountry,$ordShipPhone,$ordPayProvider,$ordComLoc,$ordExtra1,$ordExtra2,$ordShipExtra1,$ordShipExtra2,$ordCheckoutExtra1,$ordCheckoutExtra2,$ordAffiliate,$ordAVS,$ordCVV,$ordAddInfo,$insidedelivery_,$shipinsurancepercent,$freeshipmethodexists,
$commercialloc_,$wantinsurance_,$saturdaydelivery_,$signaturerelease_,$numshiprateingroup,$orighandling,$taxHandling,$orighandlingpercent,$freeshippingapplied,$freeshippingincludeshandling,$freeshippingincludesservices,$handlingeligableitem,$freeshipavailtodestination,
$handlingeligablegoods,$mobilebrowser,$currShipType,$selectedshiptype,$royalmail,$allfreeshipexempt,$nodiscounts,$usehst,$stockwarning,$backorder,$shipMethod,$numshipoptions,$WSP,$OWSP,$numshipdiscountexempt,$iTotItems,$addshippinginsurance,$packageweight,$packagefreeexemptweight,
$cpnmessage,$cpnerror,$orderid,$shipCountryCode,$listid,$displaylistid,$cartlistnumber,$gotcpncode,$rgcpncode,$statetaxfree,$countrytaxfree,$shipfreegoods,$shipdiscountexempt,$shippingtax,$totalquantity,$appliedcouponamount,$numoptions,$cartrefreshseconds;
if(@$cartisincluded!=TRUE){
	if(@$GLOBALS['iswordpress']){
		include ABSPATH . '/vsadmin/inc/uspsshipping.php';
		include ABSPATH . '/vsadmin/inc/incemail.php';
	}else{
		include './vsadmin/inc/uspsshipping.php';
		include './vsadmin/inc/incemail.php';
	}
}
if(getget('action')=='opayo'&&getget('reason')!=''){
	print '<script>if(top.location!=location)top.location.href = document.location.href;</script>';
	$GLOBALS['xxCoStp1']='<div class="ectwarning" style="text-align:center;font-size:16px;margin:25px 0">' . htmlspecials(strip_tags(getget('reason'))) . '</div>';
}
if(@$GLOBALS['xxHasDel']=='')$GLOBALS['xxHasDel']='Some of the items in your cart have been deleted and must be removed before you can continue.';
$demomode=FALSE;
$maxshipoptions=40;
$allfreeshipexempt=$success=$shiphomecountry=TRUE;
$packnumber=1;
$GLOBALS['uspsuseoauth']=$GLOBALS['upsuseoauth']=$GLOBALS['termscontentregion']=$fromshipselector=$nodiscounts=$usehst=$multipleoptions=$stockwarning=$backorder=$cartEmpty=$handlingeligableitem=$noshowcart=$isavsmismatch=$includebraintree=FALSE;
$willpickup_=$insidedelivery_=$commercialloc_=$wantinsurance_=$saturdaydelivery_=$signaturerelease_=$hasstates=$returntocustomerdetails=$minquantityerror=$deleteditemerror=FALSE;
$shipping=$iTotItems=$stateTaxRate=$countryTax=$stateTax=$outofstockcnt=$numallcountries=$ordComLoc=$numdiscountarray=0;
$GLOBALS['cartrows']=[];
$alldata=$shipMethod=$WSP=$OWSP=$appliedcouponname=$ordAVS=$ordCVV=$stateAbbrev=$international=$cpnerror=$shipselectoraction=$altrate=$shipstate=$shipstateid=$errormsg=$centinelok='';
$cpnmessage='<br>';
$GLOBALS['itemsincart']=$GLOBALS['countrytaxthreshold']=$appliedcouponamount=$totalquantity=$statetaxfree=$countrytaxfree=$shipfreegoods=$shipdiscountexempt=$numshipdiscountexempt=$totalgoods=$handlingeligablegoods=$shippingtax=0;
$paypalcheckoutexpress=$freeshippingincludeshandling=$freeshippingincludesservices=$somethingToShip=$freeshippingapplied=$warncheckspamfolder=$homecountry=$gotcpncode=$freeshipmethodexists=FALSE;
$errordname=$errordaddress=$errordcity=$errordstate=$errordshipstate=$errordcountry=$errordzip=$errordphone=$errordemail=$errordemailv=$errtermsandconditions=$errordshipaddress=$errordshipcountry=FALSE;
$packageweight=$packagefreeexemptweight=$addshippinginsurance=$selectedshiptype=$numshipoptions=$freeshipamnt=$rowcounter=$stockrelitems=$thePQuantity=$thepweight=$grandtotal=$totaldiscounts=$giftcertsamount=$loyaltypointdiscount=0;
$destZip=$payerid=$rgcpncode=$token=$analyticsoutput=$ordShipName=$ordShipLastName=$ordShipAddress=$ordShipAddress2=$ordShipCity=$ordShipState=$ordShipZip=$ordShipPhone=$ordShipCountry=$ordAffiliate=$ordAddInfo=$ordExtra1=$ordExtra2=$ordShipExtra1=$ordShipExtra2=$ordCheckoutExtra1=$ordCheckoutExtra2='';
$outofstockarr=array();
if(@$checkoutmode=='')$checkoutmode='';
$GLOBALS['alreadygotadmin']=getadminsettings();
if(@$GLOBALS['nopriceanywhere']){ $adminAltRates=0; $estimateshipping=FALSE; }
if($GLOBALS['adminAltRates']>0){
	$result=ect_query('SELECT altrateid FROM alternaterates WHERE usealtmethod<>0 ORDER BY altrateorder') or ect_error();
	if($rs=ect_fetch_assoc($result)) $shipType=$rs['altrateid'];
	ect_free_result($result);
	$result=ect_query('SELECT altrateid FROM alternaterates WHERE usealtmethodintl<>0 ORDER BY altrateorderintl') or ect_error();
	if($rs=ect_fetch_assoc($result)) $adminIntShipping=$rs['altrateid'];
	ect_free_result($result);
}
$homeCountryTaxRate=$countryTaxRate;
if(@$GLOBALS['zipposition']==''){
	$GLOBALS['zipposition']=1;
	if($origCountryID==65) $GLOBALS['zipposition']=2;
	if($origCountryID==133) $GLOBALS['zipposition']=4;
}
if(@$GLOBALS['xxAuNetR']=='') $GLOBALS['xxAuNetR']='Thank you! Your order has been received and for security reasons is currently being reviewed. We will be in touch as soon as possible!';
if(@$GLOBALS['xxChoIns']=='') $GLOBALS['xxChoIns']='Please choose if you would like to add shipping insurance';
if(@$cartisincluded!=TRUE){
	if(@$_SERVER['CONTENT_LENGTH']!='' && $_SERVER['CONTENT_LENGTH']>100000) exit;
	$cartisincluded=FALSE;
	$rgcpncode=str_replace(array("'",'"'),'',strip_tags(getrequest('cpncode')));
	if(stripos((is_null(@$_SESSION['cpncode'])?'':@$_SESSION['cpncode']), $rgcpncode . ' ')!==FALSE || stripos((is_null(@$_SESSION['giftcerts'])?'':@$_SESSION['giftcerts']), $rgcpncode . ' ')!==FALSE) $rgcpncode='';
	if($rgcpncode!=''){ // Check for gift certs
		$sSQL="SELECT gcID FROM giftcertificate WHERE gcRemaining>0 AND gcAuthorized<>0 AND gcID='" . escape_string($rgcpncode) . "'";
		$result=ect_query($sSQL) or ect_error();
		while($rs=ect_fetch_assoc($result)){
			if(strpos(@$_SESSION['giftcerts'], $rs['gcID'] . ' ')===FALSE) @$_SESSION['giftcerts'].=$rs['gcID'] . ' ';
			$rgcpncode='';
		}
		ect_free_result($result);
	}
	if($rgcpncode!=''){
		if(trim_(@$_SESSION['cpncode'])!='') $cpnerror=$GLOBALS['xxCanApp'] . ' ' . $rgcpncode . '. ' . $GLOBALS['xxOnOnCp'] . '<br>'; else @$_SESSION['cpncode']=trim($rgcpncode) . ' ';
	}
	$rgcpncode=trim_(@$_SESSION['cpncode']);
	if(getpost('payerid')!='') $payerid=getpost('payerid'); else $payerid='';
	$token=getrequest('token');
	if(str_replace(array("'",'"'),'',strip_tags(getpost('sessionid')))!='') $thesessionid=str_replace(array("'",'"'),'',strip_tags(getpost('sessionid'))); else $thesessionid=getsessionid();
	$theid=escape_string(getpost('id'));
	if(getget('mode')=='checkout')$checkoutmode=getget('mode'); else $checkoutmode=getpost('mode');
	$_SESSION['commercialloc_']=$commercialloc_=(getpost('commercialloc')=='Y');
	$_SESSION['wantinsurance_']=$wantinsurance_=(getpost('wantinsurance')=='Y');
	$_SESSION['saturdaydelivery_']=$saturdaydelivery_=(getpost('saturdaydelivery')=='Y');
	$_SESSION['signaturerelease_']=$signaturerelease_=(getpost('signaturerelease')=='Y');
	$insidedelivery_=(getpost('insidedelivery')=='Y');
	$_SESSION['willpickup_']=$willpickup_=(getpost('willpickup')=='Y');
	$ordPayProvider=getpost('payprovider');
	if(! is_numeric($ordPayProvider)) $ordPayProvider='';
	if(getget('token')!='' && $ordPayProvider=='') $ordPayProvider=19;
	if(getget('action')=='paypalcancel') $checkoutmode='paypalcancel';
	if(getget('action')=='termpp'&&getget('paymentID')!='') $checkoutmode='go';
	$shipselectoraction	= getpost('shipselectoraction');
	if(getpost('shipselectoraction')=='selector') $fromshipselector=TRUE;
	if(getpost('noredeempoints')=='1') $_SESSION['noredeempoints']=TRUE;
	if(is_numeric(getpost('altrates'))) $altrate=(int)getpost('altrates');

	$sSQL="SELECT contentData FROM contentregions WHERE contentName='termsandconditions'";
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		$GLOBALS['termscontentregion']=TRUE;
		$GLOBALS['termsandconditions']=TRUE;
	}
	ect_free_result($result);
}
if(getget('sharecart')!=''&&getget('key')!=''&&getget('list')!=''){
	$mykey=base64_encode(hash_hmac('sha256', getget('sharecart') . 'this is a saved cart' . getget('list'), $GLOBALS['adminSecret'], true));
	if($mykey==getget('key')){
		if(getget('sharecart')==@$_SESSION['clientID']){
			print '<div style="text-align:center;padding:10px;margin-bottom:10px;border:1px solid red">The source and destination carts are the same</div>';
		}else{
			$sSQL="UPDATE cart SET cartSessionID='" . escape_string($thesessionid) . "', cartClientID='" . (@$_SESSION['clientID']!='' ? escape_string($_SESSION['clientID']) : 0) . "' WHERE cartID IN (" . escape_string(getget('list')) . ") AND cartClientID='" . escape_string(getget('sharecart')) . "' AND cartCompleted=0 AND cartDateAdded>='" . date('Y-m-d', time() - (60*60*24*3)) . "'";
			ect_query($sSQL) or ect_error();
			print '<div class="cartcopiedok" style="text-align:center;padding:10px;margin-bottom:10px;border:1px solid grey">' . $GLOBALS['xxCaCoOK'] . '</div>';
		}
	}
}
if(is_numeric(getget('acartid')) && getget('acarthash')!=''){
	$sSQL="SELECT aceID FROM abandonedcartemail WHERE aceOrderID='" . escape_string(getget('acartid')) . "' AND aceKey='" . escape_string(getget('acarthash')) . "'";
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		ect_query("UPDATE cart SET cartSessionID='" . escape_string($thesessionid) . "' WHERE cartOrderID=" . getget('acartid') . " AND cartCompleted=0") or ect_error();
		ect_query("UPDATE orders SET ordSessionID='" . escape_string($thesessionid) . "' WHERE ordID=" . getget('acartid') . " AND ordStatus=2 AND ordAuthNumber=''") or ect_error();
		setacookie('ectordid',getget('acartid'),0);
		setacookie('ectsessid',$thesessionid,0);
		setacookie('ecthash',hash('sha256',getget('acartid').$thesessionid.$adminSecret),0);
	}
	ect_free_result($result);
}
$amazonpayment=$paypalexpress=FALSE;
get_wholesaleprice_sql();
$thefrompage=strip_tags(getget('rp')!='' ? getget('rp') : trim_(@$_SERVER['HTTP_REFERER']));
if(getget('rp')==''){
	$pu=parse_url($thefrompage);
	if(@strpos(strtolower($storeurl), str_replace('www.','',@$pu['host']))===FALSE) $thefrompage='';
}
if(strpos(strtolower($thefrompage),'javascript:')!==FALSE||strpos(strtolower($thefrompage),'/cart')!==FALSE||strpos(strtolower($thefrompage),'/thanks')!==FALSE) $thefrompage='';
if(@$_SESSION['clientID']!='' && @$_SESSION['clientLoginLevel']!='') $minloglevel=$_SESSION['clientLoginLevel']; else $minloglevel=0;
$countryTax=0; // At present both countryTaxRate and countryTax are set in incfunctions
$origShipType=$shipType;
$orighandling=$handling;
$orighandlingpercent=$handlingchargepercent;
if(!isset($GLOBALS['useimageincart'])) @$GLOBALS['useimageincart']=TRUE;
if(!isset($GLOBALS['linkcartproducts'])) @$GLOBALS['linkcartproducts']=TRUE;
function displayintshipping(){
	global $intShipping;
	/*	0 = Name
		1 = Delivery
		2 = Cost
		3 = Used
		4 = FSA
		5 = Service ID (USPS)
		6 = shipType
		7 = Cost for Free Ship Exempt
		8 = Cost for Insurance + Services
	*/
	print '<div style="display:table">';
		print '<div class="receipttotalsrow"><div style="display:table-cell">Name</div><div style="display:table-cell">Delivery</div><div style="display:table-cell">Cost</div><div style="display:table-cell">Used</div><div style="display:table-cell">FSA</div><div style="display:table-cell">Service&nbsp;ID</div><div style="display:table-cell">shipType</div><div style="display:table-cell">Cost&nbsp;for&nbsp;FSA</div><div style="display:table-cell">Ins+Services</div></div>'."\n";
		for($indexmso=0; $indexmso<$GLOBALS['maxshipoptions']; $indexmso++){
			if($intShipping[$indexmso][3]){
				print '<div class="receipttotalsrow">';
				for($indexint=0;$indexint<9;$indexint++)
					print '<div style="display:table-cell">' . str_replace(' ','&nbsp;',$intShipping[$indexmso][$indexint]) . '</div>';
				print '</div>'."\n";
			}
		}
	print '</div>'."\n";
}
function getcartforganalytics($gcartid){
	$ao='';
	$index=1;
	$sSQL='SELECT cartID,cartProdID,cartProdName,cartProdPrice,cartQuantity,pManufacturer,sectionName,scName FROM cart INNER JOIN products ON cart.cartProdID=products.pID INNER JOIN sections ON products.pSection=sections.sectionID LEFT JOIN searchcriteria ON products.pManufacturer=searchcriteria.scID WHERE ' . ($gcartid!=''?'cartID='.$gcartid.' AND ':'') . 'cartCompleted=0 AND ' . getsessionsql() . ' ORDER BY cartDateAdded';
	$result=ect_query($sSQL) or ect_error();
	while($rs=ect_fetch_assoc($result)){
		$brand=trim_($rs['scName']);
		if($ao!='') $ao.=',';
		$ao.="{item_id:'" . jsescapel($rs['cartProdID']) . "',item_name:'" . jsescapel($rs['cartProdName']) . "',index:" . $index++ . ',';
		if($brand!='') $ao.="item_brand:'" . jsescapel($brand) . "',";
		$ao.="item_category:'" . jsescapel($rs['sectionName']) . "',price:" . jsescapel($rs['cartProdPrice']) . '}';
	}
	return $ao;
}
function getstatefromid($tstate){
	if(is_numeric($tstate)){
		$sSQL="SELECT stateName,stateAbbrev,stateCountryID FROM states WHERE stateID='" . escape_string($tstate) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)) $tstate=@$GLOBALS['usestateabbrev'] && ($rs['stateCountryID']==1 || $rs['stateCountryID']==2) ? $rs['stateAbbrev'] : $rs['stateName'];
		ect_free_result($result);
	}
	return $tstate;
}
function getidfromstate($tstate,$statecountry){
	$tstateid='';
	$sSQL="SELECT stateID FROM states WHERE stateEnabled<>0 AND stateCountryID='" . escape_string($statecountry) . "' AND (stateName='" . escape_string($tstate) . "'" . (($statecountry==1||$statecountry==2) ? " OR stateAbbrev='" . escape_string($tstate) . "')" : ')');
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)) $tstateid=$rs['stateID'];
	ect_free_result($result);
	return $tstateid;
}
function gettermsjsfunction(){
		if($GLOBALS['termscontentregion']){ ?>
function closetandc(){
	document.getElementById('ecttncdiv').parentNode.removeChild(document.getElementById('ecttncdiv'));
	return false;
}
function doprintterms(){
	var stylesheetlist='';
	if(document.styleSheets){
		for(var dpci=0;dpci<document.styleSheets.length;dpci++){
			if(document.styleSheets[dpci].href){
				stylesheetlist+='<link rel="stylesheet" type="text/css" href="'+document.styleSheets[dpci].href+'" />\n';
			}
		}
	}
	var prnttext='<html><head>'+stylesheetlist+'</head><body onload="window.print()">\n';
	prnttext+=document.getElementById('ecttermsandconds').outerHTML+"\n";
	prnttext+='</body></'+'html>\n';
	var newwin=window.open("","printit",'menubar=no, scrollbars=yes, width=600, height=450, directories=no,location=no,resizable=yes,status=no,toolbar=no');
	newwin.document.open();
	newwin.document.write(prnttext);
	newwin.document.close();
}
<?php	}
		print "function showtermsandconds(){\r\n";
		if($GLOBALS['termscontentregion']||@$GLOBALS['isectstore']){ ?>
ecttncdiv=document.createElement('div');
ecttncdiv.setAttribute('id','ecttncdiv');
ecttncdiv.style.zIndex=1000;
ecttncdiv.style.position='fixed';
ecttncdiv.style.width='100%';
ecttncdiv.style.height='100%';
ecttncdiv.style.top='0px';
ecttncdiv.style.left='0px';
ecttncdiv.style.backgroundColor='rgba(140,140,150,0.5)';
ecttncdiv.onclick=function(){if(event.target==this)return closetandc()};
document.body.appendChild(ecttncdiv);
ajaxobj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
ajaxobj.open("GET",'vsadmin/ajaxservice.php?action=termsandconditions',false);
ajaxobj.send(null);
ecttncdiv.innerHTML=ajaxobj.responseText;
<?php 	}else{ ?>
newwin=window.open("termsandconditions.php","Terms","menubar=no, scrollbars=yes, width=420, height=380, directories=no,location=no,resizable=yes,status=no,toolbar=no");
<?php 	}
		print "}\r\n";
}
function getamazonjsurl($isdemomode){
	$scripturl='static-eu.payments-amazon.com/OffAmazonPayments/' . ($GLOBALS['origCountryCode']=='DE'?'de/':'uk/') . ($isdemomode?'sandbox/':'') . 'lpa/';
	if($GLOBALS['origCountryCode']=='US') $scripturl='static-na.payments-amazon.com/OffAmazonPayments/us/' . ($isdemomode?'sandbox/':'');
	if($GLOBALS['origCountryCode']=='JP') $scripturl='origin-na.ssl-images-amazon.com/images/G/09/EP/offAmazonPayments/sandbox/prod/lpa/';
	return('https://' . $scripturl . 'js/Widgets.js');
}
function calculateStringToSignV2(){
	global $scripturl,$endpointpath,$demomode;
	return 'POST' . "\n" . $scripturl . "\n" . $endpointpath . "\n" . getParametersAsString();
}
function getParametersAsString(){
	global $amazonprms;
	$queryParameters = array();
	foreach ($amazonprms as $key=>$value) {
		$queryParameters[] = $key . '=' . str_replace('%7E', '~', rawurlencode($value));
	}
	return implode('&', $queryParameters);
}
function calculateSignatureAndParametersToString(){
	global $amazonprms,$amazonstr;
	uksort($amazonprms, 'strcmp');
	$amazonstr=getParametersAsString();
}
function amazonparam2($nam, $val){
	global $amazonstr,$amazonprms;
	$amazonprms[$nam]=replaceaccents($val);
}
function iseuropean($cntryid){
	return($cntryid=='BE' || $cntryid=='BG' || $cntryid=='CZ' || $cntryid=='DK' || $cntryid=='DE' || $cntryid=='EE' || $cntryid=='IE' || $cntryid=='EL' || $cntryid=='ES' || $cntryid=='FR' || $cntryid=='GB' || $cntryid=='HR' || $cntryid=='IT' || $cntryid=='CY' || $cntryid=='LV' || $cntryid=='LT' || $cntryid=='LU' || $cntryid=='HU' || $cntryid=='MT' || $cntryid=='NL' || $cntryid=='AT' || $cntryid=='PL' || $cntryid=='PT' || $cntryid=='RO' || $cntryid=='SI' || $cntryid=='SK' || $cntryid=='FI' || $cntryid=='SE' || $cntryid=='UK');
}
function getstateabbrev($statename){
	$stateabbrev='';
	$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)) $stateabbrev=$rs2['stateAbbrev'];
	ect_free_result($result2);
	return($stateabbrev);
}
function zipisoptional($sci){
	global $zipoptional;
	return(in_array((int)$sci,$zipoptional));
}
function getDPs($currcode){
	return(checkDPs($currcode));
}
function createdynamicstates($sSQL){
	global $origCountry,$origCountryID,$usestateabbrev,$ordState,$ordShipState,$origCountryCode,$mobilebrowser;
?>	function getziptext(cntid){
		if(cntid==1) return("<?php print jsescape($GLOBALS['xxZip'])?>"); else return("<?php print jsescape($GLOBALS['xxPostco'])?>");
	}
	function dynamiccountries(citem,stateid){
		if(citem!=null){
			var st,smen,cntid=citem[citem.selectedIndex].value;
			if(st=document.getElementById(stateid+'statetxt')){
				if(cntid==1) st.innerHTML='<?php print jsescape($GLOBALS['xxStateD'])?>';
				else if(cntid==2||cntid==175) st.innerHTML='<?php print jsescape($GLOBALS['xxProvin'])?>';
				else if(cntid==142||cntid==201) st.innerHTML='<?php print jsescape($GLOBALS['xxCounty'])?>';
				else st.innerHTML='<?php print jsescape($GLOBALS['xxStaPro'])?>';
				if(st2=document.getElementById(stateid+'state2')) st2.placeholder=st.innerHTML;
			}
			if(st=document.getElementById(stateid+'ziptxt')) st.innerHTML=getziptext(cntid);
			if(st=document.getElementById(stateid+'zip')) st.placeholder=getziptext(cntid);
			if(smen=document.getElementById(stateid+'state')){
				smen.disabled=false;
				if(countryhasstates[cntid]){
					smen.options[0].value='';
					if(cntid==1) smen.options[0].innerHTML='<?php print jsescape($GLOBALS['xxPSelUS'])?>';
					else if(cntid==2) smen.options[0].innerHTML='<?php print jsescape($GLOBALS['xxPSelCA'])?>';
					else if(cntid==201) smen.options[0].innerHTML='<?php print jsescape($GLOBALS['xxPSelUK'])?>';
					else smen.options[0].innerHTML='<?php print jsescape($GLOBALS['xxPlsSel'])?>';
					for(var cind=0;cind<dynst[cntid].length;cind++){
						if(cind>=smen.length-1)
							smen.options[cind+1]=new Option();
						smen.options[cind+1].value=dynst[cntid][cind][2];
						smen.options[cind+1].innerHTML=dynst[cntid][cind][0];
					}
					smen.length=cind+1;
					stateselectordisabled[stateid=='s'?1:0]=false;
				}else{
					smen.options[0].innerHTML='<?php print jsescape($GLOBALS['xxOutsid'] . ' ' . $origCountryCode)?>';
					smen.disabled=true;
					stateselectordisabled[stateid=='s'?1:0]=true;
				}
				smen.selectedIndex=0;
			}
		}
	}
	function setinitialstate(isshp){<?php
$sistate=getpost('state')!='' ? getpost('state') : $ordState;
$sisstate=getpost('sstate')!='' ? getpost('sstate') : $ordShipState;
$sistatename=(! is_numeric($sistate) ? $sistate : '');
$sisstatename=(! is_numeric($sisstate) ? $sisstate : '');
if($sistate!=''){
	$sSQL2='SELECT stateID FROM states WHERE ' . (is_numeric($sistate) ? "stateID='" . escape_string($sistate) . "' " : "statename='" . escape_string($sistate) . "' OR stateAbbrev='" . escape_string($sistate) . "'");
	$result=ect_query($sSQL2) or ect_error();
	if($rs=ect_fetch_assoc($result)) $sistate=$rs['stateID'];
	ect_free_result($result);
}
if($sisstate!=''){
	$sSQL2='SELECT stateID FROM states WHERE ' . (is_numeric($sistate) ? "stateID='" . escape_string($sisstate) . "' " : "statename='" . escape_string($sisstate) . "' OR stateAbbrev='" . escape_string($sisstate) . "'");
	$result=ect_query($sSQL2) or ect_error();
	if($rs=ect_fetch_assoc($result)) $sisstate=$rs['stateID'];
	ect_free_result($result);
}
?>		var initstate=['<?php print jsescape($sistate)?>','<?php print jsescape($sisstate)?>'];
		var gotstate=false;
		if(document.getElementById(isshp+"state")){
			var smen=document.getElementById(isshp+"state");
			for(var cind=0; cind<smen.length; cind++){
				if(smen.options[cind].value==initstate[isshp=='s'?1:0]){
					smen.selectedIndex=cind;
					gotstate=true;
					break;
				}
			}
		}
		if(document.getElementById(isshp+"state2"))
			document.getElementById(isshp+"state2").value=(gotstate?'':(isshp=='s'?'<?php print jsescape($sisstatename)?>':'<?php print jsescape($sistatename)?>'));
	}
	var stateselectordisabled=[true,true];
	var dynst=[];var countryhasstates=[];
	var savstates=[];var savstatab=[];
<?php
	$currcountry=0;
	if($sSQL!=''){
		$result=ect_query($sSQL) or ect_error();
		if(ect_num_rows($result)>0){
			while($rs=ect_fetch_assoc($result)){
				if($currcountry!=$rs['stateCountryID']){
					if($currcountry!=0) print "];\n";
					$currcountry=$rs['stateCountryID'];
					print "countryhasstates['" . $currcountry . "']=" . $currcountry . ";\n";
					print 'dynst[' . $currcountry . ']=[';
				}else
					print ",\n";
				print "['" . jsescape($rs[getlangid('stateName',1048576)]) . "','" . ($currcountry==1 || $currcountry==2 ? jsescape($rs['stateAbbrev']) : '') . "'," . $rs['stateID'] . ']';
			}
			print "];\n";
		}
	}
}
function updategiftwrap(){
	global $giftwrappingid,$giftwrappingcost,$quantity,$theid;
	$quantity=0;
	$currquant=0;
	$theid=@$giftwrappingid;
	$sSQL="SELECT SUM(cartQuantity) AS cartquant FROM cart WHERE cartGiftWrap<>0 AND cartCompleted=0 AND " . getsessionsql();
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		if(! is_null($rs['cartquant'])) $quantity=(int)$rs['cartquant'];
	}
	ect_free_result($result);
	$sSQL="SELECT cartQuantity FROM cart WHERE cartProdID='" . $giftwrappingid . "' AND cartCompleted=0 AND " . getsessionsql();
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)) $currquant=$rs['cartQuantity']; else $currquant=-1;
	ect_free_result($result);
	if($quantity!=$currquant){
		if($currquant===-1){
			if(is_numeric(@$giftwrappingcost) && @$giftwrappingcost!=0 && $quantity>0) additemtocart($GLOBALS['xxGifPro'],$giftwrappingcost);
		}elseif($quantity==0 || ! is_numeric($giftwrappingcost)){
			ect_query("DELETE FROM cart WHERE cartProdID='" . $giftwrappingid . "' AND cartCompleted=0 AND " . getsessionsql()) or ect_error();
		}else
			ect_query("UPDATE cart SET cartQuantity=" . $quantity . ",cartProdPrice=" . $giftwrappingcost . " WHERE cartProdID='" . $giftwrappingid . "' AND cartCompleted=0 AND " . getsessionsql()) or ect_error();
	}
}
function getshiplogo($stype){
	global $shippinglogo,$mobilebrowser;
	if($stype==3)
		$gsl='<img src="images/usps_logo.png" alt="USPS Logo">';
	elseif($stype==4||$stype==11)
		$gsl='<img src="images/upslogo.png" alt="UPS Logo">';
	elseif($stype==6)
		$gsl='<img src="images/canadapost.gif" alt="CanadaPost Logo">';
	elseif($stype==7 || $stype==8)
		$gsl='<img src="images/fedexlogo.png" alt="FedEx Logo">';
	elseif($stype==9)
		$gsl='<img src="images/dhllogo.gif" alt="DHL Logo">';
	else
		$gsl='<img src="'.(@$shippinglogo!=''?$shippinglogo:'images/defaultshiplogo.png').'" alt="Logo">';
	return $gsl;
}
function writealtshipline($altmethod,$altid,$pretext,$defpretext,$isestimator){
	global $shippingoptionsasradios,$shipType,$origShipType;
	if(! $isestimator){
		print '<div class="altshippingselector">';
			print '<div onclick="selaltrate('.$altid.')" style="cursor:pointer">' . getshiplogo($altid) . '</div>';
			print '<div><a href="#" onclick="selaltrate('.$altid.')" class="ectlink">' . $altmethod . '</a></div>';
		print "</div>\n";
	}else{
		if(@$shippingoptionsasradios==TRUE){
			if($altmethod!='' || $origShipType==$altid) print '<div class="shipline"' . ($shipType==$altid?' style="font-weight:bold"':'') . '><label class="ectlabel shipradio"><input type="radio" class="ectradio shipradio" value="' . $altid . '"' . ($shipType==$altid?' checked="checked"':'') . ' onclick="selaltrate(' . $altid . ')" />' . ($shipType==$altid?$defpretext:$pretext) . $altmethod . '</label></div>';
		}else{
			if($altmethod!='' || $origShipType==$altid) print '<option value="'.$altid.'"'.($shipType==$altid?' selected="selected"':'').'>'.($shipType==$altid?$defpretext:$pretext).$altmethod.'</option>';
		}
	}
}
function retrieveorderdetails($ordid, $sessid){
	global $ordName,$ordLastName,$ordAddress,$ordAddress2,$ordCity,$ordState,$ordZip,$ordCountry,$ordEmail,$ordEmail2,$ordPhone,$ordShipName,$ordShipLastName,$ordShipAddress,$ordShipAddress2,$ordShipCity,$ordShipState,$ordShipZip,$ordShipCountry,$ordShipPhone,$ordPayProvider,$ordComLoc,$ordExtra1,$ordExtra2,$ordShipExtra1,$ordShipExtra2,$ordCheckoutExtra1,$ordCheckoutExtra2,$ordAffiliate,$ordAVS,$ordCVV,$ordAddInfo,$addshippinginsurance;
	global $insidedelivery_,$commercialloc_,$wantinsurance_,$saturdaydelivery_,$signaturerelease_;
	if(is_numeric($ordid) && strlen($sessid)<100){
		$result=ect_query("SELECT ordName,ordLastName,ordAddress,ordAddress2,ordCity,ordState,ordZip,ordCountry,ordEmail,ordPhone,ordShipName,ordShipLastName,ordShipAddress,ordShipAddress2,ordShipCity,ordShipState,ordShipZip,ordShipCountry,ordShipPhone,ordPayProvider,ordComLoc,ordExtra1,ordExtra2,ordShipExtra1,ordShipExtra2,ordCheckoutExtra1,ordCheckoutExtra2,ordAffiliate,ordAVS,ordCVV,ordAddInfo FROM orders WHERE ordID='".escape_string($ordid)."' AND ordSessionID='".escape_string($sessid)."'");
		if($rs=ect_fetch_assoc($result)){
			$ordName=$rs['ordName'];
			$ordLastName=$rs['ordLastName'];
			$ordAddress=$rs['ordAddress'];
			$ordAddress2=$rs['ordAddress2'];
			$ordCity=$rs['ordCity'];
			$ordState=$rs['ordState'];
			$ordZip=$rs['ordZip'];
			$ordCountry=$rs['ordCountry'];
			$ordEmail2=$ordEmail=$rs['ordEmail'];
			$ordPhone=$rs['ordPhone'];
			$ordShipName=$rs['ordShipName'];
			$ordShipLastName=$rs['ordShipLastName'];
			$ordShipAddress=$rs['ordShipAddress'];
			$ordShipAddress2=$rs['ordShipAddress2'];
			$ordShipCity=$rs['ordShipCity'];
			$ordShipState=$rs['ordShipState'];
			$ordShipZip=$rs['ordShipZip'];
			$ordShipCountry=$rs['ordShipCountry'];
			$ordShipPhone=$rs['ordShipPhone'];
			$ordPayProvider=$rs['ordPayProvider'];
			$ordComLoc=$rs['ordComLoc'];
			$ordExtra1=$rs['ordExtra1'];
			$ordExtra2=$rs['ordExtra2'];
			$ordShipExtra1=$rs['ordShipExtra1'];
			$ordShipExtra2=$rs['ordShipExtra2'];
			$ordCheckoutExtra1=$rs['ordCheckoutExtra1'];
			$ordCheckoutExtra2=$rs['ordCheckoutExtra2'];
			$ordAffiliate=$rs['ordAffiliate'];
			if(@$GLOBALS['closeaffiliateprogram'])$ordAffiliate='';
			$ordAVS=$rs['ordAVS'];
			$ordCVV=$rs['ordCVV'];
			$ordAddInfo='';
			if(is_numeric(substr(getpost("changeaction"),0,1))){
				$thebit=pow(2,(int)substr(getpost("changeaction"),0,1));
				if(substr(getpost("changeaction"),1,1)=='y'){
					if(($ordComLoc & $thebit)!=$thebit) $ordComLoc+=$thebit;
				}else{
					if(($ordComLoc & $thebit)==$thebit) $ordComLoc-=$thebit;
				}
				ect_query("UPDATE orders SET ordComLoc='" . escape_string($ordComLoc) . "' WHERE ordStatus=2 AND ordID='".escape_string(str_replace("'","",$ordid))."' AND ordSessionID='".escape_string($sessid)."'") or ect_error();
			}
			if(($ordComLoc & 1)==1) $commercialloc_=TRUE;
			if(($ordComLoc & 2)==2 || abs(@$addshippinginsurance)==1) $wantinsurance_=TRUE;
			if(($ordComLoc & 4)==4) $saturdaydelivery_=TRUE;
			if(($ordComLoc & 8)==8) $signaturerelease_=TRUE;
			if(($ordComLoc & 16)==16) $insidedelivery_=TRUE;
			$ordPhone=str_replace('xxx-xxx-xxxx','',$ordPhone);
			$ordShipPhone=str_replace('xxx-xxx-xxxx','',$ordShipPhone);
		}
		ect_free_result($result);
	}
}
function getpayprovhandling(){
	global $ordPayProvider,$handling,$orighandling,$handlingchargepercent,$orighandlingpercent;
	if($ordPayProvider!='' && is_numeric($ordPayProvider)){
		$result=ect_query("SELECT ppHandlingCharge,ppHandlingPercent FROM payprovider WHERE payProvID=".$ordPayProvider) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			$handling+=$rs['ppHandlingCharge'];
			$handlingchargepercent+=$rs['ppHandlingPercent'];
		}
		ect_free_result($result);
	}
	$orighandling=$handling;
	$orighandlingpercent=$handlingchargepercent;
}
function getcctypefromnum($thecardnum){
	if(substr($thecardnum, 0, 1)=='5')
		return('MasterCard');
	elseif(substr($thecardnum, 0, 1)=='6')
		return('Discover');
	elseif(substr($thecardnum, 0, 1)=='3')
		return('Amex');
	return('Visa');
}
function show_states($tstate){
	global $origCountryCode;
	print '<option value="">' . $GLOBALS['xxOutsid'] . ' ' . $origCountryCode . '</option>';
	return FALSE;
}
function getcountryfromid($cntryid){
	$cntname='';
	if(is_numeric($cntryid)||strlen($cntryid)==2){
		$sSQL='SELECT countryName FROM countries WHERE ';
		if($cntryid=='GB')
			$sSQL.='countryID=201';
		elseif($cntryid=='FR')
			$sSQL.='countryID=65';
		elseif($cntryid=='PT')
			$sSQL.='countryID=153';
		elseif($cntryid=='ES')
			$sSQL.='countryID=175';
		elseif(is_numeric($cntryid))
			$sSQL.="countryID='" . escape_string($cntryid) . "'";
		else
			$sSQL.="countryCode='" . escape_string($cntryid) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)) $cntname=$rs['countryName'];
		ect_free_result($result);
	}
	return($cntname);
}
function getidfromcountry($cntry){
	$cntryid=1;
	$sSQL="SELECT countryID FROM countries WHERE countryName='" . escape_string($cntry) . "'";
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)) $cntryid=$rs['countryID'];
	ect_free_result($result);
	return($cntryid);
}
function show_countries($tcountry,$showplssel){
	global $allcountries,$numallcountries;
	if($numallcountries>1&&$showplssel) print '<option value="">'.$GLOBALS['xxPlsSel'].'</option>';
	for($index=0;$index<$numallcountries;$index++){
		print '<option value="' . $allcountries[$index]['countryID'] . '"';
		if($tcountry==$allcountries[$index]['countryName']) print ' selected';
		print '>' . $allcountries[$index]['countryName'] . "</option>\n";
	}
}
function checkuserblock($thepayprov){
	global $blockmultipurchase,$multipurchaseblockmessage,$shipselectoraction;
	if(@$multipurchaseblockmessage=='') $multipurchaseblockmessage="I'm sorry. We are experiencing temporary difficulties at the moment. Please try your purchase again later.";
	$multipurchaseblocked=FALSE;
	if($thepayprov!='7' && $thepayprov!='13' && strlen($GLOBALS['REMOTE_ADDR'])<=15){
		$theip=$GLOBALS['REMOTE_ADDR'];
		if($theip=='') $theip='none';
		if(@$blockmultipurchase>0 && $shipselectoraction==''){
			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='" . 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']>=$blockmultipurchase) $multipurchaseblocked=TRUE;
			}else{
				ect_query("INSERT INTO multibuyblock (ssdenyip,lastaccess) VALUES ('" . 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)
			$multipurchaseblocked=TRUE;
	}
	return($multipurchaseblocked);
}
function multShipWeight($theweight, $themul){
	return(($theweight*$themul)/100.0);
}
function subtaxesfordiscounts($theExemptions, $discAmount){
	global $statetaxfree,$countrytaxfree,$shipfreegoods;
	if(($theExemptions & 1)==1) $statetaxfree -= $discAmount;
	if(($theExemptions & 2)==2) $countrytaxfree -= $discAmount;
	if(($theExemptions & 4)==4) $shipfreegoods -= $discAmount;
}
function addadiscount($resset, $groupdiscount, $dscamount, $subcpns, $cdcpncode, $statetaxhandback, $countrytaxhandback, $theexemptions, $thetax){
	global $totaldiscounts,$cpnmessage,$statetaxfree,$countrytaxfree,$gotcpncode,$countryTax,$appliedcouponname,$appliedcouponamount,$minloglevel,$discountarray,$numdiscountarray;
	$dscamount=round($dscamount,2);
	$discountarray[$numdiscountarray][0]=$resset['cpnID'];
	$discountarray[$numdiscountarray][1]=$resset['cpnName'];
	$discountarray[$numdiscountarray][2]=$dscamount;
	$numdiscountarray++;
	$totaldiscounts+=$dscamount;
	if($groupdiscount){
		$statetaxfree -= ($dscamount * $statetaxhandback);
		$countrytaxfree -= ($dscamount * $countrytaxhandback);
	}else{
		subtaxesfordiscounts($theexemptions, $dscamount);
		if(@$GLOBALS['perproducttaxrate']) $countryTax -= (($dscamount * $thetax) / 100.0);
	}
	if(stristr($cpnmessage,'<br>' . $resset[getlangid('cpnName',1024)] . '<br>')==FALSE){
		$cpnmessage.=$resset[getlangid('cpnName',1024)] . '<br>';
		if($subcpns){
			$theres=ect_query('SELECT cpnID FROM coupons WHERE cpnNumAvail>0 AND cpnNumAvail<30000000 AND cpnID=' . $resset['cpnID'] . ' AND ((cpnLoginLevel>=0 AND cpnLoginLevel<='.$minloglevel.') OR (cpnLoginLevel<0 AND -1-cpnLoginLevel='.$minloglevel.'))') or ect_error();
			if($theresset=ect_fetch_assoc($theres)) @$_SESSION['couponapply'].=',' . $resset['cpnID'];
			ect_query('UPDATE coupons SET cpnNumAvail=cpnNumAvail-1 WHERE cpnNumAvail>0 AND cpnNumAvail<30000000 AND cpnID=' . $resset['cpnID'] . ' AND ((cpnLoginLevel>=0 AND cpnLoginLevel<='.$minloglevel.') OR (cpnLoginLevel<0 AND -1-cpnLoginLevel='.$minloglevel.'))') or ect_error();
		}
	}
	if($cdcpncode!='' && strtolower(trim($resset['cpnNumber']))==strtolower($cdcpncode)){ $gotcpncode=TRUE; $appliedcouponname=$resset['cpnName']; $appliedcouponamount=$dscamount; }
}
function timesapply($taquant,$tathresh,$tamaxquant,$tamaxthresh,$taquantrepeat,$tathreshrepeat){
	if($tamaxquant==0) $taquantrepeat=0;
	if($tamaxthresh==0) $tathreshrepeat=0;
	if($taquantrepeat==0 && $tathreshrepeat==0)
		$tatimesapply=1.0;
	elseif($tamaxquant==0||$taquantrepeat==0)
		$tatimesapply=(int)(($tathresh - $tamaxthresh) / $tathreshrepeat)+1;
	elseif($tamaxthresh==0||$tathreshrepeat==0)
		$tatimesapply=(int)(($taquant - $tamaxquant) / $taquantrepeat)+1;
	else{
		$ta1=(int)(($taquant - $tamaxquant) / $taquantrepeat)+1;
		$ta2=(int)(($tathresh - $tamaxthresh) / $tathreshrepeat)+1;
		if($ta2 < $ta1) $tatimesapply=$ta2; else $tatimesapply=$ta1;
	}
	return($tatimesapply);
}
function jschk($str){
	return(str_replace(array('\\',"'",'<','>'),array('\\\\',"\\'",'\\<','\\>'), $str));
}
function paypalcheckoutjs($isexpress,$advancedcards,$addmessages){
	global $data1,$data3,$data4,$ppmethod,$storeurlssl,$orderid,$countryCurrency,$estimate,$thesessionid,$shipping,$stateTax,$countryTax,$handling,$totaldiscounts,$freeshipamnt,$loyaltypointdiscount,$demomode;
	$estshipping=$esthandling=$esttaxes=$estdiscounts=0;
	$sess=$thesessionid;
	$clid=@$_SESSION['clientID'];
	if($isexpress) $orderid='express';
	$check=hash('sha256',$clid.$sess.$GLOBALS['adminSecret'].$orderid.'PPCO');
	$ppfunding=$ppfundingd='';
	$buttonstyle=explode('|',$data3);
	$hidepaypalbuttons=(@$buttonstyle[9]=='hide'&&$advancedcards&&$data4!=''&&!$isexpress);
	$wantapplepay=(@$buttonstyle[10]=='apple'&&$advancedcards&&$data4!=''&&!$isexpress);
	$wantgpay=(@$buttonstyle[11]=='google'&&$advancedcards&&$data4!=''&&!$isexpress);
	if($isexpress) $wantapplepay=$wantgpay=FALSE;
	if($ppmethod==1) $methodname='authorize'; else $methodname='capture';
	if(@$buttonstyle[0]=='') $buttonstyle[0]='pill';
	//if(@$buttonstyle[4]=='hide') $ppfundingd.=',credit'; else $ppfunding.=',credit';
	if(@$buttonstyle[5]=='hide'&&!$advancedcards) $ppfundingd.=',card'; else $ppfunding.=',card';
	if(@$buttonstyle[6]=='hide') $ppfundingd.=',paylater'; else $ppfunding.=',paylater';
	if(@$buttonstyle[7]=='hide') $ppfundingd.=',venmo'; else $ppfunding.=',venmo';
	if(@$buttonstyle[8]=='hide') $ppfundingd.=',bancontact,blik,eps,giropay,ideal,mercadopago,mybank,p24,sepa,sofort';
	$ppfundingd=trim($ppfundingd,',');
	$ppfunding=trim($ppfunding,',');
	if($isexpress){
		$buttonstyle[1]='small';
		$buttonstyle[3]='vertical';
		$ppfundingd='card,bancontact,blik,eps,giropay,ideal,mercadopago,mybank,p24,sepa,sofort';
		if(@$buttonstyle[6]=='hide') $ppfundingd.=',paylater';
		$ppfunding='paypal';
	}
	$paypallocale='';
	if($GLOBALS['storelang']=='fr'&&$GLOBALS['origCountryID']==2) $paypallocale='fr_CA';
	print '<script src="https://www.paypal.com/sdk/js?' . ($paypallocale!=''?'locale='.$paypallocale.'&':'') . (@$demomode?'buyer-country=US&':'') . 'components=' . ($advancedcards?(($wantapplepay?'applepay,':'').($wantgpay?'googlepay,':'').($hidepaypalbuttons?'':'buttons,').'hosted-fields'):'buttons') . ($addmessages?',messages':'') . ($ppfunding!=''?'&enable-funding=' . $ppfunding:'') . ($ppfundingd!=''?'&disable-funding=' . $ppfundingd:'') . '&client-id=' . $data1 . ($advancedcards?'&merchant-id=' . $data4:'') . '&currency=' . $countryCurrency . '&intent=' . $methodname . ($isexpress?'&commit=false&vault=false':'') . '" data-partner-attribution-id="EcommerceTemplates_Ecom_PPCP"' . ($advancedcards?' data-client-token="' . $GLOBALS['client_token'] . '"':'') . '></script>' . "\n";
	if(!$hidepaypalbuttons) print '<div id="paypal-button" class="paypal-button' . ($isexpress?'-express':'') . '">' . ($isexpress?'':'<img src="images/preloader.gif" id="ppprepload" alt="" class="ectpreloader">') . '</div>' . "\n";
	if($wantgpay) print '<div class="paypal-button"><div id="gpay-container" class="ect-gpay-button" style="width:100%;height:48px"><script src="https://pay.google.com/gp/p/js/pay.js"></script></div></div>' . "\n";
	if($wantapplepay) print '<div class="paypal-button"><div id="applepay-container" class="ect-apple-button"><script src="https://applepay.cdn-apple.com/jsapi/v1/apple-pay-sdk.js"></script></div></div>' . "\n";
	if($isexpress){
		if(@$GLOBALS['combineshippinghandling']){
			$estshipping=$shipping+$handling;
			$esthandling=0;
		}else{
			$estshipping=$shipping;
			$esthandling=$handling;
		}
		$esttaxes=($stateTax+$countryTax);
		$estdiscounts=$totaldiscounts+$freeshipamnt+$loyaltypointdiscount;
	}
	if($advancedcards){ ?>
						<div class="card_container">
							<form id="card-form">
								<div>
									<label for="card-holder-name">Name on Card</label>
									<input type="text" id="card-holder-name" name="card-holder-name" class="card-holder-name" autocomplete="off" placeholder="card holder name" value="<?php print htmlspecials(trim_($GLOBALS['ordName'].' '.$GLOBALS['ordLastName']))?>">
								</div>
								<div>
									<label for="card-number">Card Number</label><div id="card-number" class="card_field"></div>
								</div>
								<div style="width:50%;display:inline-block;padding-right: 10px;box-sizing:border-box">
									<label for="expiration-date">Expiration Date</label>
									<div id="expiration-date" class="card_field"></div>
								</div><div style="width:50%;display:inline-block">
									<label for="cvv">CVV</label><div id="cvv" class="card_field"></div>
								</div>
								<div style="text-align:center;margin-top:20px">
									<button value="submit" id="submit" class="ectbutton widecheckout3"><?php print $GLOBALS['xxPayCar']?></button>
								</div>
							</form>
						</div>
<?php
	} ?>
<script>
<?php
	if($wantapplepay){ ?>
async function setupApplepay() {
	const applepay = paypal.Applepay();
	const {isEligible,countryCode,currencyCode,merchantCapabilities,supportedNetworks} = await  applepay.config();
	if (!isEligible) {
		throw new Error("applepay is not eligible");
	}
	document.getElementById("applepay-container").innerHTML='<apple-pay-button id="btn-appl" buttonstyle="black" type="buy" locale="en">';
	document.getElementById("btn-appl").addEventListener("click", onClick);
	async function onClick(){
		const paymentRequest = {
			countryCode,
			currencyCode: '<?php print $countryCurrency?>',
			merchantCapabilities,
			supportedNetworks,
			requiredBillingContactFields:["name","phone","email","postalAddress"],
			requiredShippingContactFields:[],
			total: {
				label: "Total",
				amount: "<?php print round($GLOBALS['grandtotal'],$GLOBALS['currDecimals']) ?>",
				type: "final",
			}
		};
		let session = new ApplePaySession(4, paymentRequest);
		session.onvalidatemerchant = (event) => {
			applepay.validateMerchant({
				validationUrl: event.validationURL,
			}).then((payload) => {
				session.completeMerchantValidation(payload.merchantSession);
			}).catch((err) => {
				console.error(err);
				session.abort();
			});
		};
		session.onpaymentmethodselected = () => {
			session.completePaymentMethodSelection({
				newTotal: paymentRequest.total,
			});
		};
		session.onpaymentauthorized = async (event) => {
			try {
				const orderResponse = await fetch('<?php print $storeurlssl?>vsadmin/ajaxservice.php?action=createppsale&ordid=<?php print $orderid?>',{
					method:'POST',headers:{'content-type':'application/x-www-form-urlencoded'},body:'<?php print 'sess='.$sess.'&clid='.$clid.'&check='.$check; ?>'
				});
				if(!orderResponse.ok) {
					throw new Error("ApplePay error creating order")
				}
				const orderResponseJS = await orderResponse.json();
				if(orderResponseJS.ecterror){
					throw new Error(orderResponseJS.ecterror);
				}else{
					await applepay.confirmOrder({ orderId: orderResponseJS.id, token: event.payment.token, billingContact: event.payment.billingContact , shippingContact: event.payment.shippingContact });
					const execResponse = await fetch('<?php print $storeurlssl?>vsadmin/ajaxservice.php?action=execppsale&ordid=<?php print $orderid?>', {
						method: 'POST',headers:{'content-type':'application/x-www-form-urlencoded'},body:'paymentID='+orderResponseJS.id
					});
					const execResponseJS = await execResponse.json();
					if(execResponseJS.ecterror){
						throw new Error(execResponseJS.ecterror);
					}else{
						session.completePayment({
							status: window.ApplePaySession.STATUS_SUCCESS,
						});
						document.location='<?php print 'thanks' . $GLOBALS['extension']?>?action=termpp&paymentID='+orderResponseJS.id+'&ordid=<?php print $orderid?>';
					}
				}
			}catch(err){
				console.error(err);
				document.getElementById('ppcoverdiv').style.display='none';
				//var err = new ApplePayError("unknown", "postalAddress", "Address is invalid");
				session.completePayment({
					//errors: [ err ],
					status: window.ApplePaySession.STATUS_FAILURE
				});
			}
		};
		session.oncancel  = () => {
			console.log("Apple Pay Cancelled !!")
		}
		session.begin();
	}
}
document.addEventListener("DOMContentLoaded", () => {
	if(ApplePaySession?.supportsVersion(4) && ApplePaySession?.canMakePayments()) {
		setupApplepay().catch(console.error);
	}
});

<?php
	}
	if($wantgpay){ ?>
const baseRequest = {
	apiVersion: 2,
	apiVersionMinor: 0,
};
let paymentsClient = null,
	allowedPaymentMethods = null,
	merchantInfo = null;
function getGoogleIsReadyToPayRequest(allowedPaymentMethods) {
	return Object.assign({}, baseRequest, {
		allowedPaymentMethods: allowedPaymentMethods,
	});
}
async function getGooglePayConfig() {
	if (allowedPaymentMethods == null || merchantInfo == null) {
		try{
			const googlePayConfig = await paypal.Googlepay().config();
			allowedPaymentMethods = googlePayConfig.allowedPaymentMethods;
			merchantInfo = googlePayConfig.merchantInfo;
		}catch(err){
			ectById('gpay-container').parentNode.style.display='none';
			console.error(err);
		}
	}
	return {allowedPaymentMethods,merchantInfo};
}
async function getGooglePaymentDataRequest() {
	const paymentDataRequest = Object.assign({}, baseRequest);
	const { allowedPaymentMethods, merchantInfo } = await getGooglePayConfig();
	paymentDataRequest.allowedPaymentMethods = allowedPaymentMethods;
	paymentDataRequest.transactionInfo = getGoogleTransactionInfo();
	paymentDataRequest.merchantInfo = merchantInfo;
	paymentDataRequest.callbackIntents = ["PAYMENT_AUTHORIZATION"];
	return paymentDataRequest;
}
function onPaymentAuthorized(paymentData) {
	return new Promise(function (resolve, reject) {
		processPayment(paymentData).then(function (data) {
			if(data.transactionState=="SUCCESS"){
				resolve({ transactionState: "SUCCESS" });
				document.getElementById('ppcoverdiv').style.display='';
				setTimeout(() => {document.location='<?php print 'thanks' . $GLOBALS['extension']?>?action=termpp&paymentID='+data.orderID+'&ordid=<?php print $orderid?>';},2000);
			}else{
				var errormessage='Unknown error';
				if(data.errormessage) errormessage=data.errormessage;
				resolve({ transactionState: "ERROR",
					error: {
						reason: "OTHER_ERROR",
						message: errormessage,
						intent: "PAYMENT_AUTHORIZATION"
					} });
			}
		}).catch(function (errDetails) {
			resolve({ transactionState: "ERROR" });
		});
	});
}
function getGooglePaymentsClient() {
	if (paymentsClient === null) {
		paymentsClient = new google.payments.api.PaymentsClient({
			environment: "<?php print $demomode?'TEST':'PRODUCTION'?>",
			paymentDataCallbacks: {
				onPaymentAuthorized: onPaymentAuthorized,
			},
		});
	}
	return paymentsClient;
}
async function onGooglePayLoaded() {
	const paymentsClient = getGooglePaymentsClient();
	const { allowedPaymentMethods } = await getGooglePayConfig();
	paymentsClient
	.isReadyToPay(getGoogleIsReadyToPayRequest(allowedPaymentMethods))
	.then(function (response) {
		if (response.result) {
			addGooglePayButton();
		}
	}).catch(function (err) {
		console.error(err);
	});
}
function addGooglePayButton() {
	const paymentsClient = getGooglePaymentsClient();
	const button = paymentsClient.createButton({
		buttonRadius:28,
		buttonSizeMode: 'fill',
		onClick: onGooglePaymentButtonClicked,
	});
	document.getElementById("gpay-container").appendChild(button);
}
function getGoogleTransactionInfo() {
	return {
		countryCode: "<?php print $GLOBALS['countryCode']?>",
		currencyCode: "<?php print $countryCurrency?>",
		totalPriceStatus: "FINAL",
		totalPrice: "<?php print round($GLOBALS['grandtotal'],$GLOBALS['currDecimals']) ?>",
		totalPriceLabel: "Total",
	};
}
async function onGooglePaymentButtonClicked() {
	const paymentDataRequest = await getGooglePaymentDataRequest();
	paymentDataRequest.transactionInfo = getGoogleTransactionInfo();
	const paymentsClient = getGooglePaymentsClient();
	paymentsClient.loadPaymentData(paymentDataRequest);
}
async function processPayment(paymentData) {
	try {
		const { currencyCode, totalPrice } = getGoogleTransactionInfo();
		const resdata = await fetch('<?php print $storeurlssl?>vsadmin/ajaxservice.php?action=createppsale&ordid=<?php print $orderid?>', {
			method:'post',headers:{'content-type':'application/x-www-form-urlencoded'},body:'<?php print 'sess='.$sess.'&clid='.$clid.'&check='.$check; ?>'
		}).then((res) => res.json());
		if(resdata.ecterror){
			document.getElementById('ppcoverdiv').style.display='none';
			console.error(resdata.ecterror);
			throw new Error(resdata.ecterror);
		}else{
			const id=resdata.id;
			const { status } = await paypal.Googlepay().confirmOrder({
				orderId: id,
				paymentMethodData: paymentData.paymentMethodData,
			});
			if (status === "APPROVED"){
				const captureResponse = await fetch('<?php print $storeurlssl?>vsadmin/ajaxservice.php?action=execppsale&ordid=<?php print $orderid?>', {
					method:'post',
					headers:{'content-type':'application/x-www-form-urlencoded'},
					body:'paymentID='+id
				}).then((res) => res.json());
				if(captureResponse.ecterror){
					document.getElementById('ppcoverdiv').style.display='none';
					console.error(captureResponse.ecterror);
					throw new Error(captureResponse.ecterror);
				}else
					return { transactionState: "SUCCESS", orderID:id };
			}else
				return { transactionState: "ERROR", errormessage: 'Transaction Failed: ' + status};
		}
	} catch (err) {
		document.getElementById('ppcoverdiv').style.display='none';
		return {
			transactionState: "ERROR",
			errormessage: err.message
		};
	}
}
document.addEventListener("DOMContentLoaded", (event) => {
	if (google && paypal.Googlepay) {
		onGooglePayLoaded().catch(console.log);
	}
});
<?php
	} ?>
	var ars_timerid='',max_height=400;
	let orderId;
	function animateremoveshipping(ishide){
		if(tcon=ectById('cart3shipselrow')){
			tcon.style.overflow='clip';
			if(ishide){
				if(max_height>50){
					tcon.style.maxHeight=max_height+'px';
					max_height-=25;
					return;
				}else
					tcon.style.display='none';
			}else{
				tcon.style.display='';
				if(max_height<400){
					max_height+=25;
					tcon.style.maxHeight=max_height+'px';
					return;
				}else
					tcon.style.maxHeight='';
			}
		}
		clearInterval(ars_timerid); 
	}
	function renderpaypalbuttons(){
<?php	if(!$hidepaypalbuttons){
			if(!$isexpress){ ?>
	ectById('ppprepload').style.display='none';
<?php		} ?>
	paypal.Buttons({
		style:{
<?php		//if(@$buttonstyle[1]=='medium') print 'height:45,'; elseif(@$buttonstyle[1]=='small') print 'height:35,';?>
			layout:'<?php print 'vertical'; // print (@$buttonstyle[3]!=''?$buttonstyle[3]:'vertical')?>',
			color:'<?php print $buttonstyle[2]?>',
			shape:'<?php print $buttonstyle[0]?>',
			label:'paypal'
		},
		createOrder:function(){
			ars_timerid=setInterval(function(){animateremoveshipping(true);},50);
			return fetch('<?php print $storeurlssl?>vsadmin/ajaxservice.php?action=createppsale&ordid=<?php print $orderid?>',{
				method:'post',headers:{'content-type':'application/x-www-form-urlencoded'},body:'<?php
					print 'sess='.$sess.'&clid='.$clid.'&check='.$check.
					'&estshipping='.number_format($estshipping,getDPs($countryCurrency),'.','') .
					'&esthandling='.number_format($esthandling,getDPs($countryCurrency),'.','') .
					'&esttaxes='.number_format($esttaxes,getDPs($countryCurrency),'.','') .
					'&estdiscounts='.number_format($estdiscounts,getDPs($countryCurrency),'.','')?>'
			}).then(function(res){
				return res.json();
			}).then(function(data){
				var token=data.id;
				if(data.ecterror)
					throw new Error(data.ecterror);
				return token;
			});
		},
		onApprove:function(data, actions){
			//alert(JSON.stringify(data));
			document.getElementById('ppcoverdiv').style.display='';
			return fetch('<?php print $storeurlssl?>vsadmin/ajaxservice.php?action=execppsale&ordid=<?php print $orderid?>',{
				method:'post',
				headers:{'content-type':'application/x-www-form-urlencoded'},
				body:'paymentID='+data.orderID+'&payerID='+data.payerID
			}).then(function(res){
				return res.json();
			}).then(function(res){
				if(res.ecterror){
					alert("We are sorry but there seems to have been an error. Please contact us with the following information...\n\n" + res.ecterror);
					document.getElementById('ppcoverdiv').style.display='none';
				}else if(res.ectsuccess=='false'){
					alert("<?php print jscheck($GLOBALS['xxNotSuc'])?>");
					document.getElementById('ppcoverdiv').style.display='none';
				}else
					document.location='<?php print ($isexpress?'cart':'thanks') . $GLOBALS['extension']?>?action=termpp&paymentID='+data.orderID+'&ordid=<?php print $orderid?>';
			});
		},
		onCancel:function(data){
			clearInterval(ars_timerid);
			ars_timerid=setInterval(function(){animateremoveshipping(false);},50);
		},
		onError:function(err){
			document.getElementById('ppcoverdiv').style.display='none';
			alert(err);
		}
	}).render('#paypal-button');
<?php	}
		if($advancedcards){ ?>
	if (paypal.HostedFields.isEligible()){
		paypal.HostedFields.render({
			createOrder:function(){
				return fetch('<?php print $storeurlssl?>vsadmin/ajaxservice.php?action=createppsale&ordid=<?php print $orderid?>', {
					method:'post',headers:{'content-type':'application/x-www-form-urlencoded'},body:'<?php print 'sess='.$sess.'&clid='.$clid.'&check='.$check?>'
				}).then(function(res){
					return res.json();
				}).then(function(orderData){
					if(orderData.ecterror) throw orderData.ecterror;
					orderId=orderData.id;
					return orderId;
				});
			},
			styles:{
				'input': {'font-size':'17px','font-family':'sans-serif'},'.valid':{'color':'darkgreen'},'.invalid':{'color':'red'}
			},
			fields:{
				number:{selector:"#card-number",placeholder:"4111 1111 1111 1111"},
				cvv:{selector:"#cvv",placeholder:"123"},
				expirationDate:{selector:"#expiration-date",placeholder:"MM/YY"}
			}
		}).then(function (cardFields){
			document.querySelector("#card-form").addEventListener('submit', (event) => {
				var cardstate=cardFields.getState();
				event.preventDefault();
				if(!cardstate.fields['number'].isValid){
					document.getElementById('ppcoverdiv').style.display='none';
					alert("<?php print jscheck($GLOBALS['xxValCC'])?>");
				}else if(!cardstate.fields['expirationDate'].isValid){
					document.getElementById('ppcoverdiv').style.display='none';
					alert("<?php print jscheck("Please enter a valid Expiration Date")?>");
				}else if(!cardstate.fields['cvv'].isValid){
					document.getElementById('ppcoverdiv').style.display='none';
					alert("<?php print jscheck("Please enter a valid CVV code")?>");
				}else{
					document.getElementById('ppcoverdiv').style.display='';
					cardFields.submit({
						cardholderName:document.getElementById('card-holder-name').value,
						billingAddress:{
							streetAddress:"<?php print jscheck($GLOBALS['ordAddress'])?>",
							extendedAddress:"<?php print jscheck($GLOBALS['ordAddress2'])?>",
							region:"<?php print jscheck($GLOBALS['ordState'])?>",
							locality:"<?php print jscheck($GLOBALS['ordCity'])?>",
							postalCode:"<?php print jscheck($GLOBALS['ordZip'])?>",
							countryCodeAlpha2:"<?php print jscheck($GLOBALS['countryCode'])?>",
						}
					}).then(function(){
						fetch('<?php print $storeurlssl?>vsadmin/ajaxservice.php?action=execppsale&ordid=<?php print $orderid?>', {
							method:'post',headers:{'content-type':'application/x-www-form-urlencoded'},body:'paymentID='+orderId
						}).then(function(res){
							return res.json();
						}).then(function (orderData){
							var errorDetail=Array.isArray(orderData.details) && orderData.details[0];
							if(orderData.ectsuccess=='false'){
								alert("<?php print jscheck($GLOBALS['xxNotSuc'])?>");
								document.getElementById('ppcoverdiv').style.display='none';
							}else if(errorDetail){
								var msg="<?php print jscheck($GLOBALS['xxNotSuc'])?>";
	<?php			if(@$demomode){ ?>
								if (errorDetail.description) msg += '\n\n' + errorDetail.description;
								if (orderData.debug_id) msg += ' (' + orderData.debug_id + ')';
	<?php			} ?>
								alert(msg);
								document.getElementById('ppcoverdiv').style.display='none';
								return;
							}else
								document.location='<?php print 'thanks' . $GLOBALS['extension']?>?action=termpp&paymentID='+orderId+'&ordid=<?php print $orderid?>';
						})
					}).catch(function (err){
						document.getElementById('ppcoverdiv').style.display='none';
						alert('Payment could not be captured! ' + JSON.stringify(err));
					});
				}
			});
		});
	}else
		document.querySelector("#card-form").style='display: none';
<?php	} ?>
	}
	var numpaypalchecks=0;
	function checkrenderpaypalbuttons(){
		if(typeof paypal!="undefined")
			renderpaypalbuttons();
		else{
			numpaypalchecks++;
			if(numpaypalchecks>10){
<?php	if(!$isexpress){ ?>
				alert("Could not load PayPal Buttons. Please check if you have any browser settings or anti-virus software which could cause this and try checking out again.");
				document.location='cart<?php print $GLOBALS['extension']?>';
<?php	} ?>
			}else
				setTimeout(checkrenderpaypalbuttons,1000);
		}
	}
	if(typeof paypal!="undefined")
		renderpaypalbuttons();
	else
		setTimeout(checkrenderpaypalbuttons,1000);
</script>
<?php
}
function calculatediscounts($cdgndtot, $subcpns, $cdcpncode){
	global $totaldiscounts,$cpnmessage,$statetaxfree,$countrytaxfree,$nodiscounts,$WSP,$rgcpncode,$gotcpncode,$thesessionid,$countryTaxRate,$countryTax,$giftcertificateid,$donationid,$giftwrappingid,$minloglevel,$allfreeshipexempt,$freeshippingapplied;
	$totaldiscounts=0;
	$cdtotquant=$cdtotprice=0;
	if($cdgndtot==0){
		$statetaxhandback=0.0;
		$countrytaxhandback=0.0;
	}else{
		$statetaxhandback=1.0 - (($cdgndtot - $statetaxfree) / $cdgndtot);
		$countrytaxhandback=1.0 - (($cdgndtot - $countrytaxfree) / $cdgndtot);
	}
	if(! $nodiscounts){
		$sSQL="SELECT cpnID FROM coupons WHERE cpnNumAvail>0 AND cpnStartDate<='" . date('Y-m-d', time()+($GLOBALS['dateadjust']*60*60)) ."' AND cpnEndDate>='" . date('Y-m-d', time()+($GLOBALS['dateadjust']*60*60)) ."' AND (cpnIsCoupon=0";
		if($cdcpncode!='') $sSQL.=" OR (cpnIsCoupon=1 AND cpnNumber='" . $cdcpncode . "')";
		$sSQL.=')';
		$cdresult=ect_query($sSQL) or ect_error();
		$nodiscounts=ect_num_rows($cdresult)==0;
	}
	if(! $nodiscounts){
		ect_query("UPDATE cart SET cartOrigProdID=cartProdID WHERE (cartOrigProdID='' OR cartOrigProdID IS NULL) AND " . getsessionsql()) or ect_error();
		$sSQL='SELECT cartOrigProdID,SUM(cartProdPrice*cartQuantity) AS thePrice,SUM(cartQuantity) AS sumQuant,pSection,COUNT(cartOrigProdID),pExemptions,pTax FROM products INNER JOIN cart ON cart.cartOrigProdID=products.pID WHERE ' . getsessionsql() . ' AND cartOrigProdID<>\''.$giftcertificateid.'\' AND cartOrigProdID<>\''.$donationid.'\' AND cartOrigProdID<>\''.$giftwrappingid.'\' AND cartCompleted=0 AND pExemptions<64 GROUP BY cartOrigProdID,pSection,pExemptions,pTax';
		$cdresult=ect_query($sSQL) or ect_error();
		$cdadindex=0;
		while($cdrs=ect_fetch_assoc($cdresult)){
			$cdalldata[$cdadindex++]=$cdrs;
		}
		for($index=0; $index<$cdadindex; $index++){
			$sSQL='SELECT SUM(coPriceDiff*cartQuantity) AS totOpts FROM cart INNER JOIN cartoptions ON cart.cartID=cartoptions.coCartID WHERE cartCompleted=0 AND ' . getsessionsql() . " AND cartOrigProdID='" . $cdalldata[$index]['cartOrigProdID'] . "'";
			$cdresult2=ect_query($sSQL) or ect_error();
			$cdrs2=ect_fetch_assoc($cdresult2);
			if(! is_null($cdrs2['totOpts'])) $cdalldata[$index]['thePrice']+=$cdrs2['totOpts'];
			if(is_null($cdalldata[$index]['pTax'])) $cdalldata[$index]['pTax']=$countryTaxRate;
			$cdtotquant+=$cdalldata[$index]['sumQuant'];
			$cdtotprice+=$cdalldata[$index]['thePrice'];
		}
		for($index=0; $index<$cdadindex; $index++){
			$cdrs=$cdalldata[$index];
			$topcpnids=$cdrs['pSection'];
			$thetopts=$cdrs['pSection'];
			if(array_key_exists($cdrs['pSection'], $GLOBALS['topcpnids_cache'])){
				$topcpnids=$GLOBALS['topcpnids_cache'][$cdrs['pSection']];
			}else{
				for($cpnindex=0; $cpnindex<= 10; $cpnindex++){
					if($thetopts==0)
						break;
					else{
						$sSQL='SELECT topSection FROM sections WHERE sectionID=' . $thetopts;
						$result2=ect_query($sSQL) or ect_error();
						if($rs2=ect_fetch_assoc($result2)){
							$thetopts=$rs2['topSection'];
							$topcpnids.=',' . $thetopts;
						}else
							break;
					}
				}
				$GLOBALS['topcpnids_cache'][$cdrs['pSection']]=$topcpnids;
			}
			$attributelist='';
			$sSQL="SELECT mSCscID FROM multisearchcriteria WHERE mSCpID='".escape_string($cdrs['cartOrigProdID'])."'";
			$result2=ect_query($sSQL) or ect_error();
			while($rs2=ect_fetch_assoc($result2))
				$attributelist.=$rs2['mSCscID'].' ';
			ect_free_result($result2);
			$sSQL='SELECT DISTINCT cpnID,cpnDiscount,cpnType,cpnNumber,'.getlangid('cpnName',1024).",cpnThreshold,cpnQuantity,cpnSitewide,cpnThresholdRepeat,cpnQuantityRepeat FROM coupons LEFT OUTER JOIN cpnassign ON coupons.cpnID=cpnassign.cpaCpnID WHERE cpnNumAvail>0 AND cpnStartDate<='" . date('Y-m-d', time()+($GLOBALS['dateadjust']*60*60)) ."' AND cpnEndDate>='" . date('Y-m-d', time()+($GLOBALS['dateadjust']*60*60)) ."' AND (cpnIsCoupon=0";
			if($cdcpncode!='') $sSQL.=" OR (cpnIsCoupon=1 AND cpnNumber='" . $cdcpncode . "')";
			$sSQL.=') AND ' .
				'((cpnSitewide<>4 AND cpnThreshold<=' . $cdrs['thePrice'] . ') OR (cpnSitewide=4 AND cpnThreshold<=' . $cdtotprice . ')) AND ((cpnSitewide<>4 AND cpnThresholdMax>' . $cdrs['thePrice'] . ') OR (cpnSitewide=4 AND cpnThresholdMax>' . $cdtotprice . ') OR cpnThresholdMax=0) AND ' .
				'((cpnSitewide<>4 AND cpnQuantity<=' . $cdrs['sumQuant'] . ') OR (cpnSitewide=4 AND cpnQuantity<=' . $cdtotquant . ')) AND ((cpnSitewide<>4 AND cpnQuantityMax>' . $cdrs['sumQuant'] . ') OR (cpnSitewide=4 AND cpnQuantityMax>' . $cdtotquant . ') OR cpnQuantityMax=0) AND ' .
				'(cpnSitewide=0 OR cpnSitewide=2 OR cpnSitewide=4) AND ' .
				"(cpnSitewide=2 OR (cpaType=2 AND cpaAssignment='" . $cdrs['cartOrigProdID'] . "') ";
			if($attributelist!='') $sSQL.="OR (cpaType=3 AND cpaAssignment IN ('".str_replace(' ',"','",trim($attributelist))."')) ";
			$sSQL.="OR (cpaType=1 AND cpaAssignment IN ('" . str_replace(',',"','",$topcpnids) . "')))" .
				' AND ((cpnLoginLevel>=0 AND cpnLoginLevel<='.$minloglevel.') OR (cpnLoginLevel<0 AND -1-cpnLoginLevel='.$minloglevel.'))';
			$result2=ect_query($sSQL) or ect_error();
			while($rs2=ect_fetch_assoc($result2)){
				if($rs2['cpnType']==0 && !$allfreeshipexempt){ // Free Ship Discount
					addadiscount($rs2, FALSE, 0, $subcpns, $cdcpncode, 0, 0, 0, 0);
					for($index2=0;$index2<$GLOBALS['itemsincart'];$index2++){
						if($cdrs['cartOrigProdID']==$GLOBALS['cartrows'][$index2]['cartProdID']||$cdrs['cartOrigProdID']==$GLOBALS['cartrows'][$index2]['cartOrigProdID']){
							$GLOBALS['cartrows'][$index2]['shipFree']=1;
						}
					}
					$freeshippingapplied=TRUE;
				}elseif($rs2['cpnType']==1){ // Flat Rate Discount
					$thedisc=(float)$rs2['cpnDiscount'] * timesapply($cdrs['sumQuant'], $cdrs['thePrice'], $rs2['cpnQuantity'], $rs2['cpnThreshold'], $rs2['cpnQuantityRepeat'], $rs2['cpnThresholdRepeat']);
					if($cdrs['thePrice'] < $thedisc) $thedisc=$cdrs['thePrice'];
					addadiscount($rs2, FALSE, $thedisc, $subcpns, $cdcpncode, $statetaxhandback, $countrytaxhandback, $cdrs['pExemptions'], $cdrs['pTax']);
				}elseif($rs2['cpnType']==2){ // Percentage Discount
					addadiscount($rs2, FALSE, (((float)$rs2['cpnDiscount'] * (float)$cdrs['thePrice']) / 100.0), $subcpns, $cdcpncode, $statetaxhandback, $countrytaxhandback, $cdrs['pExemptions'], $cdrs['pTax']);
				}
			}
		}
		$sSQL='SELECT DISTINCT cpnID,cpnDiscount,cpnType,cpnNumber,'.getlangid('cpnName',1024).",cpnSitewide,cpnThreshold,cpnThresholdMax,cpnQuantity,cpnQuantityMax,cpnThresholdRepeat,cpnQuantityRepeat FROM coupons WHERE cpnNumAvail>0 AND cpnStartDate<='" . date('Y-m-d', time()+($GLOBALS['dateadjust']*60*60)) ."' AND cpnEndDate>='" . date('Y-m-d', time()+($GLOBALS['dateadjust']*60*60)) ."' AND (cpnIsCoupon=0";
		if($cdcpncode!='') $sSQL.=" OR (cpnIsCoupon=1 AND cpnNumber='" . $cdcpncode . "')";
		$sSQL.=') AND cpnThreshold<=' . $cdtotprice . ' AND cpnQuantity<=' . $cdtotquant . ' AND (cpnSitewide=1 OR cpnSitewide=3) AND (cpnType=0 OR cpnType=1 OR cpnType=2)' .
			' AND ((cpnLoginLevel>=0 AND cpnLoginLevel<='.$minloglevel.') OR (cpnLoginLevel<0 AND -1-cpnLoginLevel='.$minloglevel.'))';
		$result2=ect_query($sSQL) or ect_error();
		while($rs2=ect_fetch_assoc($result2)){
			if($rs2['cpnSitewide']==3){
				$sSQL='SELECT cpaType,cpaAssignment FROM cpnassign WHERE (cpaType=1 OR cpaType=3) AND cpacpnID=' . $rs2['cpnID'];
				$result3=ect_query($sSQL) or ect_error();
				$secids=$attributeids='';
				while($rs3=ect_fetch_assoc($result3)){
					if($rs3['cpaType']==1)$secids.=$rs3['cpaAssignment'].' '; else $attributeids.=$rs3['cpaAssignment'].' ';
					$addcomma=',';
				}
				if($secids!=''||$attributeids!=''){
					$sectionidsql=' AND (';
					if($secids!='') $sectionidsql.='products.pSection IN (' . getsectionids(str_replace(' ',',',trim($secids)),FALSE) . ')';
					if($attributeids!='') $sectionidsql.=($secids!=''?' OR ':'') . 'multisearchcriteria.mSCscID IN (' . str_replace(' ',',',trim($attributeids)) . ')';
					$sectionidsql.=')';
				}else
					$sectionidsql='notassigned';
			}else // cpnSitewide==1
				$sectionidsql='';
			$totquant=$totprice=0;
			$prodids=',';
			if($sectionidsql!='notassigned'){
				$sSQL='SELECT DISTINCT cartID,cartProdPrice,cartOrigProdID,cartQuantity,pExemptions FROM (products INNER JOIN cart ON cart.cartOrigProdID=products.pID) LEFT JOIN multisearchcriteria ON cart.cartOrigProdID=multisearchcriteria.mSCpID WHERE ' . getsessionsql() . $sectionidsql . " AND cartOrigProdID<>'".$giftcertificateid."' AND cartOrigProdID<>'".$donationid."' AND cartOrigProdID<>'".$giftwrappingid."' AND cartCompleted=0 AND pExemptions<64";
				$result4=ect_query($sSQL) or ect_error();
				while($rs4=ect_fetch_assoc($result4)){
					//if(($rs4['pExemptions']&16)!=16){
						$totprice+=($rs4['cartProdPrice']*$rs4['cartQuantity']);
						$totquant+=$rs4['cartQuantity'];
						$prodids.=$rs4['cartOrigProdID'] . ',';
						$sSQL="SELECT coPriceDiff FROM cartoptions WHERE coCartID=" . $rs4['cartID'];
						$result3=ect_query($sSQL) or ect_error();
						while($rs3=ect_fetch_assoc($result3)){
							$totprice+=($rs3['coPriceDiff']*$rs4['cartQuantity']);
						}
						ect_free_result($result3);
					//}
				}
				ect_free_result($result4);
			}
			if($totquant>0 && $rs2['cpnThreshold']<=$totprice && ($rs2['cpnThresholdMax']>$totprice || $rs2['cpnThresholdMax']==0) && $rs2['cpnQuantity']<=$totquant && ($rs2['cpnQuantityMax']>$totquant || $rs2['cpnQuantityMax']==0)){
				if($rs2['cpnType']==1){ // Flat Rate Discount
					$thedisc=(float)$rs2['cpnDiscount'] * timesapply($totquant, $totprice, $rs2['cpnQuantity'], $rs2['cpnThreshold'], $rs2['cpnQuantityRepeat'], $rs2['cpnThresholdRepeat']);
					if($totprice < $thedisc) $thedisc=$totprice;
				}elseif($rs2['cpnType']==2){ // Percentage Discount
					$thedisc=((float)$rs2['cpnDiscount'] * (float)$totprice) / 100.0;
				}
				if($rs2['cpnType']==1||$rs2['cpnType']==2){
					addadiscount($rs2, TRUE, $thedisc, $subcpns, $cdcpncode, $statetaxhandback, $countrytaxhandback, 3, 0);
					if(@$GLOBALS['perproducttaxrate'] && $cdtotprice>0){
						for($index=0; $index<$cdadindex; $index++){
							$cdrs=$cdalldata[$index];
							$applicdisc =0;
							if($rs2['cpnType']==1 && $cdrs['sumQuant']>0) // Flat Rate Discount
								$applicdisc=$thedisc / ($cdtotquant / $cdrs['sumQuant']);
							elseif($rs2['cpnType']==2 && $cdrs['thePrice']>0) // Percentage Discount
								$applicdisc=$thedisc / ($cdtotprice / $cdrs['thePrice']);
							if(($cdrs['pExemptions'] & 2)!=2) $countryTax -= (($applicdisc * $cdrs['pTax']) / 100.0);
						}
					}
				}elseif(!$allfreeshipexempt){
					addadiscount($rs2, FALSE, 0, $subcpns, $cdcpncode, 0, 0, 0, 0);
					for($index2=0;$index2<$GLOBALS['itemsincart'];$index2++){
						if(strpos($prodids,','.$GLOBALS['cartrows'][$index2]['cartProdID'].',')!==FALSE||strpos($prodids,','.$GLOBALS['cartrows'][$index2]['cartOrigProdID'].',')!==FALSE){
							$GLOBALS['cartrows'][$index2]['shipFree']=1;
						}
					}
				}
			}
		}
		ect_query("UPDATE cart SET cartOrigProdID='' WHERE cartOrigProdID=cartProdID AND " . getsessionsql()) or ect_error();
	}
	if($statetaxfree < 0) $statetaxfree=0;
	if($countrytaxfree < 0) $countrytaxfree=0;
	$totaldiscounts=round($totaldiscounts, 2);
}
function calculateshippingdiscounts($subcpns){
	global $freeshippingapplied,$nodiscounts,$totalgoods,$totalquantity,$rgcpncode,$freeshipavailtodestination,$freeshipmethodexists,$cpnmessage,$shipping,$freeshipamnt,$gotcpncode,$handling,$handlingchargepercent,$freeshippingincludeshandling,$freeshippingincludesservices;
	global $somethingToShip,$shipType,$maxshipoptions,$intShipping,$selectedshiptype,$iTotItems,$numuspsmeths,$uspsmethods,$shipMethod,$fromshipselector,$minloglevel,$shippingafterproductdiscounts,$totaldiscounts,$allfreeshipexempt,$shipdiscountexempt,$numshipdiscountexempt;
	$freeshipamnt=0;
	if($allfreeshipexempt) $freeshipmethodexists=FALSE;
	unset($_SESSION['tofreeshipquant']);
	unset($_SESSION['tofreeshipamount']);
	if(! $nodiscounts){
		$sSQL='SELECT cpnID,'.getlangid('cpnName',1024).',cpnNumber,cpnDiscount,cpnThreshold,cpnCntry,cpnHandling,cpnInsurance FROM coupons WHERE cpnType=0 AND cpnSitewide=1 AND cpnNumAvail>0 AND cpnThreshold<='.($totalgoods-($shipdiscountexempt+(@$shippingafterproductdiscounts?$totaldiscounts:0))).' AND (cpnThresholdMax>'.($totalgoods-($shipdiscountexempt+(@$shippingafterproductdiscounts?$totaldiscounts:0))).' OR cpnThresholdMax=0) AND cpnQuantity<='.($totalquantity-$numshipdiscountexempt).' AND (cpnQuantityMax>'.($totalquantity-$numshipdiscountexempt)." OR cpnQuantityMax=0) AND cpnStartDate<='" . date('Y-m-d', time()+($GLOBALS['dateadjust']*60*60)) ."' AND cpnEndDate>='" . date('Y-m-d', time()+($GLOBALS['dateadjust']*60*60)) ."' AND (cpnIsCoupon=0 OR (cpnIsCoupon=1 AND cpnNumber='".$rgcpncode."'))" .
			' AND ((cpnLoginLevel>=0 AND cpnLoginLevel<='.$minloglevel.') OR (cpnLoginLevel<0 AND -1-cpnLoginLevel='.$minloglevel.'))';
		$result=ect_query($sSQL) or ect_error();
		while($rs=ect_fetch_assoc($result)){
			if($freeshipavailtodestination || (int)$rs['cpnCntry']==0){
				if($rgcpncode!='' && strtolower(trim($rs['cpnNumber']))==strtolower($rgcpncode)){ $gotcpncode=TRUE; $appliedcouponname=$rs['cpnName']; }
				if($freeshipmethodexists){
					if($fromshipselector){
						if($intShipping[$selectedshiptype][4]==1){
							$freeshipamnt=$intShipping[$selectedshiptype][2] - ($intShipping[$selectedshiptype][7] + getfreeshipinsurance($selectedshiptype));
							if(stristr($cpnmessage,'<br>' . $rs[getlangid('cpnName',1024)] . '<br>')==FALSE) $cpnmessage.=$rs[getlangid('cpnName',1024)] . '<br>';
						}
					}else{
						if($intShipping[$selectedshiptype][3]) $freeshipamnt=$intShipping[$selectedshiptype][2] - ($intShipping[$selectedshiptype][7] + getfreeshipinsurance($selectedshiptype));
						if(stristr($cpnmessage,'<br>' . $rs[getlangid('cpnName',1024)] . '<br>')==FALSE) $cpnmessage.=$rs[getlangid('cpnName',1024)] . '<br>';
					}
					if($rs['cpnHandling']!=0){ $freeshippingincludeshandling=TRUE; $handling=0; $handlingchargepercent=0; }
					if($rs['cpnInsurance']!=0) $freeshippingincludesservices=TRUE;
					if($subcpns){
						$theres=ect_query('SELECT cpnID FROM coupons WHERE cpnNumAvail>0 AND cpnNumAvail<30000000 AND cpnID=' . $rs['cpnID'] . ' AND ((cpnLoginLevel>=0 AND cpnLoginLevel<='.$minloglevel.') OR (cpnLoginLevel<0 AND -1-cpnLoginLevel='.$minloglevel.'))') or ect_error();
						if($theresset=ect_fetch_assoc($theres)) @$_SESSION['couponapply'].=',' . $rs['cpnID'];
						//ect_query('UPDATE coupons SET cpnNumAvail=cpnNumAvail-1 WHERE cpnNumAvail>0 AND cpnNumAvail<30000000 AND cpnID=' . $rs['cpnID']) or ect_error();
					}
					$freeshippingapplied=TRUE;
				}
			}
		}
		ect_free_result($result);
	}
	if($somethingToShip && ! $fromshipselector){
		$gotshipping=FALSE;
		if($shipType>=1){
			if($shipType==2 || $shipType==5) sortshippingarray();
			for($indexmso=0; $indexmso<$maxshipoptions; $indexmso++){
				if($intShipping[$indexmso][3]==TRUE){
					if(!$gotshipping || ($intShipping[$indexmso][4]&&$freeshippingapplied)){
						$shipping=$intShipping[$indexmso][2];
						$shipMethod=$intShipping[$indexmso][0];
						$selectedshiptype=$indexmso;
						$gotshipping=TRUE;
					}
					if($intShipping[$indexmso][4]&&$freeshippingapplied) $freeshipamnt=$intShipping[$indexmso][2] - ($intShipping[$indexmso][7] + getfreeshipinsurance($indexmso));
				}
			}
		}
		if(! $freeshippingapplied && $freeshipmethodexists){
			$sSQL='SELECT MIN(cpnQuantity) AS minquant,MIN(cpnThreshold) as minthreshold FROM coupons WHERE cpnType=0 AND cpnSitewide=1 AND cpnNumAvail>0 AND (cpnThresholdMax>'.($totalgoods-($shipdiscountexempt+(@$shippingafterproductdiscounts?$totaldiscounts:0))).' OR cpnThresholdMax=0) AND (cpnQuantityMax>'.($totalquantity-$numshipdiscountexempt)." OR cpnQuantityMax=0) AND cpnStartDate<='" . date('Y-m-d', time()+($GLOBALS['dateadjust']*60*60)) ."' AND cpnEndDate>='" . date('Y-m-d', time()+($GLOBALS['dateadjust']*60*60)) ."' AND (cpnIsCoupon=0 OR (cpnIsCoupon=1 AND cpnNumber='".$rgcpncode."'))" .
				' AND ((cpnLoginLevel>=0 AND cpnLoginLevel<='.$minloglevel.') OR (cpnLoginLevel<0 AND -1-cpnLoginLevel='.$minloglevel.'))';
			$result=ect_query($sSQL) or ect_error();
			$rs=ect_fetch_assoc($result);
			if(! is_null($rs['minquant'])){
				if($rs['minquant']-($totalquantity-$shipdiscountexempt)>0) $_SESSION['tofreeshipquant']=$rs['minquant']-($totalquantity-$numshipdiscountexempt);
				if($rs['minthreshold']-($totalgoods-($shipdiscountexempt+(@$shippingafterproductdiscounts?$totaldiscounts:0)))>0) $_SESSION['tofreeshipamount']=$rs['minthreshold']-($totalgoods-($shipdiscountexempt+(@$shippingafterproductdiscounts?$totaldiscounts:0)));
			}
			ect_free_result($result);
		}
	}
	if($freeshipamnt>$shipping) $freeshipamnt=$shipping;
}
function getshiptype(){
	global $shipType,$adminIntShipping,$shipcountry,$origCountry,$shipCountryCode,$usandcausedomesticservice,$cartisincluded;
	if($adminIntShipping!=0 && $shipcountry!=$origCountry && ! (($shipCountryCode=='US' || $shipCountryCode=='CA') && @$usandcausedomesticservice)){
		if($cartisincluded || getpost('altrates')=='') $shipType=$adminIntShipping;
	}
	return $shipType;
}
function getadminshippingparams(){
	global $shipType;
	
	$sSQL='SELECT adminPacking,AusPostAPI,adminCanPostUser,adminCanPostLogin,adminCanPostPass,adminUSPSUser,uspsPw,uspsAccount,uspsCommercial,uspsAccessToken,uspsCntnrFE,uspsCntnrFB,uspsCntnrFP,uspsCntnrFS,uspsCntnrPL,uspsCntnrSB,uspsTokenTimeout,smartPostHub,adminUPSUser,adminUPSpw,adminUPSAccess,adminUPSAccess2,adminUPSAccessTime,adminUPSAccount,adminUPSNegotiated,FedexAccountNo,FedexMeter,FedexUserKey,FedexUserPwd,DHLSiteID,DHLSitePW,DHLAccountNo FROM adminshipping WHERE adminShipID=1';
	$result=ect_query($sSQL) or ect_error();
	$rs=ect_fetch_assoc($result);
	$GLOBALS['AusPostAPI']=trim($rs['AusPostAPI']);
	$GLOBALS['adminCanPostUser']=trim($rs['adminCanPostUser']);
	$GLOBALS['adminCanPostLogin']=trim($rs['adminCanPostLogin']);
	$GLOBALS['adminCanPostPass']=trim($rs['adminCanPostPass']);
	$GLOBALS['packtogether']=((int)$rs['adminPacking']==1);
	$GLOBALS['uspsUser']=$rs['adminUSPSUser'];
	$GLOBALS['uspsPw']=$rs['uspsPw'];
	$GLOBALS['uspsAccount']=$rs['uspsAccount'];
	$GLOBALS['uspsCommercial']=$rs['uspsCommercial'];
	
	$GLOBALS['uspsAccessToken']=$rs['uspsAccessToken'];
	$GLOBALS['uspsTokenTimeout']=$rs['uspsTokenTimeout'];

	$GLOBALS['uspsCntnrFE']=$rs['uspsCntnrFE'];
	$GLOBALS['uspsCntnrFB']=$rs['uspsCntnrFB'];
	$GLOBALS['uspsCntnrFP']=$rs['uspsCntnrFP'];
	$GLOBALS['uspsCntnrFS']=$rs['uspsCntnrFS'];
	$GLOBALS['uspsCntnrPL']=$rs['uspsCntnrPL'];
	$GLOBALS['uspsCntnrSB']=$rs['uspsCntnrSB'];
	
	if(strlen($rs['adminUPSUser'])>40 || strlen($rs['adminUPSpw'])>40){
		$GLOBALS['upsuseoauth']=TRUE;
		$GLOBALS['upsUser']=$rs['adminUPSUser'];
		$GLOBALS['upsPw']=$rs['adminUPSpw'];
	}else{
		$GLOBALS['upsUser']=upsdecode($rs['adminUPSUser'], '');
		$GLOBALS['upsPw']=upsdecode($rs['adminUPSpw'], '');
	}
	$GLOBALS['smartPostHub']=$rs['smartPostHub'];
	$GLOBALS['upsAccess']=$rs['adminUPSAccess'];
	$GLOBALS['upsAccess2']=$rs['adminUPSAccess2'];
	$GLOBALS['upsAccessTime']=$rs['adminUPSAccessTime'];
	$GLOBALS['upsAccount']=$rs['adminUPSAccount'];
	$GLOBALS['upsnegdrates']=$rs['adminUPSNegotiated'];
	$GLOBALS['fedexaccount']=$rs['FedexAccountNo'];
	$GLOBALS['fedexmeter']=$rs['FedexMeter'];
	$GLOBALS['fedexuserkey']=$rs['FedexUserKey'];
	$GLOBALS['fedexuserpwd']=$rs['FedexUserPwd'];
	$GLOBALS['DHLSiteID']=$rs['DHLSiteID'];
	$GLOBALS['DHLSitePW']=$rs['DHLSitePW'];
	$GLOBALS['DHLAccountNo']=$rs['DHLAccountNo'];
	ect_free_result($result);
}
function initshippingmethods(){
	global $shipType,$adminShipping,$adminIntShipping,$allzones,$numzones,$splitUSZones,$shiphomecountry,$numshipoptions,$intShipping,$success,$errormsg,$commercialloc_,$codpaymentprovider,$signaturerelease_,$allowsignaturerelease,$signatureoption,$saturdaydelivery_,$saturdaypickup,$insidedelivery_,$insidepickup,$thesessionid,$willpickup_,$selectedshiptype,$currShipType,$ordShipCity,$countryCurrency,$DHLSiteID,$DHLSitePW,$shipCountryID,$adminCanPostLogin,$adminCanPostPass,$packtogether,$returntocustomerdetails;
	global $uspsmethods,$numuspsmeths,$international,$shipcountry,$maxshipoptions,$origCountry,$willpickuptext,$willpickupcost,$shipstate,$shipinsuranceamt,$fedexaccount,$fedexmeter,$stateAbbrev,$shipStateAbbrev,$usestateabbrev,$ordPayProvider,$adminAltRates,$altrate,$shipping,$willpickupnohandling,$handling,$orighandling,$handlingchargepercent,$orighandlingpercent,$shipMethod,$freeshipmethodexists,$multipleoptions,$fedexuserkey,$fedexuserpwd,$fedexpickuptype,$smartPostHub,$smartpostindicia,$smartpostancendorsement,$paypalexpress;
	global $sXML,$uspsUser,$upsAccess,$upsUser,$upsPw,$upspickuptype,$origZip,$origCountryCode,$destZip,$shipCountryCode,$adminCanPostUser,$packaging,$adminUnits,$homedelivery,$originstatecode,$ordCity,$ordAddress,$ordAddress2,$ordShipAddress,$ordShipAddress2,$upsnegdrates,$upsAccount,$fromshipselector,$thepweight,$initialpackweight,$storelang,$splitpackat,$nosplitlargepacks,$addshippinginsurance;
	if($shipcountry!=$origCountry && ! ($shipType==3 && $shipCountryCode=='PR')){
		$international='Intl';
		if(!@$GLOBALS['willpickupinternational']){
			$willpickuptext='';
			$willpickup_=FALSE;
		}
	}
	if($willpickup_){
		$shipType=0;
		$adminAltRates=0;
		$addshippinginsurance=0;
		if(@$willpickupcost!='') $shipping=$willpickupcost; else $shipping=0;
		$shipMethod=$willpickuptext;
		if(@$willpickupnohandling) $handlingchargepercent=$handling=$orighandling=$orighandlingpercent=0;
	}
	if($adminAltRates>0){
		$result=ect_query('SELECT altrateid FROM alternaterates WHERE usealtmethod'.$international.'<>0') or ect_error();
		if(ect_num_rows($result)<2) $adminAltRates=0;
		ect_free_result($result);
	}
	if($altrate!='' && $adminAltRates>0){
		$result=ect_query('SELECT altrateid FROM alternaterates WHERE usealtmethod'.$international.'<>0 AND altrateid='.$altrate) or ect_error();
		if(ect_num_rows($result)>0) $shipType=$altrate;
		ect_free_result($result);
	}
	if($shipType==3 && strlen($GLOBALS['uspsUser'])>42){
		$GLOBALS['uspsuseoauth']=TRUE;
		$GLOBALS['packtogether']=TRUE;
	}
	if(@$initialpackweight!='' && $shipType!=5) $thepweight=$initialpackweight;
	if($shipType==11) $GLOBALS['packtogether']=TRUE;
	for($i=0; $i < $maxshipoptions; $i++){
		$intShipping[$i][0]=''; // Name
		$intShipping[$i][1]=''; // Delivery
		$intShipping[$i][2]=0; // Cost
		$intShipping[$i][3]=0; // Used
		$intShipping[$i][4]=0; // FSA
		$intShipping[$i][5]=''; // Service ID (USPS)
		$intShipping[$i][6]=$shipType; // shipType
		$intShipping[$i][7]=0; // Cost for Free Ship Exempt
		$intShipping[$i][8]=0; // Cost for Insurance + Services
	}
	if($fromshipselector){
		if(is_numeric(getpost('orderid')) && is_numeric(getpost('shipselectoridx'))){
			$numshipoptions=0;
			$sSQL='SELECT soMethodName,soCost,soFreeShipExempt,soFreeShip,soShipType,soDeliveryTime FROM shipoptions WHERE soOrderID=' . getpost('orderid') . ' ORDER BY soIndex';
			$result=ect_query($sSQL) or ect_error();
			while($rs=ect_fetch_assoc($result)){
				$intShipping[$numshipoptions][0]=$rs['soMethodName'];
				$intShipping[$numshipoptions][1]=$rs['soDeliveryTime'];
				$intShipping[$numshipoptions][2]=$rs['soCost'];
				$intShipping[$numshipoptions][3]=TRUE;
				$intShipping[$numshipoptions][4]=$rs['soFreeShip'];
				$freeshipmethodexists=($freeshipmethodexists || $intShipping[$numshipoptions][4]);
				$intShipping[$numshipoptions][6]=$rs['soShipType'];
				$intShipping[$numshipoptions][7]=$rs['soFreeShipExempt'];
				$numshipoptions++;
			}
			ect_free_result($result);
			$selectedshiptype=(int)getpost('shipselectoridx');
			$shipping=$intShipping[$selectedshiptype][2];
			$shipMethod=$intShipping[$selectedshiptype][0];
			$shipType=$intShipping[$selectedshiptype][6];
			$currShipType=$intShipping[0][6];
			$multipleoptions=TRUE;
			$numshipoptions--;
		}
	}elseif($shipType==1){ // Flat rate shipping
		$intShipping[0][0]=(@$GLOBALS['combineshippinghandling'] ? $GLOBALS['xxShipHa'] : $GLOBALS['xxShippg']);
		$intShipping[0][3]=TRUE;
		$intShipping[0][4]=1;
	}elseif($shipType==2 || $shipType==5){ // Weight / Price based shipping
		$allzones=[];
		$numzones=0;
		$zoneid=0;
		if($splitUSZones && $shiphomecountry && is_numeric($shipCountryID)){
			if($paypalexpress && $shipCountryID==201) $shipstate=str_replace(
				array('East Ayrshire','North Ayrshire','South Ayrshire','East Riding of Yorkshire','Greater Manchester','Argyll and Bute','Edinburgh City','Aberdeen City','Clackmannan','Glasgow (City of)','Antrim','Armagh','Down','Fermanagh','Londonderry','Tyrone','Humberside','North East Lincolnshire','Dumfries and Galloway','East Dunbartonshire','East Renfrewshire','North Lanarkshire','Perthshire and Kinross','South Lanarkshire','Stirling','West Dunbartonshire','Blaenau Gwent','Isle of Anglesey','Merthyr Tydfil','Caerphilly','Conwy','Newport','Swansea','Torfaen','The Vale of Glamorgan','Wrexham','Neath Port Talbot','Bridgend','Western Isles','Inverclyde','Falkirk'),
				array('Ayrshire','Ayrshire','Ayrshire','Yorkshire','Manchester','Argyll','Edinburgh','Aberdeenshire','Clackmannanshire','Glasgow','County Antrim','County Armagh','County Down','County Fermanagh','County Londonderry','County Tyrone','North Humberside','Lincolnshire','Dumfriesshire','Dunbartonshire','Renfrewshire','Lanarkshire','Perthshire','Lanarkshire','Stirlingshire','Dunbartonshire','Gwent','Anglesey','Glamorgan','Glamorgan','Clwyd','Gwent','Glamorgan','Monmouthshire','Glamorgan','Clwyd','West Glamorgan','Mid Glamorgan','Inverness-shire','Renfrewshire','Stirlingshire'),
					$shipstate);
			$sSQL='states INNER JOIN postalzones ON postalzones.pzID=states.stateZone WHERE stateCountryID=' . $shipCountryID . " AND (stateName='" . escape_string($shipstate) . "' OR stateAbbrev='" . escape_string($shipstate) . "')";
		}else
			$sSQL="countries INNER JOIN postalzones ON postalzones.pzID=countries.countryZone WHERE countryName='" . escape_string($shipcountry) . "'";
		$result=ect_query('SELECT pzID,pzMultiShipping,pzFSA,pzMethodName1,pzMethodName2,pzMethodName3,pzMethodName4,pzMethodName5 FROM '.$sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			$zoneid=$rs['pzID'];
			$numshipoptions=$rs['pzMultiShipping']+1;
			for($index3=0; $index3 < $numshipoptions; $index3++){
				$intShipping[$index3][0]=$rs['pzMethodName' . ($index3+1)];
				$intShipping[$index3][3]=TRUE;
				$intShipping[$index3][4]=(($rs['pzFSA'] & (1 << $index3))>0 ? 1 : 0);
			}
		}else{
			$success=FALSE;
			if($splitUSZones && $shiphomecountry && $shipstate=='') $errormsg=$GLOBALS['xxPlsSta']; else $errormsg='Country / state shipping zone is unassigned.';
			$returntocustomerdetails=TRUE;
			return(FALSE);
		}
		ect_free_result($result);
		$sSQL='SELECT zcWeight,zcRate,zcRate2,zcRate3,zcRate4,zcRate5,zcRatePC,zcRatePC2,zcRatePC3,zcRatePC4,zcRatePC5 FROM zonecharges WHERE zcZone=' . $zoneid . ' ORDER BY zcWeight';
		$result=ect_query($sSQL) or ect_error();
		while($rs=ect_fetch_assoc($result))
			$allzones[$numzones++]=$rs;
		ect_free_result($result);
	}elseif($shipType==3 || $shipType==4 || $shipType>=6){ // USPS / UPS / Canada Post / FedEx / SmartPost / DHL
		$uspsmethods=[];
		$numuspsmeths=0;
		if($shipType==3){
			$sSQL=' uspsID<100 AND uspsLocal='.($international==''?'1':'0');
		}elseif($shipType==4)
			$sSQL=' uspsID>100 AND uspsID<200';
		elseif($shipType==6)
			$sSQL=' uspsID>200 AND uspsID<300';
		elseif($shipType==7)
			$sSQL=' uspsID>300 AND uspsID<400'.($international==''&&$commercialloc_?" AND uspsMethod<>'GROUNDHOMEDELIVERY'":'');
		elseif($shipType>=8)
			$sSQL=' uspsID>'.($shipType-4).'00 AND uspsID<'.($shipType-3).'00' . ($shipType==10 ? ' AND uspsLocal='.($international==''?'1':'0') : '');
		$result=ect_query('SELECT uspsMethod,uspsFSA,uspsShowAs,uspsLocal FROM uspsmethods WHERE'.$sSQL.' AND uspsUseMethod=1') or ect_error();
		if(ect_num_rows($result)>0){
			while($rs=ect_fetch_assoc($result))
				$uspsmethods[$numuspsmeths++]=$rs;
		}else{
			$success=FALSE;
			$errormsg='Admin Error: ' . $GLOBALS['xxNoMeth'];
		}
		ect_free_result($result);
	}
	if(($shipType==4 || $shipType==7 || $shipType==8 || $shipType==11) && $shipCountryCode=='US' && $shipStateAbbrev=='PR') $shipCountryCode='PR';
	if($shipType==3 && $shipCountryCode=='PR'){ $shipCountryCode='US'; $shipStateAbbrev='PR'; }
	if(($shipCountryCode=='PR' || ($shipCountryCode=='US' && $shipStateAbbrev=='PR')) && strlen($destZip)==3) $destZip='00'.$destZip;
	if($shipType==3){
		$sXML='';
		if(!$GLOBALS['uspsuseoauth']){
			$sXML='<' . $international . 'Rate' . ($international==''?'V4':'V2') . 'Request USERID="' . $uspsUser . '"><Revision>2</Revision>';
			// Convert shipping methods to old style.
			for($index2=0;$index2<$numuspsmeths;$index2++){
				if($uspsmethods[$index2]['uspsMethod']=='MEDIA_MAIL') $uspsmethods[$index2]['uspsMethod']='Media';
				if($uspsmethods[$index2]['uspsMethod']=='PARCEL_SELECT') $uspsmethods[$index2]['uspsMethod']='Parcel Select Ground';
				if($uspsmethods[$index2]['uspsMethod']=='BOUND_PRINTED_MATTER') $uspsmethods[$index2]['uspsMethod']='BPM';
				if($uspsmethods[$index2]['uspsMethod']=='USPS_RETAIL_GROUND') $uspsmethods[$index2]['uspsMethod']='Retail Ground';
				if($uspsmethods[$index2]['uspsMethod']=='USPS_GROUND_ADVANTAGE') $uspsmethods[$index2]['uspsMethod']='GROUND ADVANTAGE';
				if($uspsmethods[$index2]['uspsMethod']=='PRIORITY_MAIL_EXPRESS') $uspsmethods[$index2]['uspsMethod']='Priority Mail Express';
				if($uspsmethods[$index2]['uspsMethod']=='PRIORITY_MAIL') $uspsmethods[$index2]['uspsMethod']='PRIORITY';
				
				if($uspsmethods[$index2]['uspsMethod']=='PRIORITY_MAIL_INTERNATIONAL') $uspsmethods[$index2]['uspsMethod']='2';
				if($uspsmethods[$index2]['uspsMethod']=='PRIORITY_MAIL_EXPRESS_INTERNATIONAL') $uspsmethods[$index2]['uspsMethod']='1';
				if($uspsmethods[$index2]['uspsMethod']=='FIRST-CLASS_PACKAGE_INTERNATIONAL_SERVICE') $uspsmethods[$index2]['uspsMethod']='15';
			}
		}
	}elseif($shipType==4 || $shipType==11){
		if($shipCountryCode=='US' && $shipStateAbbrev=='VI') $shipCountryCode='VI';
		if(strlen($GLOBALS['upsUser'])>40||strlen($GLOBALS['upsPw'])>40){
			$sXML='{
				"RateRequest":{
					"Shipment":{
						"Shipper":{
							"ShipperNumber":' . json_encode($GLOBALS['upsAccount']) . ',
							"Address":{"PostalCode":' . json_encode($origZip) . ',"CountryCode":' . json_encode($origCountryCode) . '}
						},
						"ShipTo":{
							"Address":{
								"AddressLine":[
									' . json_encode($ordShipAddress!=''?$ordShipAddress:$ordAddress) . ',
									' . json_encode($ordShipAddress!=''?$ordShipAddress2:$ordAddress2) . '
								],'
								. ($shipCountryCode=='US'||$shipCountryCode=='CA'?'"StateProvinceCode":' . json_encode($shipStateAbbrev) . ',':'') . '
								"PostalCode":' . json_encode($destZip) . ',"CountryCode":' . json_encode($shipCountryCode) .
								(! $commercialloc_ ? ',"ResidentialAddressIndicator":"Y"' : '') . '
							}
						},
						' . ($shipType==11?'"Service":{"Code":"093"},':'') . '
						"ShipFrom":{
							"Address":{
								' . (@$upsnegdrates ? '"StateProvinceCode":"' . @$GLOBALS['defaultshipstate'] . '",': '') . '
								"PostalCode":' . json_encode($origZip) . ',
								"CountryCode":' . json_encode($origCountryCode) . '
							}
						},' . (@$upspickuptype!=''?'"Service":{"Code":' . json_encode($upspickuptype) . '},':'') . '
						"Package":[';
		}else{
			$sXML='<?xml version="1.0"?><AccessRequest xml:lang="en-US">' . addtag('AccessLicenseNumber',$upsAccess) . addtag('UserId',$upsUser) . addtag('Password',$upsPw) . '</AccessRequest><?xml version="1.0"?>' .
				'<RatingServiceSelectionRequest xml:lang="en-US"><Request><TransactionReference><CustomerContext>Rating and Service</CustomerContext><XpciVersion>1.0001</XpciVersion></TransactionReference>' .
				'<RequestAction>Rate</RequestAction><RequestOption>' . ($shipType==11?'Rate':'shop') . '</RequestOption></Request>';
			if(@$upspickuptype!='') $sXML.='<PickupType><Code>' . $upspickuptype . '</Code></PickupType>';
			$sXML.='<Shipment><Shipper>' . (@$upsnegdrates || $shipType==11? addtag('ShipperNumber',$upsAccount) : '') . '<Address>' . (@$upsnegdrates ? addtag('StateProvinceCode',@$GLOBALS['defaultshipstate']) : '') . addtag('PostalCode',$origZip) . addtag('CountryCode',$origCountryCode) . '</Address></Shipper>' .
				'<ShipTo><Address>' . addtag('AddressLine1',$ordShipAddress!=''?$ordShipAddress:$ordAddress) . addtag('AddressLine2',$ordShipAddress2!=''?$ordShipAddress2:$ordAddress2) . addtag('City',$ordShipCity!=''?$ordShipCity:$ordCity) . ($shipCountryCode=='US'||$shipCountryCode=='CA'?addtag('StateProvinceCode',$shipStateAbbrev):'') . addtag('PostalCode',$destZip) . addtag('CountryCode',$shipCountryCode) . (! $commercialloc_ ? '<ResidentialAddressIndicator/>' : '') . '</Address></ShipTo>';
			if($shipType==11) $sXML.='<Service><Code>93</Code></Service>';
		}
	}elseif($shipType==6){
		$packtogether=TRUE; $splitpackat=''; $nosplitlargepacks=TRUE; // Canada Post cannot handle more than one package
		$sXML='<soapenv:Envelope xmlns:rate="http://www.canadapost.ca/ws/soap/ship/rate/v2" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">' .
			'<soapenv:Header><wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"><wsse:UsernameToken><wsse:Username>' . $adminCanPostLogin . '</wsse:Username><wsse:Password>' . $adminCanPostPass . '</wsse:Password></wsse:UsernameToken></wsse:Security></soapenv:Header>' .
			'<soapenv:Body><rate:get-rates-request><platform-id>0008107483</platform-id>' . ($storelang=='fr'?'<locale>FR</locale>':'') . '<mailing-scenario><customer-number>' . $adminCanPostUser . '</customer-number><origin-postal-code>' . strtoupper(str_replace(' ','',$origZip)) . '</origin-postal-code><destination>';
		if($shipCountryCode=='CA')
			$sXML.='<domestic><postal-code>' . strtoupper(str_replace(' ','',$destZip)) . '</postal-code></domestic>';
		elseif($shipCountryCode=='US')
			$sXML.='<united-states><zip-code>' . $destZip . '</zip-code></united-states>';
		else
			$sXML.='<international><country-code>' . $shipCountryCode . '</country-code></international>';
		$sXML.='</destination>';
	}elseif($shipType==7 || $shipType==8){ // FedEx
		if(@$packaging!='') $fedexpackaging='FEDEX_' . strtoupper($packaging); else $fedexpackaging='YOUR_PACKAGING';
		if(@$fedexpickuptype=='') $fedexpickuptype='REGULAR_PICKUP';
		$fedextimestamp='';
		if($saturdaydelivery_==TRUE)
			$fedextimestamp='2010-03-12';
		elseif(@$GLOBALS['noweekendshipment']){
			if((int)date('w')==0)$fedextimestamp=time()+(60*60*24);
			if((int)date('w')==6)$fedextimestamp=time()+(2*60*60*24);
			if($fedextimestamp!='') $fedextimestamp=date('Y-m-d',$fedextimestamp);
		}
		if($fedextimestamp!='') $fedextimestamp=$fedextimestamp='<v9:ShipTimestamp>'.$fedextimestamp.'T10:00:00-04:00</v9:ShipTimestamp>';
		$sXML='<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v9="http://fedex.com/ws/rate/v9">' .
		"<soapenv:Header/><soapenv:Body><v9:RateRequest><v9:WebAuthenticationDetail><v9:CspCredential><v9:Key>mKOUqSP4CS0vxaku</v9:Key><v9:Password>IAA5db3Pmhg3lyWW6naMh4Ss2</v9:Password></v9:CspCredential>" .
		"<v9:UserCredential><v9:Key>" . $fedexuserkey . "</v9:Key><v9:Password>" . $fedexuserpwd . "</v9:Password></v9:UserCredential></v9:WebAuthenticationDetail>" .
		"<v9:ClientDetail><v9:AccountNumber>" . $fedexaccount . "</v9:AccountNumber><v9:MeterNumber>" . $fedexmeter . "</v9:MeterNumber><v9:ClientProductId>IBTP</v9:ClientProductId><v9:ClientProductVersion>3272</v9:ClientProductVersion></v9:ClientDetail>" .
		"<v9:TransactionDetail><v9:CustomerTransactionId>Rate Request</v9:CustomerTransactionId></v9:TransactionDetail>" .
		"<v9:Version><v9:ServiceId>crs</v9:ServiceId><v9:Major>9</v9:Major><v9:Intermediate>0</v9:Intermediate><v9:Minor>0</v9:Minor></v9:Version>" .
		"<v9:ReturnTransitAndCommit>true</v9:ReturnTransitAndCommit>" .
		'<v9:RequestedShipment>' . $fedextimestamp . '<v9:DropoffType>' . $fedexpickuptype . "</v9:DropoffType>" . ($shipType==8?'<v9:ServiceType>SMART_POST</v9:ServiceType>':'<v9:PackagingType>'.$fedexpackaging.'</v9:PackagingType>') .
		"<v9:Shipper><v9:Address><v9:PostalCode>" . $origZip . "</v9:PostalCode><v9:CountryCode>" . $origCountryCode . "</v9:CountryCode>" .
		"</v9:Address></v9:Shipper><v9:Recipient><v9:Address>";
		if($ordShipAddress!='') $sXML.="<v9:StreetLines>" . vrxmlencode($ordShipAddress) . "</v9:StreetLines>";
		if($ordShipCity!='') $sXML.="<v9:City>" . $ordShipCity . "</v9:City>";
		if($shipCountryCode=="US" || $shipCountryCode=="CA") $sXML.="<v9:StateOrProvinceCode>" . $shipStateAbbrev . "</v9:StateOrProvinceCode>";
		$sXML.="<v9:PostalCode>" . $destZip . "</v9:PostalCode>" .
		"<v9:CountryCode>" . $shipCountryCode . "</v9:CountryCode><v9:Residential>" . ($commercialloc_ ? "false" : "true") . "</v9:Residential></v9:Address></v9:Recipient>";
		if($shipType==8){
			if(@$smartpostindicia=='') $smartpostindicia='PARCEL_SELECT';
			$sXML.="<v9:SmartPostDetail><v9:Indicia>" . $smartpostindicia . "</v9:Indicia>" . (@$smartpostancendorsement!='' ? "<v9:AncillaryEndorsement>" . $smartpostancendorsement . "</v9:AncillaryEndorsement>" : '') . "<v9:HubId>" . $smartPostHub . "</v9:HubId></v9:SmartPostDetail>";
		}else{
			$sXML.="<v9:SpecialServicesRequested>";
			if($saturdaydelivery_==TRUE) $sXML.="<v9:SpecialServiceTypes>SATURDAY_DELIVERY</v9:SpecialServiceTypes>";
			if($saturdaypickup==TRUE) $sXML.="<v9:SpecialServiceTypes>SATURDAY_PICKUP</v9:SpecialServiceTypes>";
			if($insidedelivery_==TRUE) $sXML.="<v9:SpecialServiceTypes>INSIDE_DELIVERY</v9:SpecialServiceTypes>";
			if($insidepickup==TRUE) $sXML.="<v9:SpecialServiceTypes>INSIDE_PICKUP</v9:SpecialServiceTypes>";
			if(@$emailnotification==TRUE) $sXML.="<v9:SpecialServiceTypes>EMAIL_NOTIFICATION</v9:SpecialServiceTypes>";
			if(getpost('homedelivery')!='') $sXML.="<v9:SpecialServiceTypes>HOME_DELIVERY_PREMIUM</v9:SpecialServiceTypes><v9:HomeDeliveryPremiumDetail><v9:HomeDeliveryPremiumType>" . getpost('homedelivery') . "</v9:HomeDeliveryPremiumType></v9:HomeDeliveryPremiumDetail>";
			if($ordPayProvider!=''){
				//if(int(ordPayProvider)=codpaymentprovider then $sXML.="<v9:SpecialServiceTypes>COD</v9:SpecialServiceTypes><v9:CodDetail><v9:CodCollectionAmount><v9:Currency>CAD</v9:Currency><v9:Amount>XXXFEDEXGRANDTOTXXX</v9:Amount></v9:CodCollectionAmount><v9:CollectionType>ANY</v9:CollectionType></v9:CodDetail>"
			}
			if(@$holdatlocation==TRUE) $sXML.="<v9:SpecialServiceTypes>HOLD_AT_LOCATION</v9:SpecialServiceTypes><v9:HoldAtLocationDetail><v9:PhoneNumber>9052125251</v9:PhoneNumber><v9:LocationContactAndAddress><v9:Address><v9:StreetLines>HAL Address Line 1</v9:StreetLines><v9:City>St-Laurent</v9:City><v9:StateOrProvinceCode>QC</v9:StateOrProvinceCode><v9:PostalCode>H4T2A3</v9:PostalCode><v9:CountryCode>CA</v9:CountryCode></v9:Address></v9:LocationContactAndAddress></v9:HoldAtLocationDetail>";
			$sXML.="</v9:SpecialServicesRequested>";
			$sXML.="<v9:CustomsClearanceDetail>" . (@$customsaccountnumber!='' ? "<v9:DutiesPayment><v9:PaymentType>SENDER</v9:PaymentType></v9:DutiesPayment>" : '') . "<v9:CustomsValue><v9:Currency>" . $countryCurrency . "</v9:Currency><v9:Amount>XXXFEDEXGRANDTOTXXX</v9:Amount></v9:CustomsValue></v9:CustomsClearanceDetail>";
		}
		$sXML.="<v9:RateRequestTypes>ACCOUNT</v9:RateRequestTypes><v9:PackageDetail>INDIVIDUAL_PACKAGES</v9:PackageDetail>";
	}elseif($shipType==9){
		$sXML='<?xml version="1.0" encoding="utf-8" ?><q1:DCTRequest xmlns:q1="http://www.dhl.com"><GetQuote>' .
		'<Request><ServiceHeader><SiteID>' . $DHLSiteID . '</SiteID><Password>' . $DHLSitePW . '</Password></ServiceHeader></Request>' .
		'<From><CountryCode>' . $origCountryCode . '</CountryCode><Postalcode>' . $origZip . '</Postalcode></From>' .
		'<BkgDetails><PaymentCountryCode>' . $origCountryCode . '</PaymentCountryCode>' .
		'<Date>' . date('Y-m-d', time()+86400) . '</Date><ReadyTime>PT9H</ReadyTime>' .
		'<DimensionUnit>' . (($adminUnits & 12)==4 || (($adminUnits & 12)==0 && ($adminUnits & 1)==1) ? 'IN' : 'CM') . '</DimensionUnit><WeightUnit>' . (($adminUnits & 1)==1 ? 'LB' : 'KG') . '</WeightUnit><Pieces>';
	}elseif($shipType==10){ // Australia Post
		$packtogether=TRUE; $splitpackat=''; $nosplitlargepacks=TRUE; // Australia Post cannot handle more than one package
	}
	return(TRUE);
}
$packdims=array(0,0,0,0,0,0,0,0); // len : wid : hei : vol : maxlen : maxwid : maxhei : items
function zeropackdims(){
	global $packdims,$thepweight;
	for($zpd=0;$zpd<=7;$zpd++) $packdims[$zpd]=0;
	$thepweight=0;
}
function reorderpackagedimensions(){
	global $packdims;
	if($packdims[2]>$packdims[1]){ $apdtemp=$packdims[1]; $packdims[1]=$packdims[2]; $packdims[2]=$apdtemp; }
	if($packdims[1]>$packdims[0]){ $apdtemp=$packdims[0]; $packdims[0]=$packdims[1]; $packdims[1]=$apdtemp; }
	if($packdims[2]>$packdims[1]){ $apdtemp=$packdims[1]; $packdims[1]=$packdims[2]; $packdims[2]=$apdtemp; }
}
function reorderproddims(&$pdims){
	$pdims[0]=(float)$pdims[0]; $pdims[1]=(float)$pdims[1]; $pdims[2]=(float)$pdims[2];
	if($pdims[2]>$pdims[1]){ $apdtemp=$pdims[1]; $pdims[1]=$pdims[2]; $pdims[2]=$apdtemp; }
	if($pdims[1]>$pdims[0]){ $apdtemp=$pdims[0]; $pdims[0]=$pdims[1]; $pdims[1]=$apdtemp; }
	if($pdims[2]>$pdims[1]){ $apdtemp=$pdims[1]; $pdims[1]=$pdims[2]; $pdims[2]=$apdtemp; }
}
function addpackagedimensions($dimens, $apdquant){
	global $packdims,$adminUnits;
	if(($adminUnits & 12)!=0){
		$origdimens=$packdims;
		$proddims=explode('x',$dimens);
		if(@$proddims[0]!=''&&@$proddims[1]!=''&&@$proddims[2]!=''){
			if(@$GLOBALS['fitproductsinsamebox']){
				$packdims[0]=$proddims[0];
				$packdims[1]=$proddims[1];
				$packdims[2]=$proddims[2];
			}else{
				reorderproddims($proddims);
				if($proddims[0]>$packdims[4]) $packdims[4]=$proddims[0];
				if($proddims[1]>$packdims[5]) $packdims[5]=$proddims[1];
				if($proddims[2]>$packdims[6]) $packdims[6]=$proddims[2];
				$proddims[2]=$proddims[2] * $apdquant;
				$thelength=$proddims[0];
				reorderproddims($proddims);
				while($apdquant>4 && $proddims[0]>$proddims[2] * 2 && $proddims[0]>$thelength){
					$proddims[0]=$proddims[0] / 2; $proddims[2]=$proddims[2] * 2; $apdquant=$apdquant / 2;
					reorderproddims($proddims);
				}
				$thelength=$proddims[0]; $thewidth=$proddims[1]; $theheight=$proddims[2];
				$objvol=$thelength * $thewidth * $theheight;
				if($thelength>$packdims[0]) $packdims[0]=$thelength;
				if($thewidth>$packdims[1]) $packdims[1]=$thewidth;
				if($theheight>$packdims[2]) $packdims[2]=$theheight;
				if($objvol + $packdims[3]>$packdims[0] * $packdims[1] * $packdims[2]) $packdims[2]=$packdims[2] + ($origdimens[2]>0 && $origdimens[2] < $theheight ? $origdimens[2] : $theheight);
				if($objvol + $packdims[3]>$packdims[0] * $packdims[1] * $packdims[2]) $packdims[1]=$packdims[1] + ($origdimens[1]>0 && $origdimens[1] < $thewidth ? $origdimens[1] : $thewidth);
				if($objvol + $packdims[3]>$packdims[0] * $packdims[1] * $packdims[2]) $packdims[0]=$packdims[0] + ($origdimens[0]>0 && $origdimens[0] < $thelength ? $origdimens[0] : $thelength);
				$packdims[3]=$packdims[3] + $objvol;
			}
			reorderpackagedimensions();
		}
	}
	$packdims[7]+=$apdquant;
	// print "Bin is : " . $packdims[0] . ':' . $packdims[1] . ':' . $packdims[2] . '=' . ($packdims[0]*$packdims[1]*$packdims[2]) . '<br>';
}
function splitlargepacks(){
	global $packdims,$shipType,$adminUnits,$nosplitlargepacks,$thepweight,$splitpackat,$adminCanPostLogin;
	$slpweight=$thepweight;
	$slpnumpacks=1;
	if($packdims[7]<=1&&@$nosplitlargepacks==TRUE) return 1;
	if($shipType==6){
		if(($adminUnits & 12)==4){ $maxlenplusgirth=118; $maxlength=78; }else{ $maxlenplusgirth=300; $maxlength=200; }
		if(($adminUnits & 3)==1) $maxweight=66; else $maxweight=30;
		if($adminCanPostLogin!='') $nosplitlargepacks=TRUE;
	}elseif($shipType==4 || $shipType==7 || $shipType==8 || $shipType==9 || $shipType==11){
		if(($adminUnits & 12)==4){ $maxlenplusgirth=165; $maxlength=108; }else{ $maxlenplusgirth=419; $maxlength=274; }
		if(($adminUnits & 3)==1) $maxweight=150; else $maxweight=68;
	}else{ // USPS Default
		if(($adminUnits & 12)==8) $maxlenplusgirth=330; else $maxlenplusgirth=130;
		$maxlength=0;
		$maxweight=70;
	}
	if(is_numeric(@$splitpackat)&&@$splitpackat!=0) $maxweight=(float)$splitpackat;
	if(@$nosplitlargepacks!=TRUE && ($adminUnits & 12)!=0){
		if($packdims[0] + (($packdims[1] + $packdims[2]) * 2)>$maxlenplusgirth){ // Max Length + Girth
			$divisor=1;
			while(($packdims[0]/sqrt($divisor)) + ((($packdims[1]/sqrt($divisor)) + $packdims[2]) * 2)>$maxlenplusgirth)
				$divisor++;
			if($packdims[0]/sqrt($divisor)>$maxlength && $maxlength!=0 && ($packdims[0]/$divisor) + (($packdims[1] + $packdims[2]) * 2)<=$maxlenplusgirth)
				$packdims[0]=$packdims[0]/$divisor;
			else{
				$packdims[0]=$packdims[0]/sqrt($divisor);
				$packdims[1]=$packdims[1]/sqrt($divisor);
			}
			$slpnumpacks *= $divisor;
			$slpweight /= $divisor;
			reorderpackagedimensions();
		}
		if($packdims[0]>$maxlength && $maxlength!=0){
			$packdims[0]=$packdims[0] / 2;
			$slpnumpacks *= 2;
			$slpweight /= 2;
			reorderpackagedimensions();
		}
	}
	if($slpweight>$maxweight && ($packdims[7]<=$slpnumpacks || @$nosplitlargepacks!=TRUE)){
		$slpindex=2;
		while(TRUE){
			if($slpweight/$slpindex<=$maxweight){
				$packdims[0]/=$slpindex;
				$slpnumpacks*=$slpindex;
				reorderpackagedimensions();
				break;
			}
			$slpindex++;
		}
	}
	return($slpnumpacks);
}
function islastpacktogether($prodindex){
	global $itemsincart,$cartrows;
	for($tindex=$prodindex+1;$tindex<$itemsincart;$tindex++)
		if(($cartrows[$tindex]['pExemptions'] & 32)!=32) return(FALSE);
	return(TRUE);
}
function addproducttoshipping($apsrs, $prodindex){
	global $shipping,$shipType,$packtogether,$shipThisProd,$somethingToShip,$itemsincart,$intShipping,$international,$shipcountry,$fromshipselector,$packageweight,$packagefreeexemptweight;
	global $rowcounter,$origZip,$destZip,$sXML,$numshipoptions,$allzones,$numzones,$dHighWeight,$adminUnits,$shipCountryCode,$countryCode,$allfreeshipexempt;
	global $upspacktype,$splitpackat,$thePQuantity,$thepweight,$totalgoods,$shipfreegoods,$packaging,$packdims,$initialpackweight,$saturdaydelivery_,$royalmail;
	$shipThisProd=TRUE;
	$savepacktogether=FALSE;
	if($packtogether && ($apsrs['pExemptions'] & 32)==32){
		$savepacktogether=$packtogether;
		$savethepweight=$thepweight;
		$savepackageweight=$packageweight;
		$savepackdims=$packdims;
		zeropackdims();
		$packtogether=FALSE;
	}
	if(($apsrs['pExemptions'] & 4)==4){ // No Shipping on this product
		$shipThisProd=FALSE;
	}else
		addpackagedimensions(trim_($apsrs['pDims']), ($packtogether ? (int)$apsrs['cartQuantity'] : 1));
	if(($apsrs['pExemptions'] & 16)!=16) $allfreeshipexempt=FALSE;
	if($fromshipselector){
	}elseif($shipType==1){ // Flat rate shipping
		if($shipThisProd){
			// $shipping+=$apsrs['pShipping'] + $apsrs['pShipping2'] * ($apsrs['cartQuantity']-1);
			$intShipping[0][2]+=$apsrs['pShipping'] + $apsrs['pShipping2'] * ($apsrs['cartQuantity']-1);
			if(($apsrs['pExemptions'] & 16)==16) $intShipping[0][7]+=$apsrs['pShipping'] + $apsrs['pShipping2'] * ($apsrs['cartQuantity']-1);
			$somethingToShip=TRUE;
		}
	}elseif($shipType==2 || $shipType==5){ // Weight / Price based shipping
		$havematch=FALSE;
		for($index3=0; $index3 < $numshipoptions; $index3++)
			$dHighest[$index3]=0;
		if($numzones>0){
			if($shipThisProd){
				$somethingToShip=TRUE;
				if($shipType==2) $tmpweight=(float)$apsrs['pWeight']; else $tmpweight=(float)$apsrs['cartProdPrice'];
				if($packtogether){
					$thepweight+=((float)($apsrs['cartQuantity'])*$tmpweight);
					$thePQuantity=1;
				}else{
					$thepweight=$tmpweight + (@$initialpackweight!=''?$initialpackweight:0);
					$thePQuantity=(float)$apsrs['cartQuantity'];
				}
				$packageweight+=(float)($apsrs['cartQuantity'])*$tmpweight;
				if(($apsrs['pExemptions'] & 16)==16) $packagefreeexemptweight+=(float)($apsrs['cartQuantity'])*$tmpweight;
			}
			if(((!$packtogether && $shipThisProd) || ($packtogether && islastpacktogether($prodindex))) && ($thepweight>0 || $shipType==5)){ // Only calculate pack together when we have the total
				for($index2=0;$index2<$numzones;$index2++){
					if($allzones[$index2]['zcWeight']>=$thepweight){
						$havematch=TRUE;
						for($index3=0; $index3 < $numshipoptions; $index3++){
							if($allzones[$index2]['zcRatePC'.($index3==0?'':$index3+1)]!=0) // Percentage
								$intShipping[$index3][2]+=((float)$allzones[$index2]['zcRate'.($index3==0?'':$index3+1)]*$thePQuantity*$thepweight)/100.0;
							else
								$intShipping[$index3][2]+=((float)$allzones[$index2]['zcRate'.($index3==0?'':$index3+1)]*$thePQuantity);
							if((float)$allzones[$index2]['zcRate'.($index3==0?'':$index3+1)]==-99999.0) $intShipping[$index3][3]=FALSE;
							if($shipCountryCode==$countryCode && $saturdaydelivery_ && @$royalmail){
								if($index3==2 || $index3==3){
									if($index3==2) $intShipping[$index3][2]*=1.2;
									$intShipping[$index3][2]+=3;
								}else
									$intShipping[$index3][3]=FALSE;
							}
						}
						break;
					}
					$dHighWeight=$allzones[$index2]['zcWeight'];
					for($index3=0; $index3 < $numshipoptions; $index3++){
						if($allzones[$index2]['zcRatePC'.($index3==0?'':$index3+1)]!=0) // Percentage
							$dHighest[$index3]=($allzones[$index2]['zcRate'.($index3==0?'':$index3+1)]*$dHighWeight)/100.0;
						else
							$dHighest[$index3]=$allzones[$index2]['zcRate'.($index3==0?'':$index3+1)];
					}
				}
				if(! $havematch){
					for($index3=0; $index3 < $numshipoptions; $index3++){
						$intShipping[$index3][2]+=$dHighest[$index3];
						if($dHighest[$index3]==-99999.0) $intShipping[$index3][3]=FALSE;
					}
					if($allzones[0]['zcWeight']<0){
						$dHighWeight=$thepweight - $dHighWeight;
						while($dHighWeight>0){
							for($index3=0; $index3 < $numshipoptions; $index3++)
								$intShipping[$index3][2]+=((float)($allzones[0]['zcRate'.($index3==0?'':$index3+1)])*$thePQuantity);
							$dHighWeight+=$allzones[0]['zcWeight'];
						}
					}
				}
			}
		}
	}elseif($shipType==3){ // USPS Shipping
		if($packtogether){
			if($shipThisProd){
				$somethingToShip=TRUE;
				$thepweight+=((float)$apsrs['pWeight'] * (int)$apsrs['cartQuantity']);
				$packageweight+=((float)$apsrs['pWeight'] * (int)$apsrs['cartQuantity']);
				if(($apsrs['pExemptions'] & 16)==16) $packagefreeexemptweight+=((float)$apsrs['pWeight'] * (int)$apsrs['cartQuantity']);
			}
			if(islastpacktogether($prodindex) && $thepweight>0){
				$numpacks=splitlargepacks();
				if($international!='')
					$sXML.=addUSPSInternational($rowcounter,$thepweight / $numpacks,$numpacks,'Package',$shipcountry,$totalgoods-$shipfreegoods);
				else
					$sXML.=addUSPSDomestic($rowcounter,'Parcel',$origZip,$destZip,$thepweight / $numpacks,$numpacks,'REGULAR','True',$totalgoods-$shipfreegoods);
				$rowcounter++;
				zeropackdims();
			}
		}else{
			if($shipThisProd){
				$somethingToShip=TRUE;
				$thepweight=$apsrs['pWeight'] + (@$initialpackweight!=''?$initialpackweight:0);
				$packageweight+=$thepweight;
				if(($apsrs['pExemptions'] & 16)==16) $packagefreeexemptweight+=$thepweight;
				$numpacks=splitlargepacks();
				if($international!='')
					$sXML.=addUSPSInternational($rowcounter,$thepweight / $numpacks,$apsrs['cartQuantity']*$numpacks,'Package',$shipcountry,$apsrs['cartProdPrice']);
				else
					$sXML.=addUSPSDomestic($rowcounter,'Parcel',$origZip,$destZip,$thepweight / $numpacks,$apsrs['cartQuantity']*$numpacks,'REGULAR','True',$apsrs['cartProdPrice']);
				$rowcounter++;
				zeropackdims();
			}
		}
	}elseif($shipType==4 || $shipType>=6){ // UPS Shipping OR Canada Post OR FedEx OR DHL
		if($shipType==4 || $shipType==11){
			$packaging='02';
			if(@$packaging!=''){
				if($packaging=='envelope') $packaging='01';
				if($packaging=='pak') $packaging='04';
				if($packaging=='box') $packaging='21';
				if($packaging=='tube') $packaging='03';
				if($packaging=='10kgbox') $packaging='25';
				if($packaging=='25kgbox') $packaging='24';
			}elseif(@$upspacktype!='')
				$packaging=$upspacktype;
		}
		if($packtogether){
			if($shipThisProd){
				$somethingToShip=TRUE;
				$thepweight+=((float)$apsrs['pWeight'] * (int)$apsrs['cartQuantity']);
				$packageweight+=((float)$apsrs['pWeight'] * (int)$apsrs['cartQuantity']);
				if(($apsrs['pExemptions'] & 16)==16) $packagefreeexemptweight+=((float)$apsrs['pWeight'] * (int)$apsrs['cartQuantity']);
			}
			if(islastpacktogether($prodindex) && $thepweight>0){
				$numpacks=splitlargepacks();
				for($index3=0;$index3 < $numpacks; $index3++)
					if($shipType==4 || $shipType==11)
						$sXML.=addUPSInternational($thepweight / $numpacks,$adminUnits,$packaging,$shipCountryCode,$totalgoods-$shipfreegoods,$packdims);
					elseif($shipType==6)
						$sXML.=addCanadaPostPackage($thepweight / $numpacks,$adminUnits,$packaging,$shipCountryCode,$totalgoods-$shipfreegoods,$packdims);
					elseif($shipType==9)
						$sXML.=addDHLPackage($thepweight / $numpacks,$adminUnits,$packaging,$shipCountryCode,$totalgoods-$shipfreegoods,$packdims);
					elseif($shipType==7||$shipType==8)
						$sXML.=addFedexPackage($thepweight / $numpacks,$totalgoods-$shipfreegoods,$packdims);
				if($shipType!=10) zeropackdims();
			}
		}else{
			if($shipThisProd){
				$somethingToShip=TRUE;
				$thepweight=$apsrs['pWeight'] + (@$initialpackweight!=''?$initialpackweight:0);
				$packageweight+=$thepweight;
				if(($apsrs['pExemptions'] & 16)==16) $packagefreeexemptweight+=$thepweight;
				$numpacks=splitlargepacks();
				for($index2=0;$index2 < (int)$apsrs['cartQuantity']; $index2++)
					for($index3=0;$index3 < $numpacks; $index3++)
						if($shipType==4 || $shipType==11)
							$sXML.=addUPSInternational($thepweight / $numpacks,$adminUnits,$packaging,$shipCountryCode,$apsrs['cartProdPrice'],$packdims);
						elseif($shipType==6)
							$sXML.=addCanadaPostPackage($thepweight / $numpacks,$adminUnits,$packaging,$shipCountryCode,$apsrs['cartProdPrice'],$packdims);
						elseif($shipType==9)
							$sXML.=addDHLPackage($thepweight / $numpacks,$adminUnits,$packaging,$shipCountryCode,$apsrs['cartProdPrice'],$packdims);
						elseif($shipType==7||$shipType==8)
							$sXML.=addFedexPackage($thepweight / $numpacks,$apsrs['cartProdPrice'],$packdims);
				zeropackdims();
			}
		}
	}
	if($savepacktogether && ($apsrs['pExemptions'] & 32)==32){
		$thepweight=$savethepweight;
		//$packageweight=$savepackageweight;
		$packtogether=$savepacktogether;
		$packdims=$savepackdims;
	}
}
function calculateshipping(){
	global $shipType,$freeshipmethodexists,$multipleoptions,$somethingToShip,$willpickuptext,$willpickupcost,$numshipoptions,$upsUser,$upsPw,$shipCountryCode,$destZip,$totalgoods,$thesessionid,$handling,$willpickup_,$DHLAccountNo,$origCountryCode,$countryCurrency,$smartPostHub,$commercialloc_;
	global $shipping,$shipMethod,$success,$errormsg,$sXML,$intShipping,$international,$iTotItems,$uspsmethods,$numuspsmeths,$shipstate,$maxshipoptions,$saturdaydelivery_,$saturdaypickup,$upsnegdrates,$fromshipselector,$packageweight,$packagefreeexemptweight,$shipCountryID,$ordCity;
	if($fromshipselector){
	}elseif($shipType==1){
		$freeshipmethodexists=TRUE;
	}elseif($shipType==3 && $somethingToShip){
		if(!$GLOBALS['uspsuseoauth'])
			$sXML.='</' . $international . 'Rate' . ($international=='' ? 'V4' : 'V2') . 'Request>';
		$success=USPSCalculate($sXML,$international,$errormsg,$intShipping);
		if(substr($errormsg, 0, 30)=='Warning - Bound Printed Matter') $success=TRUE;
		if($success){
			$maxsopt=0;
			for($indexmso=0; $indexmso<$maxshipoptions; $indexmso++){
				$shipRow=$intShipping[$indexmso];
				if($iTotItems==$shipRow[3]){
					$intShipping[$indexmso][3]=TRUE;
					$maxsopt=$indexmso;
					for($index2=0;$index2<$numuspsmeths;$index2++){
						if(str_replace('-',' ',strtolower($shipRow[5]))==str_replace('-',' ',strtolower($uspsmethods[$index2]['uspsMethod']))){
							$intShipping[$indexmso][4]=$uspsmethods[$index2]['uspsFSA'];
						}
					}
				}else
					$intShipping[$indexmso][3]=FALSE;
			}
			for($ssaindex2=0; $ssaindex2<=$maxsopt-1; $ssaindex2++){
				if($intShipping[$ssaindex2][3]==TRUE){
					$csmatch=$intShipping[$ssaindex2][0];
					for($ssaindex=$ssaindex2+1; $ssaindex<=$maxsopt; $ssaindex++){
						if($csmatch==$intShipping[$ssaindex][0]&&!$intShipping[$ssaindex][4]) $intShipping[$ssaindex][3]=FALSE;
					}
				}
			}
		}
	}elseif(($shipType==4 || $shipType==11) && $somethingToShip){
		if(trim($upsUser)!='' && trim($upsPw)!=''){
			if(strlen($GLOBALS['upsUser'])>40||strlen($GLOBALS['upsPw'])>40){
				$serviceoptions=',"ShipmentServiceOptions":{' . trim(($saturdaydelivery_ ? '"SaturdayDeliveryIndicator":"Y",' : '') . (@$saturdaypickup ? '"SaturdayPickupIndicator":"Y",' : ''),',') . '}';
				$serviceoptions.=(@$upsnegdrates?',"ShipmentRatingOptions":{"NegotiatedRatesIndicator":"Y"}':'');
				$sXML.=']' . $serviceoptions . '}}}';
			}else{
				$sXML.='<ShipmentServiceOptions>' . ($saturdaydelivery_ ? '<SaturdayDelivery/>' : '') . (@$saturdaypickup==TRUE ? '<SaturdayPickup/>' : '') . '</ShipmentServiceOptions>' . (@$upsnegdrates==TRUE?'<RateInformation><NegotiatedRatesIndicator /></RateInformation>':'') . '</Shipment></RatingServiceSelectionRequest>';
			}
			$success=UPSCalculate($sXML,$international,$errormsg,$intShipping);
		}else{
			$success=FALSE;
			$errormsg='You must register with UPS by logging on to your online admin section and clicking the &quot;Register with UPS&quot; link before you can use the UPS OnLine&reg; Shipping Rates and Services Selection';
		}
	}elseif($shipType==6 && $somethingToShip){
		if(getpost('shipping')==''){
			$sXML.='</mailing-scenario></rate:get-rates-request></soapenv:Body></soapenv:Envelope>';
			$success=CanadaPostCalculate($sXML,$international,$errormsg,$intShipping);
		}
	}elseif(($shipType==7 || $shipType==8) && $somethingToShip){
		$sXML=str_replace('XXXFEDEXGRANDTOTXXX',$totalgoods,$sXML);
		$sXML.='</v9:RequestedShipment></v9:RateRequest></soapenv:Body></soapenv:Envelope>';
		if($shipType==8 && $smartPostHub==''){ $success=FALSE; $errormsg='SmartPost Hub ID not set'; }else $success=fedexcalculate($sXML,$international,$errormsg,$intShipping);
	}elseif($shipType==9 && $somethingToShip){
		if($shipCountryCode=='IE' && $ordCity=='') $ordCity='Dublin';
		$sXML.='</Pieces><PaymentAccountNumber>' . $DHLAccountNo . '</PaymentAccountNumber><IsDutiable>' . ($origCountryCode==$shipCountryCode || (iseuropean($origCountryCode) && iseuropean($shipCountryCode)) ? 'N' : 'Y') . '</IsDutiable>' .
			'<NetworkTypeCode>AL</NetworkTypeCode>' .
		($commercialloc_?'':'<QtdShp><QtdShpExChrg><SpecialServiceType>TK</SpecialServiceType></QtdShpExChrg></QtdShp>') .
		'</BkgDetails><To><CountryCode>' . $shipCountryCode . '</CountryCode><Postalcode>' . strtoupper($destZip) . '</Postalcode>' . (zipisoptional($shipCountryID)||$shipCountryID==65?'<City>'.$ordCity.'</City>':'') . '</To>' .
			'<Dutiable><DeclaredCurrency>' . $countryCurrency . '</DeclaredCurrency><DeclaredValue>' . $totalgoods . '</DeclaredValue></Dutiable></GetQuote></q1:DCTRequest>';
		$success=dhlcalculate($sXML,$international,$errormsg,$intShipping);
	}elseif($shipType==10 && $somethingToShip)
		$success=auspostcalculate($packageweight,$international,$errormsg,$intShipping);
	if($success && getpost('shipping')=='' && $somethingToShip && ! $fromshipselector && $shipType>=1){
		$totShipOptions=0;
		$multipleoptions=TRUE;
		$packagefreeshipweight=0;
		for($index2=0;$index2<$GLOBALS['itemsincart'];$index2++){
			if(@$GLOBALS['cartrows'][$index2]['shipFree']==1 && (@$GLOBALS['cartrows'][$index2]['pExemptions'] & 4)!=4 && (@$GLOBALS['cartrows'][$index2]['pExemptions'] & 16)!=16){
				$packagefreeshipweight+=($shipType==5?$GLOBALS['cartrows'][$index2]['cartProdPrice']:$GLOBALS['cartrows'][$index2]['pWeight'])*$GLOBALS['cartrows'][$index2]['cartQuantity'];
			}
		}
		for($indexmso=0; $indexmso<$maxshipoptions; $indexmso++){
			if($intShipping[$indexmso][3]==TRUE){
				$totShipOptions++;
				if($intShipping[$indexmso][4]){
					$freeshipmethodexists=TRUE;
					if($packageweight>0 && $packagefreeshipweight>0){
						//$intShipping[$indexmso][2]*=(($packageweight-$packagefreeshipweight)/$packageweight);
						$intShipping[$indexmso][2]=round($intShipping[$indexmso][2],2);
					}
				}
			}
			if($shipType>=2 && $packageweight>0){
				$intShipping[$indexmso][7]=round($intShipping[$indexmso][2]*(1-($packagefreeshipweight/$packageweight)),2);
			}
		}
		if($totShipOptions==0 && ! $willpickup_){
			$multipleoptions=FALSE;
			$success=FALSE;
			$errormsg=$GLOBALS['adminAltRates']==2?$GLOBALS['xxPlShOp']:$GLOBALS['xxNoMeth'];
		}
		if($willpickup_) $multipleoptions=TRUE;
	}
	return($success);
}
function saveshippingoptions(){
	global $shipType,$intShipping,$orderid,$maxshipoptions;
	$maxindex=0;
	if($shipType>=1 && is_numeric($orderid)){
		$sSQL="SELECT MAX(soIndex) AS maxindex FROM shipoptions WHERE soOrderID='" . escape_string($orderid) . "'";
		$result=ect_query($sSQL) or ect_error();
		$rs=ect_fetch_assoc($result);
		if(! is_null($rs['maxindex'])) $maxindex=$rs['maxindex']+1;
		ect_free_result($result);
		for($indexmso=0; $indexmso<$maxshipoptions; $indexmso++){
			if($intShipping[$indexmso][3]==TRUE){
				$sSQL='INSERT INTO shipoptions (soOrderID,soIndex,soMethodName,soCost,soFreeShipExempt,soFreeShip,soShipType,soDeliveryTime,soDateAdded) VALUES (' .
					$orderid . ',' . $maxindex . ",'" . escape_string($intShipping[$indexmso][0]) . "'," . $intShipping[$indexmso][2] . ',' . $intShipping[$indexmso][7] . ',' .
					$intShipping[$indexmso][4] . ',' . $shipType . ",'" . escape_string($intShipping[$indexmso][1]) . "','" . date('Y-m-d', time()) . "')";
				ect_query($sSQL) or ect_error();
				$maxindex++;
			}
		}
	}
}
$numshiprate=0; $numshiprateingroup=0;
function writeshippingoption($soindex,$shipcost,$freeshipexempt,$freeship,$shipmethod,$isselected,$wsodelivery){
	global $numshiprate,$numshiprateingroup,$shippingoptionsasradios,$orighandling,$taxHandling,$orighandlingpercent,$stateTaxRate,$countryTaxRate,$freeshippingapplied,$totalgoods,$totaldiscounts,$freeshippingincludeshandling,$handlingeligableitem,$handlingeligablegoods,$shipType,$mobilebrowser;
	if($freeshippingapplied && $freeship==1) $wsofreeshipamnt=($shipcost-($freeshipexempt + getfreeshipinsurance($soindex))); else $wsofreeshipamnt=0;
	$wsohandling=round($orighandling, 2);
	if($handlingeligableitem==FALSE)
		$wsohandling=0;
	elseif(@$orighandlingpercent!=0){
		$temphandling=((($totalgoods + $shipcost + $wsohandling) - ($totaldiscounts + $wsofreeshipamnt)) * $orighandlingpercent / 100.0);
		if($handlingeligablegoods < $totalgoods && $totalgoods>0) $temphandling=$temphandling * ($handlingeligablegoods / $totalgoods);
		$wsohandling+=$temphandling;
	}
	if($taxHandling==1) $wsohandling+=((float)$wsohandling*((float)$stateTaxRate+(float)$countryTaxRate))/100.0;
	if($freeship==1 && @$freeshippingincludeshandling) $wsohandling=0;
	if(@$shippingoptionsasradios==TRUE)
		print '<div class="shiprateline"><label class="ectlabel shipradio"><input type="radio" class="ectradio shipradio" value="RATE"'.($isselected?' checked="checked"':'').' onclick="updateshiprate(this,'.$numshiprate.')" /><span class="shipratemethod'.($numshiprateingroup==0?' shipratemethodselected':'').'">'.$shipmethod.' '.(@$GLOBALS['combineshippinghandling']?FormatEuroCurrency(($shipcost+$wsohandling)-$wsofreeshipamnt):FormatEuroCurrency($shipcost-$wsofreeshipamnt)).'</span></label>'.($wsodelivery!=''?'<div class="cart3servicecommitment">(' . $wsodelivery . ')</div>':'') . '</div>';
	else
		print '<option value="RATE"'.($isselected?' selected="selected"':'').'>'.$shipmethod.' '.($wsodelivery!=''?'(' . $wsodelivery . ') ':'').(@$GLOBALS['combineshippinghandling']?FormatEuroCurrency(($shipcost+$wsohandling)-$wsofreeshipamnt):FormatEuroCurrency($shipcost-$wsofreeshipamnt)).'</option>';
	$numshiprate++;
	$numshiprateingroup++;
}
$currShipType='';
function showshippingselect(){
	global $fromshipselector,$shipType,$shippingoptionsasradios,$numshiprate,$currShipType,$selectedshiptype,$maxshipoptions,$intShipping,$numshiprateingroup,$saturdaydelivery_,$royalmail,$ordComLoc,$adminAltRates;
	if(! $fromshipselector) calculateshippingdiscounts(FALSE);
	if($shipType>=1){
		if(@$shippingoptionsasradios!=TRUE){
			print '<select class="ectselectinput nofixw" size="1" onchange="updateshiprate(this,(this.selectedIndex'.($fromshipselector?'-1':'').')+'.$numshiprate.')">';
			if($fromshipselector) print '<option value="">'.$GLOBALS['xxPlsSel'].'</option>';
		}
		for($indexmso=0; $indexmso<$maxshipoptions; $indexmso++){
			if($intShipping[$indexmso][3]){
				if($currShipType=='') $currShipType=$intShipping[$indexmso][6];
				if($currShipType!=$intShipping[$indexmso][6]){
					$currShipType=$intShipping[$indexmso][6];
					$numshiprateingroup=0;
					if(@$shippingoptionsasradios!=TRUE) print '</select>';
					print '</div></div><div class="shiptableline' . ($adminAltRates==2?2:'') . '"><div class="shiplogo' . ($adminAltRates==2?2:'') . '">' . getshiplogo($currShipType) . '</div><div class="shiptablerates' . ($adminAltRates==2?2:'') . '">';
					if(@$shippingoptionsasradios!=TRUE) print '<select class="ectselectinput nofixw" size="1" onchange="updateshiprate(this,(this.selectedIndex-1)+'.$numshiprate.')"><option value="">'.$GLOBALS['xxPlsSel'].'</option>';
				}
				writeshippingoption($indexmso,round($intShipping[$indexmso][2], 2), round($intShipping[$indexmso][7], 2), $intShipping[$indexmso][4], $intShipping[$indexmso][0], $indexmso==$selectedshiptype, $intShipping[$indexmso][1]);
			}
		}
		if(@$shippingoptionsasradios!=TRUE) print '</select>';
		if(@$royalmail && $shipType==2 && $saturdaydelivery_)
			print '<div class="nosaturdaydelivery">First and Second Class post are not available with Saturday Delivery.</div>';
	}
}
function getuspsinsurancerate($theamount){
	if($theamount<=0)
		return(0);
	elseif($theamount<=50)
		return(1.75);
	elseif($theamount<=100)
		return(2.25);
	elseif($theamount<=200)
		return(2.75);
	else
		return(4.70 + (1.0 * floor(($theamount-200.01) / 100.0)));
}
function getfreeshipinsurance($soindex){
	global $somethingToShip,$wantinsurance_,$addshippinginsurance,$totalgoods,$shipType,$shipinsurancepercent,$shipinsurancemin,$shipping,$intShipping,$freeshippingincludesservices,$nocarrierinsurancerates;
	$shipinsurancetotal=0;
	if(($wantinsurance_ && @$addshippinginsurance==2) || @$addshippinginsurance==1){
		if($shipping>0 && !$freeshippingincludesservices){
			if(($shipType==3||$shipType==4||$shipType==6||$shipType==7||$shipType==8||$shipType==11)&&!$nocarrierinsurancerates){
				$shipinsurancetotal=$intShipping[$soindex][8];
			}else{
				$shipinsurancetotal=round(($totalgoods*$shipinsurancepercent)/100.0,2);
				if($shipinsurancetotal<$shipinsurancemin) $shipinsurancetotal=$shipinsurancemin;
			}
		}
	}
	return $shipinsurancetotal;
}
function insuranceandtaxaddedtoshipping(){
	global $shipinsuranceamt,$somethingToShip,$wantinsurance_,$addshippinginsurance,$maxshipoptions,$selectedshiptype,$nocarrierinsurancerates;
	global $totalgoods,$shipping,$taxShipping,$stateTaxRate,$countryTaxRate,$intShipping,$shipType,$shipinsurancepercent,$shipinsurancemin;
	if(($wantinsurance_ && @$addshippinginsurance==2) || @$addshippinginsurance==1){
		if($shipType==3&&!$nocarrierinsurancerates){
			for($index3=0; $index3 < $maxshipoptions; $index3++)
				$intShipping[$index3][2]+=$intShipping[$index3][8];
			$shipping+=$intShipping[$selectedshiptype][8];
		}elseif($shipType==2 || $shipType==5 || $nocarrierinsurancerates){
			$shipinsurancetotal=round(($totalgoods*$shipinsurancepercent)/100.0,2);
			if($shipinsurancetotal<$shipinsurancemin) $shipinsurancetotal=$shipinsurancemin;
			for($index3=0; $index3 < $maxshipoptions; $index3++){
				$intShipping[$index3][2]+=$shipinsurancetotal;
			}
			$shipping+=$shipinsurancetotal;
		}
	}
	if(@$taxShipping==1){
		for($index3=0; $index3 < $maxshipoptions; $index3++)
			$intShipping[$index3][2]+=((float)$intShipping[$index3][2]*((float)$stateTaxRate+(float)$countryTaxRate))/100.0;
		$shipping+=((float)$shipping*((float)$stateTaxRate+(float)$countryTaxRate))/100.0;
	}
}
function calculatetaxandhandling(){
	global $handlingchargepercent,$handling,$orighandling,$totalgoods,$shipping,$totaldiscounts,$freeshipamnt,$taxHandling,$stateTaxRate,$countryTaxRate,$taxShipping,$homeCountryTaxRate,$freeshippingapplied,$freeshippingincludeshandling;
	global $stateTax,$countryTax,$origCountryID,$shipCountryID,$shipStateAbbrev,$usehst,$statetaxfree,$countrytaxfree,$proratashippingtax,$handlingeligablegoods,$handlingeligableitem,$shiphomecountry,$shippingtax,$success,$giftcertificateid,$donationid;
	$handling=$orighandling;
	if($GLOBALS['countrytaxthreshold']!=0){
		if(($totalgoods-$totaldiscounts)>$GLOBALS['countrytaxthreshold']){
			$countryTaxRate=0;
			$taxShipping=0;
		}
	}
	if($handlingeligableitem==FALSE||($freeshippingapplied&&$freeshippingincludeshandling&&$freeshipamnt>0))
		$handling=0;
	else{
		if($handlingchargepercent!=0){
			$temphandling=((($totalgoods + $shipping + $handling) - ($totaldiscounts + $freeshipamnt)) * $handlingchargepercent / 100.0);
			if($handlingeligablegoods < $totalgoods && $totalgoods>0) $temphandling=$temphandling * ($handlingeligablegoods / $totalgoods);
			$handling+=$temphandling;
		}
		if(@$taxHandling==1) $handling+=((float)$handling*((float)$stateTaxRate+(float)$countryTaxRate))/100.0;
	}
	if($origCountryID==2 && $shipCountryID==2 && ($shipStateAbbrev=='NB' || $shipStateAbbrev=='NF' || $shipStateAbbrev=='NS' || $shipStateAbbrev=='ON' || $shipStateAbbrev=='PE')) $usehst=TRUE; else $usehst=FALSE;
	if($totalgoods>0){
		$stateTax=((float)$totalgoods-((float)$totaldiscounts+(float)$statetaxfree))*(float)$stateTaxRate/100.0;
		if(!@$GLOBALS['perproducttaxrate']) $countryTax=((float)$totalgoods-((float)$totaldiscounts+(float)$countrytaxfree))*(float)$countryTaxRate/100.0;
		if(@$GLOBALS['showtaxinclusive']===3 && $homeCountryTaxRate>0){
			$countryTax=round(($totalgoods-($totaldiscounts+$countrytaxfree)) / ((100+$homeCountryTaxRate)/$homeCountryTaxRate),2);
			$totalgoods-=$countryTax;
			if($countryTaxRate!=$homeCountryTaxRate){
				if($countryTaxRate!=0) $countryTax*=($countryTaxRate/$homeCountryTaxRate); else $countryTax=0;
			}
		}
	}
	if(@$taxShipping==2 && ($shipping - $freeshipamnt>0)){
		if(! ($origCountryID==2 && $shipCountryID==2 && ! $usehst)){
			if(@$proratashippingtax==TRUE){
				if($totalgoods>0) $stateTax+=(((float)$totalgoods-((float)$totaldiscounts+(float)$statetaxfree)) / $totalgoods) * (((float)$shipping-(float)$freeshipamnt)*(float)$stateTaxRate/100.0);
			}else
				$stateTax+=(((float)$shipping-(float)$freeshipamnt)*(float)$stateTaxRate/100.0);
		}
		$shippingtax=(((float)$shipping-(float)$freeshipamnt)*(float)$countryTaxRate/100.0);
		$countryTax+=$shippingtax;
	}
	if(@$taxHandling==2){
		$stateTax+=((float)$handling*(float)$stateTaxRate/100.0);
		$countryTax+=((float)$handling*(float)$countryTaxRate/100.0);
	}
	if($stateTax < 0) $stateTax=0;
	if($countryTax < 0) $countryTax=0;
	if($usehst){
		$countryTax=round($stateTax+$countryTax,$GLOBALS['currDecimals']);
		$stateTax=0;
	}else{
		$stateTax=round($stateTax,$GLOBALS['currDecimals']);
		$countryTax=round($countryTax,$GLOBALS['currDecimals']);
	}
	if($success&&@$GLOBALS['avalarastate']!=0&&@$GLOBALS['destZip']!=''&&((int)@$_SESSION["clientActions"] & 1)!=1){
		$numtaxableitems=0;
		$avalarajson='{"lines": [';
		$sSQL='SELECT cartID,cartQuantity,cartProdPrice,cartProdID,cartProdName,pTaxCode,pExemptions FROM cart LEFT JOIN products ON cart.cartProdID=products.pID WHERE cartCompleted=0 AND ' . getsessionsql() . ' ORDER BY cartDateAdded';
		$result3=ect_query($sSQL) or ect_error();
		$addcomma='';
		while($rs3=ect_fetch_assoc($result3)){
			if(($rs3['cartProdID']==$giftcertificateid || $rs3['cartProdID']==$donationid) && is_null($rs3['pExemptions'])) $rs3['pExemptions']=15;
			$optPriceDiff=0;
			if(($rs3['pExemptions']&1)!=1){
				$sSQL='SELECT SUM(coPriceDiff) AS sumDiff FROM cartoptions WHERE coCartID='.$rs3['cartID'];
				$result4=ect_query($sSQL) or ect_error();
				$rs4=ect_fetch_assoc($result4);
				if(! is_null($rs4['sumDiff'])) $optPriceDiff=$rs4['sumDiff'];
				ect_free_result($result4);
				$avalarajson.=$addcomma.'{"quantity":'.$rs3['cartQuantity'].',"amount":'.(($rs3['cartProdPrice']+$optPriceDiff)*$rs3['cartQuantity']).',
					  ' . (trim_($rs3['pTaxCode'])!=''?'"taxCode":"' . $rs3['pTaxCode'] . '",':'') . ($totaldiscounts>0?'"discounted":"true",':'') . '"itemCode":"'.$rs3['cartProdID'].'","description":'.json_encode($rs3['cartProdName']).'}';
				$addcomma=',';
				$numtaxableitems++;
			}
		}
		if($GLOBALS['ordShipAddress']!=''){
			$destaddress=@$GLOBALS['ordShipAddress'];
			$destcity=@$GLOBALS['ordShipCity'];
		}else{
			$destaddress=@$GLOBALS['ordAddress'];
			$destcity=@$GLOBALS['ordCity'];
		}
		if($numtaxableitems>0){
			if(@$taxShipping>0 && ($shipping - $freeshipamnt>0)){
				$avalarajson.=',{"quantity":1,"amount":'.($shipping - $freeshipamnt).',"taxCode":' . json_encode(@$GLOBALS['avalarafreightcode']!=''?$GLOBALS['avalarafreightcode']:'FR020100') . ',"itemCode":"freight","description":'.json_encode('Shipping').'}';
			}
			if(@$taxHandling>0 && $handling>0){
				$avalarajson.=',{"quantity":1,"amount":'.($handling).',"taxCode":' . json_encode(@$GLOBALS['avalarahandlingcode']!=''?$GLOBALS['avalarahandlingcode']:'OH010000') . ',"itemCode":"handling","description":'.json_encode('Handling').'}';
			}
			$avalarajson.='],
				  "addresses":{
					"shipFrom":{
						' . (@$GLOBALS['origaddress']!="" ? '"line1":' . json_encode($GLOBALS['origaddress']) . "," : '') . '
						' . (@$GLOBALS['origcity']!="" ? '"city":' . json_encode($GLOBALS['origcity']) . "," : '') . '
						' . (@$GLOBALS['origstate']!="" ? '"region":' . json_encode($GLOBALS['origstate']) . "," : '') . '
						"country":' . json_encode($GLOBALS['origCountryCode']) . ',
						"postalCode":' . json_encode($GLOBALS['origZip']) . '
					},
					"shipTo":{
						' . ($destaddress!=''&&$destcity!='' ? '"line1":' . json_encode($destaddress) . ',"city":' . json_encode($destcity) . ',' : '') . '
						"region":' . json_encode($GLOBALS['shipStateAbbrev']) . ',
						"country":' . json_encode($GLOBALS['shipCountryCode']) . ',
						"postalCode":' . json_encode($GLOBALS['destZip']) . '
					}
				  },' . ($totaldiscounts>0 ? '"discount":' . $totaldiscounts . ',' : '') . '
				  "type":"SalesOrder","date":"' . date("Y-m-d\TH:i:s+00:00",time()+($GLOBALS['dateadjust']*60*60)) . '","customerCode":"NONE",
				  ' . (trim_(@$_SESSION['avalaraentityuse'])!=''?'"entityUseCode":' . json_encode($_SESSION['avalaraentityuse']) . ',':'') . '
				  "currencyCode":"' . $GLOBALS['countryCurrency'] . '"}';
			avalaraheaders();
			if(callcurlfunction('https://' . (abs(@$GLOBALS['avalarastate'])!=2?'sandbox-':'') . 'rest.avatax.com/api/v2/transactions/create',$avalarajson,$jres,'',$errormsg,FALSE)){
				if($GLOBALS['http_status']!=201){
					$stateTax=$countryTax=0;
					$errormsg=@$jsarray->{'error'}->{'message'};
					if($errormsg=='')$errormsg='Invalid Avalara Login Credentials';
					$success=FALSE;
				}else{
					$jsarray=json_decode($jres);
					$stateTax=@$jsarray->{'totalTax'};
					$countryTax=0;
				}
			}else
				$success=FALSE;
			//print $avalarajson . "<hr>" . $jres . "<br>";
		}
	}
	$handling=round($handling,$GLOBALS['currDecimals']);
	if(@$GLOBALS['showtaxinclusive']!=0){ $_SESSION['xscountrytax']=$countryTax; $_SESSION['xsstatetax']=$stateTax; }
	if(@$GLOBALS['showtaxinclusive']==3){ $_SESSION['xscountrytax']=$shippingtax; $_SESSION['xsstatetax']=0; }
}
function do_stock_check($sublevels,&$hasbackorder,&$hasstockwarning){
	global $quantity,$cartID,$outofstockarr,$WSP,$addedprods,$numaddedprods;
	$sameitemstock=array();
	$gotstock=TRUE;
	$hasbackorder=FALSE;
	$sSQL='SELECT cartID,cartQuantity,pInStock,pID,pStockByOpts,'.$WSP.'pPrice,pBackOrder,pSell FROM cart INNER JOIN products ON cart.cartProdId=products.pID WHERE cartCompleted=0 AND ' . getsessionsql() . ' ORDER BY cartDateAdded';
	$result3=ect_query($sSQL) or ect_error();
	while($rs3=ect_fetch_assoc($result3)){
		$cartID=$rs3['cartID'];
		$thequant=$rs3['cartQuantity'];
		$pID=trim($rs3['pID']);
		$pInStock=(int)$rs3['pInStock'];
		$pStockByOpts=(int)$rs3['pStockByOpts'];
		$pPrice=$rs3['pPrice'];
		$pBackOrder=($rs3['pBackOrder']!=0);
		$pSell=$rs3['pSell'];
		if($pID!=''){
			if($GLOBALS['useStockManagement']){
				$thisiteminstock=TRUE;
				if(($quantity=$thequant)==0){
					if($GLOBALS['checkoutmode']=='acceptstock') ect_query('DELETE FROM cart WHERE cartID='.$cartID) or ect_error();
					$gotstock=FALSE;
				}elseif((int)$pStockByOpts!=0){
					$sSQL="SELECT coID,optStock,coOptID FROM cart INNER JOIN cartoptions ON cart.cartID=cartoptions.coCartID 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 cartID='" . $cartID . "'";
					$result=ect_query($sSQL) or ect_error();
					while($rs=ect_fetch_assoc($result)){
						$sameitems=0;
						foreach($sameitemstock as $samestockitem){
							if($samestockitem[0]==$rs['coOptID'] && $samestockitem[2]==TRUE) $sameitems+=$samestockitem[1];
						}
						$pInStock=(int)$rs['optStock'];
						if(($pInStock-$sameitems) < $quantity){
							$thisiteminstock=FALSE;
							$quantity=($pInStock-$sameitems);
							if($quantity < 0) $quantity=0;
							if($sublevels && ! $pBackOrder) ect_query('UPDATE cart SET cartQuantity='.$quantity.' WHERE (cartCompleted=0 OR cartCompleted=3) AND cartID='.$cartID) or ect_error();
							if($pBackOrder) $hasbackorder=TRUE; else $gotstock=FALSE;
							array_push($outofstockarr, array($rs['coID'], TRUE, $pID, $pPrice, $pBackOrder));
						}
						array_push($sameitemstock, array($rs['coOptID'], $thequant, TRUE));
					}
					ect_free_result($result);
				}else{
					$sameitems=0;
					foreach($sameitemstock as $samestockitem){
						if($samestockitem[0]==$pID && $samestockitem[2]==FALSE) $sameitems+=$samestockitem[1];
					}
					if($pInStock < ($thequant+$sameitems)){
						$thisiteminstock=FALSE;
						$quantity=($pInStock-$sameitems);
						if($quantity < 0) $quantity=0;
						if($sublevels && ! $pBackOrder) ect_query('UPDATE cart SET cartQuantity='.$quantity.' WHERE (cartCompleted=0 OR cartCompleted=3) AND cartID='.$cartID) or ect_error();
						if($pBackOrder) $hasbackorder=TRUE; else $gotstock=FALSE;
						array_push($outofstockarr, array($cartID, FALSE, $pID, $pPrice, $pBackOrder));
					}
					array_push($sameitemstock, array($pID, $thequant, FALSE));
				}
				for($index2=0; $index2<$numaddedprods; $index2++){
					if($addedprods[$index2][5]==$cartID){
						if(! $thisiteminstock) $addedprods[$index2][4]=($pBackOrder?3:2);
						if(! $pBackOrder) $addedprods[$index2][2]=$quantity;
					}
				}
			}elseif($pSell==0 && $pBackOrder!=0){
				$hasbackorder=TRUE;
				for($index2=0; $index2<$numaddedprods; $index2++){
					if($addedprods[$index2][5]==$cartID) $addedprods[$index2][4]=3;
				}
			}
		}
	}
	$hasstockwarning=! $gotstock;
	if($sublevels){
		foreach($outofstockarr as $outofstockitem)
			checkpricebreaks($outofstockitem[2], $outofstockitem[3]);
	}
}
function vrhmac2($key, $text){
	$idatastr='                                                                ';
	$odatastr='                                                                ';
	$hkey=(string)substr($key,0,64);
	$idatastr.=$text;
	for($i=0; $i<64; $i++){
		$idata[$i]=$ipad[$i]=0x36;
		$odata[$i]=$opad[$i]=0x5C;
	}
	for($i=0; $i< strlen($hkey); $i++){
		$ipad[$i] ^= ord($hkey[$i]);
		$opad[$i] ^= ord($hkey[$i]);
		$idata[$i]=($ipad[$i] & 0xFF);
		$odata[$i]=($opad[$i] & 0xFF);
	}
	for($i=0; $i< strlen($text); $i++)
		$idata[64+$i]=ord($text[$i]) & 0xFF;
	for($i=0; $i< strlen($idatastr); $i++)
		$idatastr[$i]=chr($idata[$i] & 0xFF);
	for($i=0; $i< strlen($odatastr); $i++)
		$odatastr[$i]=chr($odata[$i] & 0xFF);
	$innerhashout=md5($idatastr);
	for($i=0; $i<16; $i++)
		$odatastr.=chr(hexdec(substr($innerhashout,$i*2,2)));
	return md5($odatastr);
}
function checkdeletecart($thecartid){
	global $giftwrappingid;
	$sSQL="SELECT cartID,cartListID,cartClientID,listOwner,cartProdID,cartProdPrice FROM cart LEFT JOIN customerlists ON cart.cartListID=customerlists.listID WHERE (cartCompleted=0 OR cartCompleted=3) AND cartID='".escape_string($thecartid)."' AND " . getsessionsql();
	$result=ect_query($sSQL) or ect_error();
	if($rs2=ect_fetch_assoc($result)){
		if(! is_null($rs2['listOwner'])) $listowner=(int)$rs2['listOwner']; else $listowner=0;
		if($rs2['cartListID']>0 && $listowner!=@$_SESSION['clientID'])
			ect_query("UPDATE cart SET cartCompleted=3,cartOrderID=0,cartClientID=".$rs2['listOwner']." WHERE cartID='".escape_string($thecartid)."'") or ect_error();
		else{
			if($rs2['cartProdID']==$giftwrappingid)
				ect_query("UPDATE cart SET cartGiftWrap=0 WHERE " . getsessionsql()) or ect_error();
			else
				print '<script>gtag("event","remove_from_cart", { currency:"' . $GLOBALS['countryCurrency'] . '",value:' . $rs2['cartProdPrice'] . ',items:[' . getcartforganalytics($thecartid) . ']});</script>'."\n";
			ect_query("DELETE FROM cart WHERE cartID='".escape_string($thecartid)."'") or ect_error();
			ect_query("DELETE FROM cartoptions WHERE coCartID='".escape_string($thecartid)."'") or ect_error();
			ect_query("DELETE FROM giftcertificate WHERE gcCartID='".escape_string($thecartid)."'") or ect_error();
			updategiftwrap();
		}
	}elseif(@$_SESSION['clientID']!=''){
		ect_free_result($result);
		$sSQL="SELECT cartID FROM cart INNER JOIN customerlists ON cart.cartListID=customerlists.listID WHERE cartID='".escape_string($thecartid)."' AND listOwner=" . $_SESSION['clientID'];
		$result=ect_query($sSQL) or ect_error();
		if(ect_num_rows($result)>0) ect_query("UPDATE cart SET cartListID=0 WHERE cartID='".escape_string($thecartid)."'") or ect_error();
	}
	ect_free_result($result);
}
function writeshippingflags($costage){
	global $willpickuptext,$willpickupcost,$willpickup_,$commercialloc,$saturdaydelivery,$addshippinginsurance,$allowsignaturerelease,$signatureoption,$insidedelivery,$ordComLoc,$redstar,$holdatlocation,$homedelivery,$tleft,$tright,$ordName,$ordPayProvider,$paypalcheckoutexpress,$shipType;
	$hasshipflag=FALSE;
	if($shipType!=0){
		if(@$willpickuptext!='' || $willpickup_ || @$commercialloc || @$saturdaydelivery || abs(@$addshippinginsurance)==2 || (@$allowsignaturerelease && @$signatureoption!='') || @$insidedelivery || @$holdatlocation || @$homedelivery) $hasshipflag=TRUE;
	}
	if(@$GLOBALS['termsandconditions']&&$costage==3&&($ordPayProvider=='19'||$ordPayProvider=='21'||$ordPayProvider=='26'||$paypalcheckoutexpress)) $hasshipflag=TRUE;
	if($hasshipflag) print '<div class="coshipflagscontainer">';
	if(@$willpickuptext!='' || $willpickup_){ ?>
			<div class="billformrowflags"><div class="cdshipftflag cdformtwillpickup"><input type="checkbox" class="ectcheckbox" name="willpickup" id="shipflag0" value="Y" <?php
				if($willpickup_) print 'checked="checked" ';
				if($costage==3) print 'onchange="setchangeflag(this.checked,\'w\')" '?>/></div>
			<div class="cdshipflag cdformwillpickup"><?php print labeltxt($willpickuptext,'shipflag0') . (@$willpickupcost!=''?' (' . FormatEuroCurrency($willpickupcost) . ')' : '')?></div></div>
<?php
	}
	if(!$willpickup_&&$shipType!=0){
		if(@$commercialloc==TRUE){ ?>
			<div class="billformrowflags"><div class="cdshipftflag"><input type="checkbox" class="ectcheckbox" name="commercialloc" id="shipflag1" value="Y" <?php
			if(($ordComLoc & 1)==1 || ($ordName=='' && @$commercialloc===2)) print 'checked="checked" ';
			if($costage==3) print 'onchange="setchangeflag(this.checked,0)" '?>/></div>
			<div class="cdshipflag"><?php print labeltxt($GLOBALS['xxComLoc'],'shipflag1')?></div></div>
<?php	}
		if(@$saturdaydelivery==TRUE){ ?>
			<div class="billformrowflags"><div class="cdshipftflag"><input type="checkbox" class="ectcheckbox" name="saturdaydelivery" id="shipflag2" value="Y" <?php
			if(($ordComLoc & 4)==4) print 'checked="checked" ';
			if($costage==3) print 'onchange="setchangeflag(this.checked,2)" '?>/></div>
			<div class="cdshipflag"><?php print labeltxt($GLOBALS['xxSatDel'],'shipflag2')?></div></div>
<?php	}
		if(abs(@$addshippinginsurance)==2){ ?>
			<div class="billformrowflags"><?php
				if(@$GLOBALS['forceinsuranceselection']&&$costage!=3)
					print '<div class="cdshipftselect"><select class="ectselectinput" name="wantinsurance" size="1" onchange="remwarning(this)" aria-required="true"><option value="">'.$GLOBALS['xxPlsSel'].'</option><option value="">'.$GLOBALS['xxNo'].'</option><option value="Y">'.$GLOBALS['xxYes'].'</option></select></div>';
				else
					print '<div class="cdshipftflag"><input type="checkbox" class="ectcheckbox" name="wantinsurance" id="shipflag3" value="Y" '.(($ordComLoc & 2)==2?'checked="checked"':'').($costage==3?'onchange="setchangeflag(this.checked,1)" ':'').'/></div>';?>
			<div class="cdshipflag"><?php print labeltxt(@$GLOBALS['forceinsuranceselection']?$GLOBALS['xxChoIns']:$GLOBALS['xxWantIns'],'shipflag3')?></div></div>
<?php	}
		if(@$allowsignaturerelease==TRUE && @$signatureoption!=''){ ?>
			<div class="billformrowflags"><div class="cdshipftflag"><input type="checkbox" class="ectcheckbox" name="signaturerelease" id="shipflag4" value="Y" <?php
			if(($ordComLoc & 8)==8) print 'checked="checked" ';
			'onchange="setchangeflag(this.checked,3)" '?>/></div>
			<div class="cdshipflag"><?php print labeltxt($GLOBALS['xxSigRel'],'shipflag4')?></div></div>
<?php	}
		if(@$insidedelivery==TRUE){ ?>
			<div class="billformrowflags"><div class="cdshipftflag"><input type="checkbox" class="ectcheckbox" name="insidedelivery" id="shipflag5" value="Y" <?php
			if(($ordComLoc & 16)==16) print 'checked="checked" ';
			'onchange="setchangeflag(this.checked,4)" '?>/></div>
			<div class="cdshipflag"><?php print labeltxt($GLOBALS['xxInsDel'],'shipflag5')?></div></div>
<?php	}
		if(@$holdatlocation==TRUE){ ?>
			<div class="billformrowflags"><div class="cdshipftflag"><input type="checkbox" class="ectcheckbox" name="holdatlocation" id="shipflag6" value="Y" /></div>
			<div class="cdshipflag"><?php print labeltxt('Please click here to Hold at Location','shipflag6')?></div></div>
<?php	}
		if(@$homedelivery==TRUE){ ?>
			<div class="billformrowflags"><div class="cdshipftflag">Delivery Options:</div>
			<div class="cdshipftselect"><select name="homedelivery" class="ectselectinput" size="1">
			<option value="">Standard Delivery</option>
			<option value="EVENING">Evening Home Delivery</option>
			<option value="DATE_CERTAIN">Date Certain Home Delivery</option>
			<option value="APPOINTMENT">Appointment Home Delivery</option>
			</select></div></div>
<?php	}
	}
	if(@$GLOBALS['termsandconditions']&&$costage==3&&($ordPayProvider=='19'||$ordPayProvider=='21'||$ordPayProvider=='26'||$paypalcheckoutexpress)){ ?>
		<div class="billformrowflags">
		  <div class="cdshipftflag"><input type="checkbox" name="termsandconds" class="ectcheckbox" onchange="ectremoveclass(this,'ectwarning')" id="ecttnccheckbox" value="1" onclick="document.getElementById('sftermsandconds').value=this.checked?1:''"<?php print (getpost('sftermsandconds')=='1'?' checked':'')?> aria-required="true"></div>
		  <div class="cdshipflag"><?php print labeltxt($GLOBALS['xxTermsCo'],'ecttnccheckbox')?></div>
		</div>
<?php
	}
	if($hasshipflag) print '</div>';
}
function displaycartactions($cid,$tlistid){
	global $haspubliclist,$imgdelete,$imgmovetocart,$imgcartaddtolist,$ispubliclist,$itemdeleted;
	if(!$ispubliclist) print '<div class="cartdelete"><a href="#"><img class="cartdelete" src="images/delete.png" alt="'.$GLOBALS['xxDelete'].'" onclick="return dodelete('.$cid.',\''.$tlistid.'\')" /></a></div>';
	if($haspubliclist&&$ispubliclist&&!$itemdeleted)
		print '<div class="cartaddtolist">'.imageorbuttontag(@$imgmovetocart,$GLOBALS['xxMovCar'],'cartaddtolist','whichcartid=\''.$cid.'\';return dosaveitem(\'x\')', TRUE).'</div>';
	elseif(@$_SESSION['clientID']!=''&&@$GLOBALS['enablewishlists']&&!$itemdeleted)
		print '<div class="cartaddtolist"><div style="position:relative;display:inline">'.imageorbuttontag(@$imgcartaddtolist,$GLOBALS['xxMovToL'],'cartaddtolist','return cartdispsavelist('.$cid.',\''.$tlistid.'\',this)', TRUE).'</div></div>';
}
function writeestimatormenu(){
	global $shippingoptionsasradios,$adminAltRates,$international,$shipping,$handling,$adminShipping,$adminIntShipping,$mobilebrowser;
	if($adminAltRates==2){
		print '<div class="estimatorchecktext" id="estimatorchecktext"></div><div class="estimatorcheckcarrier" id="estimatorcheckcarrier"></div>';
	}elseif($adminAltRates==1){
		$sSQL='SELECT altrateid,altratename,'.getlangid('altratetext',65536).',usealtmethod,usealtmethodintl FROM alternaterates WHERE usealtmethod'.$international.'<>0 ORDER BY altrateorder'.$international.',altrateid';
		$result=ect_query($sSQL) or ect_error();
		if(ect_num_rows($result)>0){
			if(@$shippingoptionsasradios!=TRUE) print '<select id="altratesselect" size="1" onchange="selaltrate(this[this.selectedIndex].value)"'.($mobilebrowser?' style="font-size:10px"':'').'>'; else print '<div'.($mobilebrowser?' style="font-size:10px"':'').'>';
			while($rs=ect_fetch_assoc($result)){
				writealtshipline($rs[getlangid('altratetext',65536)],$rs['altrateid'],$GLOBALS['xxOrCom'].': ',$GLOBALS['xxShEsWi'].': ',TRUE);
			}
			if(@$shippingoptionsasradios!=TRUE) print '</select>'; else print '</div>';
		}
		ect_free_result($result);
	}
}
function displaydiscounts(){
	global $checkoutmode,$totaldiscounts,$loyaltypointdiscount,$loyaltypointsavailable,$loyaltypointvalue,$countryTax,$totalgoods;
	if($totaldiscounts>0) print '<div class="cartdiscounts_cntnr"><div class="cartdiscountstext ectdscntt">' . $GLOBALS['xxDsApp'] . '</div><div class="cartdiscounts ectdscnt" id="discountspan">' . FormatEuroCurrency($totaldiscounts) . "</div></div>\r\n";
	if($checkoutmode!='savedcart' && round($loyaltypointsavailable*$loyaltypointvalue,2)>=(@$GLOBALS['loyaltypointminimum']!=''?$GLOBALS['loyaltypointminimum']:0.05)){
		if(@$_SESSION['noredeempoints']!=TRUE){
			$loyaltypointdiscount=$loyaltypointsavailable*$loyaltypointvalue;
			if($loyaltypointdiscount>$totalgoods+(@$GLOBALS['showtaxinclusive']==3?$countryTax:0)-$totaldiscounts) $loyaltypointdiscount=$totalgoods+(@$GLOBALS['showtaxinclusive']==3?$countryTax:0)-$totaldiscounts;
		}
		print '<div class="cartloyaltypoint_cntnr"><div class="cartloyaltypointmenu ectdscntt">';
		print '<select size="1" onchange="document.location=\'cart'.$GLOBALS['extension'].'?redeempoints=\'+(this.selectedIndex==1?\'no\':\'yes\')"><option value="">' . $GLOBALS['xxReLPts'] . '</option><option value=""' . (@$_SESSION['noredeempoints']==TRUE ? ' selected="selected"' : '') . '>' . $GLOBALS['xxSaLPts'] . ' (' . $loyaltypointsavailable . ')</option></select>';
		print '</div><div class="cartloyaltypoints ectdscnt">';
		if(@$_SESSION['noredeempoints']==TRUE) print '-'; else print FormatEuroCurrency($loyaltypointdiscount);
		print '</div></div>';
	}
}
function displaycartclosed(){
	global $listid,$displaylistid,$cartlistnumber;
	if($listid==='') return FALSE;
	if(getget('pli')!=='') return getget('pli')!=$listid;
	return (string)$displaylistid!==(string)$cartlistnumber && (string)getpost('listid')!==(string)$listid;
}
function displaylistheader($cartlistnumber,$checkoutstep,$listname,$isclosed,$numitems,$tclass){
	print '<div class="cartlistdiv cartlistshop">';
	print '<div class="ectdivhead cartlistname cartlistcart" style="cursor:pointer" onclick="document.getElementById(\'cartlistid'.$cartlistnumber."').style.display==''?document.getElementById('cartlistimgid".$cartlistnumber."').src='images/arrow-down.png':document.getElementById('cartlistimgid".$cartlistnumber."').src='images/arrow-up.png';document.getElementById('cartlistid".$cartlistnumber."').style.display=(document.getElementById('cartlistid".$cartlistnumber.'\').style.display==\'\'?\'none\':\'\')"><div class="checkoutstep'.($cartlistnumber==2?' checkoutstepof3':'').'">'.($cartlistnumber==2?$checkoutstep:'&nbsp;').'</div><div class="cartname">' . $listname . ($numitems>0?' (' . $numitems . ')':'') . '</div><div class="cartlistimg"><img src="images/arrow-' . ($isclosed?'down':'up') . '.png" id="cartlistimgid'.$cartlistnumber.'" alt="Show / Hide Cart" /></div></div>' . "\r\n";
	print '</div>';
	print '<div class="' . trim('cartlistcontents '.$tclass) . '" id="cartlistid'.$cartlistnumber.'"' . ($isclosed?' style="display:none"':'') . '>';
}
function showcartlines($iscartresume){
	global $itemsincart,$cartlineunique,$cartrows,$outofstockarr,$changechecker,$amazonpaycheckout,$checkoutmode,$cartlistnumber,$shipType,$totalquantity,$totalgoods,$giftcertificateid,$giftwrappingid,$donationid,$handlingeligablegoods;
	global $shipfreegoods,$stockwarning,$backorder,$countryTax,$countryTaxRate,$countrytaxfree,$somethingToShip,$handlingeligableitem,$shipdiscountexempt,$numshipdiscountexempt,$minquantityerror,$deleteditemerror;
	if($iscartresume) $GLOBALS['linkcartproducts']=FALSE;
	if(!$amazonpaycheckout){
		if(($stockwarning || $backorder) && $checkoutmode!='savedcart'){
			print '<div class="cartstockbackorder_cntnr">';
			if($stockwarning){
				print '<div class="cartstockwarning"><div class="cartoutstock ectwarning">' . $GLOBALS['xxNoStok'].'</div>' .
					'<div class="cartstockacceptlevel"><button type="button" style="margin:10px auto" onclick="acceptstock()" class="ectbutton">' . $GLOBALS['xxStkUTo'].' '.$GLOBALS['xxClkHere'];
				if(getget('mode')!='add' && $checkoutmode!='update') print '<div style="margin-top:5px;font-size:11px">' . $GLOBALS['xxJusBuy'] . '</div>';
				print '</button></div>';
				print '</div>';
			}
			if($backorder) print '<div class="cartbackorder ectwarning">' . $GLOBALS['xxBakOrW'] . '</div>';
			print '</div>';
		}
		if(@$GLOBALS['priceschangedwarning']!=''){
			print '<div class="pricechanged">' . $GLOBALS['priceschangedwarning'] . '</div>';
		}
		$minquantmessage='';
		for($index=0;$index<$itemsincart;$index++){
			if($cartrows[$index]['cartQuantity']<=$cartrows[$index]['pMinQuant']&&$cartrows[$index]['pMinQuant']>0){
				$minquantmessage.='<div class="ectwarning">' . str_replace(array('%pname%','%quant%'),array($cartrows[$index]['cartProdName'],$cartrows[$index]['pMinQuant']+1),$GLOBALS['xxMinQuw']) . '</div>';
				if($checkoutmode!='savedcart') $minquantityerror=TRUE;
			}
			if(is_null($cartrows[$index]['pID'])&&$cartrows[$index]['cartProdID']!=$donationid&&$cartrows[$index]['cartProdID']!=$giftcertificateid&&$cartrows[$index]['cartProdID']!=$giftwrappingid){
				$minquantmessage.='<div class="ectwarning">' . str_replace('%pname%',$cartrows[$index]['cartProdName'],'The product %pname% has been deleted from the product catalog.') . '</div>';
				if($checkoutmode!='savedcart') $deleteditemerror=TRUE;
			}
		}
		if($minquantmessage!='') print '<div class="cartminquant_cntnr">' . $minquantmessage . '</div>';
		print '<div class="cartdetails_cntnr">';
		print '<div class="cartdetails cartdetailsid"></div>';
		print '<div class="cartdetails cartdetailsnameprice' . ($iscartresume?' cartdetailsnamepricecr':'') . '">';
			print '<div class="cartdetails cartdetailsname' . ($iscartresume?' cartdetailsnamecr':'') . '">' . $GLOBALS['xxCOName'] . '</div>';
			if(!@$GLOBALS['nopriceanywhere']) print '<div class="cartdetails cartdetailsprice">' . $GLOBALS['xxCOUPri'] . '</div>';
		print '</div>';
		print '<div class="cartdetailsquanttotal">';
			print '<div class="cartdetails cartdetailsquant">' . $GLOBALS['xxQuanty'] . '</div>';
			if(!$iscartresume) print '<div class="cartdetails cartdetailscheck">&nbsp;</div>';
			print '<div class="cartdetails cartdetailstotal">' . (@$GLOBALS['nopriceanywhere']?'&nbsp;':$GLOBALS['xxTotal']) . '</div>';
		print '</div>';
		print '</div>';
	}
	print '<div class="cartlineitems">';
	for($index=0;$index<$itemsincart;$index++){
		$cartlineunique++;
		$alldata=$cartrows[$index];
		$itemdeleted=(is_null($alldata['pID'])&&$alldata['cartProdID']!=$donationid&&$alldata['cartProdID']!=$giftcertificateid);
		$sSQL="SELECT imageSrc FROM productimages WHERE imageType=0 AND imageProduct='" . escape_string($alldata['cartProdID']) . "' ORDER BY imageNumber LIMIT 0,1";
		$result2=ect_query($sSQL) or ect_error();
		if($rs2=ect_fetch_assoc($result2)) $alldata['pImage']=$rs2['imageSrc'];
		ect_free_result($result2);
		if($alldata['pImage']=='' && trim_($alldata['cartOrigProdID'])!=''){
			$sSQL="SELECT imageSrc FROM productimages WHERE imageType=0 AND imageProduct='" . escape_string($alldata['cartOrigProdID']) . "' ORDER BY imageNumber LIMIT 0,1";
			$result2=ect_query($sSQL) or ect_error();
			if($rs2=ect_fetch_assoc($result2)) $alldata['pImage']=$rs2['imageSrc'];
			ect_free_result($result2);
		}
		if(is_null($alldata['pWeight'])) $alldata['pWeight']=0;
		if(is_null($alldata['pExemptions'])){
			if($alldata['cartProdID']==$giftcertificateid || $alldata['cartProdID']==$donationid) $alldata['pExemptions']=15;
			if($alldata['cartProdID']==$giftwrappingid) $alldata['pExemptions']=12;
		}
		$changechecker.='if(document.checkoutform.quant' . $alldata['cartID'] . '.value!=' . $alldata['cartQuantity'] . ") dowarning=true;\n";
		$theoptions='';
		$theoptionspricediff=0;
		$isoutofstock=FALSE;
		$sSQL="SELECT coID,coOptGroup,coCartOption,coPriceDiff,coWeightDiff,optAltImage,optType FROM cartoptions LEFT JOIN options ON cartoptions.coOptID=options.optID LEFT JOIN optiongroup ON options.optGroup=optiongroup.optGrpID WHERE coCartID=" . $alldata['cartID'] . ' ORDER BY coID';
		$opts=ect_query($sSQL) or ect_error();
		$optPriceDiff=0;
		while($rs=ect_fetch_assoc($opts)){
			$optoutofstock=FALSE;
			foreach($outofstockarr as $outofstockitem){
				if($outofstockitem[0]==$rs['coID'] && $outofstockitem[1]==TRUE && $outofstockitem[4]==FALSE){ $optoutofstock=TRUE; $isoutofstock=TRUE; }
			}
			$theoptionspricediff+=$rs['coPriceDiff'];
			$alldata['pWeight']+=(float)$rs['coWeightDiff'];
			if(trim_($rs['optAltImage'])!='' && @$GLOBALS['useimageincart'] && $rs['optType']!=4){
				if(strpos(trim($alldata['pImage']), '%s')!==FALSE) $alldata['pImage']=str_replace('%s', $rs['optAltImage'], trim($alldata['pImage'])); else $alldata['pImage']=$rs['optAltImage'];
			}
			$theoptions.='<div class="cartoptionsline' . ($optoutofstock ? ' ectwarning' : '') . '"><div class="cartoptiongroup' . ($itemdeleted?' ectwarning':'') . '">' . $rs['coOptGroup'] . '</div><div class="cartoptiongroupspacer"></div>' .
				'<div class="cartoption' . ($itemdeleted?' ectwarning':'') . '">' . str_replace(array("\r\n","\n"),array('<br>','<br>'),htmlspecials($rs['coCartOption'])) . '</div>';
			if(!@$GLOBALS['nopriceanywhere']) $theoptions.='<div class="cartoptionprice' . ($itemdeleted?' ectwarning':'') . '">' . ($rs['coPriceDiff']==0 || @$GLOBALS['hideoptpricediffs']==TRUE ? '- ' : FormatEuroCurrency($rs['coPriceDiff'])) . '</div>';
			if(!@$GLOBALS['nopriceanywhere']) $theoptions.='<div class="cartoptiontotal' . ($itemdeleted?' ectwarning':'') . '">' . ($rs['coPriceDiff']==0 || @$GLOBALS['hideoptpricediffs']==TRUE ? '- ' : FormatEuroCurrency($rs['coPriceDiff']*$alldata['cartQuantity'])) . '</div>';
			$theoptions.='</div>' . "\r\n";
			$totalgoods+=($rs['coPriceDiff']*(int)$alldata['cartQuantity']);
			if(($alldata['pExemptions'] & 8)!=8) $handlingeligablegoods+=$rs['coPriceDiff']*(int)$alldata['cartQuantity'];
		}
		ect_free_result($opts);
		foreach($outofstockarr as $outofstockitem){
			if($outofstockitem[0]==$alldata['cartID'] && $outofstockitem[1]==FALSE && $outofstockitem[4]==FALSE) $isoutofstock=TRUE;
		}
		$cartOrigProdName=$alldata['cartProdName'];
		if($alldata['cartOrigProdID']!=''){
			$opts=ect_query("SELECT pName,pDisplay,".getaltlang('pStaticURL',8388608).",pStaticPage,".getlangid('pLongDescription',4)." FROM products WHERE pID='" . escape_string($alldata['cartOrigProdID']) . "'") or ect_error();
			if($rs=ect_fetch_assoc($opts)){
				$alldata['pDisplay']=$rs['pDisplay'];
				$alldata['pStaticURL']=$rs['pStaticURL'];
				$alldata['pStaticPage']=$rs['pStaticPage'];
				$cartOrigProdName=$rs['pName'];
				$alldata[getlangid('pLongDescription',4)]=$rs[getlangid('pLongDescription',4)];
			}
			ect_free_result($opts);
		}
		if(!(@$GLOBALS['forcedetailslink'] || trim_($alldata[getlangid('pLongDescription',4)])!='')){
			$opts=ect_query("SELECT imageSrc FROM productimages WHERE imageType=1 AND imageProduct='" . escape_string($alldata['cartProdID']) . "' ORDER BY imageNumber LIMIT 0,1") or ect_error();
			if($rs=ect_fetch_assoc($opts)) $GLOBALS['forcedetailslink']=TRUE;
			ect_free_result($opts);
		}
		if($alldata['pDisplay']!=0 && @$GLOBALS['linkcartproducts'] && (@$GLOBALS['forcedetailslink'] || trim($alldata[getlangid('pLongDescription',4)])!='')){
			$thedetailslink=getdetailsurl($alldata['cartOrigProdID']?$alldata['cartOrigProdID']:$alldata['cartProdID'],$alldata['pStaticPage'],$cartOrigProdName,$alldata['pStaticURL'],'',@$GLOBALS['pathtohere']);
			if(@$GLOBALS['detailslink']!=''){
				$startlink=str_replace('%pid%', $alldata['cartProdID'], $GLOBALS['detailslink']);
				$endlink=@$detailsendlink;
			}else{
				$startlink='<a class="ectlink" href="'.$thedetailslink.'">';
				$endlink='</a>';
			}
		}else{
			$startlink='';
			$endlink='';
		}
		if(!$amazonpaycheckout){ // Cart line
			print '<div class="cartandoptsline"><div class="cartline">';
				print '<div class="cartlineid' . ($itemdeleted?' ectwarning':'') . '">';
				if(@$GLOBALS['useimageincart'] && ! (trim($alldata['pImage'])=='' || trim($alldata['pImage'])=='prodimages/')) print $startlink . '<img class="cartimage" src="' . $alldata['pImage'] . '" alt="' . strip_tags($alldata['cartProdName']) . '" />' . $endlink; else print $startlink . $alldata['cartProdID'] . $endlink;
				print '</div>';
				print '<div class="cartlinenameprice">';
					print '<div class="cartlinename' . ($iscartresume?' cartlinenamecr':'') . ($itemdeleted?' ectwarning':'') . '">';
					print $startlink . $alldata['cartProdName'] . $endlink;
					if($alldata['pGiftWrap']!=0 && !$iscartresume) print '<div class="giftwrap"><a href="cart'.$GLOBALS['extension'].'?mode=gw">' . ($alldata['cartGiftWrap']!=0?$GLOBALS['xxGWrSel']:$GLOBALS['xxGWrAva']) . '</a></div>';
					$sSQL="SELECT quantity,pName,quantity FROM productpackages INNER JOIN products on productpackages.pID=products.pID WHERE packageID='" . escape_string($alldata['cartProdID']) . "'";
					$result2=ect_query($sSQL) or ect_error();
					if(ect_num_rows($result2)>0){
						print '<div class="packagediv">';
						while($rs2=ect_fetch_assoc($result2))
							print '<div class="packagerow">' . $rs2['pName'] . ' (' . $rs2['quantity'] . ')</div>';
						print '</div>';
					}
					ect_free_result($result2);
					print '</div>';
					if(@$GLOBALS['nopriceanywhere']!=TRUE) print '<div class="cartlineprice' . ($itemdeleted?' ectwarning':'') . '"><span class="cartlinepricelabel">' . $GLOBALS['xxCOUPri'] . '</span>' . (@$GLOBALS['hideoptpricediffs']==TRUE ? FormatEuroCurrency($alldata['cartProdPrice'] + $theoptionspricediff) : FormatEuroCurrency($alldata['cartProdPrice'])) . '</div>';
				print '</div>';
				print '<div class="cartlinequanttotal">';
					print '<div class="cartlinequant' . ($itemdeleted?' ectwarning':'') . '">';
					if($itemdeleted)
						print '-';
					elseif(getget('pla')!=''||$iscartresume)
						print $alldata['cartQuantity'];
					else
						print '<input class="ecttextinput cartquant" onkeydown="showupdatebutton('.$alldata['cartID'].','.$cartlineunique.',\''.$cartlistnumber.'\')" type="text" id="quant' . $alldata['cartID'] . '" value="' . $alldata['cartQuantity'] . '" size="2" maxlength="5" ' . ($isoutofstock||$alldata['cartQuantity']<=$alldata['pMinQuant']?'style="background-color:#FF7070" ':'') . ($alldata['cartQuantity']<=$alldata['pMinQuant']?'title="'.htmlspecials(str_replace('%quant%',$alldata['pMinQuant']+1,$GLOBALS['xxMinQua'])).'" " ':'') . ' aria-label="Quantity for ' . htmlspecials($alldata['cartProdName']) . '">';
					print '</div>';
					if(!$iscartresume){
						print '<div class="cartlinecheck' . ($itemdeleted?' ectwarning':'') . '">';
						if($checkoutmode!='savedcart'){
						}elseif($alldata['cartCompleted']==0 || $alldata['cartCompleted']==2)
							print '<div class="wishlistpurch wishlistpurchasing">' . $GLOBALS['xxPurcha'] . '</div>';
						elseif($alldata['cartCompleted']==1)
							print '<div class="wishlistpurch wishlistpurchased">' . $GLOBALS['xxPurchd'] . '</div>';
						displaycartactions($alldata['cartID'],$cartlistnumber);
						print '</div>';
					}
					print '<div class="cartlinetotal' . ($itemdeleted?' ectwarning':'') . '" id="cartlinetot'.$cartlineunique.'">' . (@$GLOBALS['nopriceanywhere']?'-':(@$GLOBALS['hideoptpricediffs']==TRUE ? FormatEuroCurrency(($alldata['cartProdPrice'] + $theoptionspricediff)*$alldata['cartQuantity']) : FormatEuroCurrency($alldata['cartProdPrice']*$alldata['cartQuantity']))) . '</div>';
				print '</div>';
			print "</div>\r\n";
			//if(@$GLOBALS['iswordpress']) ob_flush();
			print $theoptions . '</div>';
		}
		$runTot=$alldata['cartProdPrice'] * (int)$alldata['cartQuantity'];
		$totalquantity+=(int)$alldata['cartQuantity'];
		$totalgoods+=($alldata['cartProdPrice']*(int)$alldata['cartQuantity']);
		if(!$iscartresume){
			$alldata['cartProdPrice']+=$theoptionspricediff;
			if(trim_(@$_SESSION['clientID'])!=''){ $alldata['pExemptions']=((int)$alldata['pExemptions'] | ((int)$_SESSION['clientActions'] & 7)); if(((int)$_SESSION['clientActions'] & 32)==32) $alldata['pExemptions']|=8; }
			if(($shipType==2 || $shipType==3 || $shipType==4 || $shipType>=6) && (float)$alldata['pWeight']<=0.0)
				$alldata['pExemptions']=($alldata['pExemptions'] | 4);
			if(@$GLOBALS['perproducttaxrate']){
				if(is_null($alldata['pTax'])) $alldata['pTax']=$countryTaxRate;
				if(($alldata['pExemptions'] & 2)!=2) $countryTax+=(($alldata['pTax'] * $alldata['cartProdPrice'] * (int)$alldata['cartQuantity']) / 100.0);
			}else{
				if(($alldata['pExemptions'] & 2)==2) $countrytaxfree+=$runTot + ($theoptionspricediff * (int)($alldata['cartQuantity']));
			}
			if(($alldata['pExemptions'] & 4)==4) $shipfreegoods+=$runTot; else $somethingToShip=TRUE;
			if($alldata['cartProdID']==$giftcertificateid || $alldata['cartProdID']==$donationid){ $shipdiscountexempt+=$runTot; $numshipdiscountexempt+=$alldata['cartQuantity']; }
			if(($alldata['pExemptions'] & 8)!=8){ $handlingeligableitem=TRUE; $handlingeligablegoods+=$runTot; }
			if(@$_SESSION['xsshipping']=='' && $checkoutmode!='savedcart') addproducttoshipping($alldata, $index);
		}
	}
	print '</div>';
}
function showcartresumeheader($checkoutstep){
	global $cartrows,$itemsincart,$totalgoods,$totalquantity;
	global $ordEmail,$ordName,$ordLastName,$ordAddress,$ordAddress2,$ordCity,$ordState,$ordZip,$ordCountry,$ordExtra1,$ordExtra2;
	global $ordShipName,$ordShipLastName,$ordShipAddress,$ordShipAddress2,$ordShipCity,$ordShipState,$ordShipZip,$ordShipCountry,$ordShipExtra1,$ordShipExtra2;
	$totalgoods=$totalquantity=0;
	$cartrows=[];
	$querystr='cartCompleted=0 AND '.getsessionsql();
	$sSQL="SELECT cartID,cartProdID,cartOrigProdID,cartProdName,cartProdPrice,cartQuantity,pWeight,pShipping,pShipping2,pExemptions,pSection,pDims,pTax,pStaticPage,pDisplay,'' AS pImage,'' AS pLargeImage,cartCompleted,pGiftWrap,cartGiftWrap,".getaltlang('pStaticURL',8388608).",pMinQuant,pID,".getlangid('pDescription',2).','.getlangid('pLongDescription',4).' FROM cart LEFT JOIN products ON cart.cartProdID=products.pID LEFT OUTER JOIN sections ON products.pSection=sections.sectionID WHERE ' . $querystr . ' ORDER BY cartID';
	$result=ect_query($sSQL) or ect_error();
	$itemsincart=ect_num_rows($result);
	while($rsCart=ect_fetch_assoc($result))
		$cartrows[]=$rsCart;
	displaylistheader(0,$checkoutstep,$GLOBALS['xxShoCar'],@$GLOBALS['cartresumeopen']?FALSE:TRUE,$itemsincart,'cartresumecontents');
	if(count($cartrows)>0) showcartlines(TRUE);
	calculatetaxandhandling();
	print '</div>';
	if($checkoutstep==3&&trim($ordName.$ordLastName)!=''){
		displaylistheader(1,$checkoutstep,$GLOBALS['xxCusDet'],@$GLOBALS['custdetailsresumeopen']?FALSE:TRUE,0,'custdetailsresume');
?>
<script>
function checkcustdetails(){
	var form = document.createElement("form");
	var element1 = document.createElement("input");
	form.method = "POST";
	form.action = "cart<?php print $GLOBALS['extension']?>";
	element1.value='checkout';
	element1.name='mode';
	form.appendChild(element1);  
	document.body.appendChild(form);
	form.submit();
	document.body.removeChild(form);
}
</script>
<?php		print '<div class="custdetsresumehead">' . $GLOBALS['xxContEm'] . '</div>';
			print '<div class="custdetsresumeline">' . htmlspecials($ordEmail) . '</div>';
			print '<div class="custdetsresumehead">' . $GLOBALS['xxBilAdd'] . '</div>';
			print '<div class="custdetsresumeline">' . (@$ordExtra1!=''?@$GLOBALS['extraorderfield1'].': '.$ordExtra1.'<br>':'') . trim($ordName.' '.$ordLastName).', '.$ordAddress.(@$ordAddress2!=''?', '.$ordAddress2:'').', '.trim($ordCity.' '.$ordState.' '.$ordZip). ', ' . $ordCountry . (@$ordExtra2!=''?'<br>' . @$GLOBALS['extraorderfield2'] . ': '. $ordExtra2:'') . '</div>';
			if(trim($ordShipAddress)!=''){
				print '<div class="custdetsresumehead">' . $GLOBALS['xxShpAdd'] . '</div>';
				print '<div class="custdetsresumeline">' . (@$ordShipExtra1!=''?@$GLOBALS['extraorderfield1'].': '.$ordShipExtra1.'<br>':'') . trim($ordShipName.' '.$ordShipLastName).', '.$ordShipAddress.(@$ordShipAddress2!=''?', '.$ordShipAddress2:'').', '.trim($ordShipCity.' '.$ordShipState.' '.$ordShipZip). ', ' . $ordShipCountry . (@$ordShipExtra2!=''?'<br>' . @$GLOBALS['extraorderfield2'] . ': '. $ordShipExtra2:'') . '</div>';
			}
			print '<div><input class="ectbutton" type="button" value="Change" onclick="checkcustdetails()" /></div>';
		print '</div>';
	}
	displaylistheader(2,$checkoutstep,$GLOBALS[$checkoutstep==2?'xxCstDtl':'xxChkCmp'],FALSE,0,'cartmaincontents');
}
function requirevalidstate($tshiptype){
	global $splitUSZones,$adminAltRates;
	$isrequired=FALSE;
	if($splitUSZones){
		if(@$adminAltRates==2){
			$result=ect_query('SELECT altrateid FROM alternaterates WHERE usealtmethod<>0 AND altrateid IN (2,5)') or ect_error();
			$isrequired=ect_num_rows($result)>0;
			ect_free_result($result);
		}else{
			$isrequired=$tshiptype==2||$tshiptype==5;
		}
	}
	return $isrequired;
}
$amzrefid_=getrequest('amzrefid');
if($amzrefid_!=''){ // Amazon Payment
	if(getpayprovdetails(21,$data1,$data2,$data3,$demomode,$ppmethod)){
		$ordPayProvider='21';
		$data2arr=explode('&',$data2);
		$data2=$data2arr[0];
		$sellerid=@$data2arr[1];
		$amazonstr='';
		$amazonprms=[];
		$ordName=$ordLastName=$ordAddress=$ordAddress2=$ordState=$ordCountry=$ordPhone=$ordEmail=$ordEmail2='';
		$countryid=$ordComLoc=0;
		$checkoutmode='go';
		$amazonpayment=TRUE;

		$timestamp=gmdate("Y-m-d\TH:i:s.\\0\\0\\0\\Z", time());
		$scripturl='mws-eu.amazonservices.com';
		if($GLOBALS['origCountryCode']=='US') $scripturl='mws.amazonservices.com';
		if($GLOBALS['origCountryCode']=='JP') $scripturl='mws.amazonservices.jp';
		$endpointpath='/OffAmazonPayments' . ($demomode?'_Sandbox':'') . '/2013-01-01';
		$endpoint='https://' . $scripturl . $endpointpath;

		amazonparam2('AWSAccessKeyId',$data2);
		amazonparam2('Action','GetOrderReferenceDetails');
		//amazonparam2('AddressConsentToken',ZZZ);
		amazonparam2('AmazonOrderReferenceId',$amzrefid_);
		amazonparam2('SellerId',$sellerid);
		amazonparam2('SignatureMethod','HmacSHA256');
		amazonparam2('SignatureVersion',2);
		amazonparam2('Timestamp',$timestamp);
		amazonparam2('Version','2013-01-01');
	// &OrderReferenceAttributes.PlatformId=PLATFORM_ID_HERE&OrderReferenceAttributes.SellerNote=Lorem%20ipsum&OrderReferenceAttributes.SellerOrderAttributes.StoreName=YOUR_STORE_NAME 
		calculateSignatureAndParametersToString();
		$amazonprms['Signature']=base64_encode(hash_hmac('sha256', calculateStringToSignV2($amazonprms), $data3, true));
		$amazonstr=getParametersAsString();
		
		if(callcurlfunction($endpoint,$amazonstr,$res,'',$errormsg,FALSE)){
			$xmlDoc=new vrXMLDoc($res);
			$nodeList=$xmlDoc->nodeList->childNodes[0];
			for($i=0; $i < $nodeList->length; $i++){
				if($nodeList->nodeName[$i]=='Error'){
					$amazonpayment=$checkoutmode='';
					$e=$nodeList->childNodes[$i];
					for($j=0; $j < $e->length; $j++){
						if($e->nodeName[$j]=='Message'){
							$carterror='Amazon Error: ' . $e->nodeValue[$j];
						}
					}
				}elseif($nodeList->nodeName[$i]=='GetOrderReferenceDetailsResult'){
					$e=$nodeList->childNodes[$i];
					for($j=0; $j < $e->length; $j++){
						if($e->nodeName[$i]=='OrderReferenceDetails'){
							$f=$e->childNodes[$j];
							for($k=0; $k < $f->length; $k++){
								if($f->nodeName[$k]=='Constraints'){
									$g=$f->childNodes[$k];
									for($l=0; $l < $g->length; $l++){
										if($g->nodeName[$l]=='Constraint'){
											$h=$g->childNodes[$l];
											$isamountconstraint=FALSE;
											for($m=0; $m < $h->length; $m++){
												if($h->nodeName[$m]=='ConstraintID'){
													if($h->nodeValue[$m]=='AmountNotSet'){
														$isamountconstraint=TRUE;
													}
												}elseif($h->nodeName[$m]=='Description'){
													$thisconstraint=$h->nodeValue[$m];
												}
											}
											if(!$isamountconstraint){
												$amazonpayment=$checkoutmode='';
												$carterror=$thisconstraint;
											}
										}
									}
								}elseif($f->nodeName[$k]=='Destination'){
									$g=$f->childNodes[$k];
									for($l=0; $l < $g->length; $l++){
										if($g->nodeName[$l]=='PhysicalDestination'){
											$h=$g->childNodes[$l];
											for($m=0; $m < $h->length; $m++){
												if($h->nodeName[$m]=='StateOrRegion'){
													$ordState=$h->nodeValue[$m];
												}elseif($h->nodeName[$m]=='City'){
													$ordCity=$h->nodeValue[$m];
												}elseif($h->nodeName[$m]=='CountryCode'){
													$tmpcntry=str_replace("'",'',$h->nodeValue[$m]);
													$sSQL='SELECT countryName,countryID,countryOrder FROM countries WHERE countryEnabled=1 AND ';
													if($tmpcntry=='GB')
														$sSQL.='countryID=201';
													elseif($tmpcntry=='FR')
														$sSQL.='countryID=65';
													elseif($tmpcntry=='PT')
														$sSQL.='countryID=153';
													elseif($tmpcntry=='ES')
														$sSQL.='countryID=175';
													else
														$sSQL.="countryCode='" . escape_string($tmpcntry) . "'";
													$result=ect_query($sSQL) or ect_error();
													if($rs=ect_fetch_assoc($result)){
														$ordCountry=$rs['countryName'];
														$countryid=$rs['countryID'];
														$homecountry=($countryid==$origCountryID);
													}else{
														$errormsg='Purchasing from your country is not supported.';
														$success=FALSE;
													}
													ect_free_result($result);
												}elseif($h->nodeName[$m]=='PostalCode'){
													$ordZip=$h->nodeValue[$m];
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}else
			print "curl failed<br>";
	}
}elseif(substr(getget('token'),0,2)=='EC' && $checkoutmode!='paypalcancel'){ // PayPal Express
	if(getpayprovdetails(19,$username,$password,$data3,$demomode,$ppmethod)){
		$data2arr=explode('&',$password);
		$password=urldecode(@$data2arr[0]);
		$isthreetoken=(trim(urldecode(@$data2arr[2]))=='1');
		$signature=''; $sslcertpath='';
		if($isthreetoken){
			$signature=urldecode(@$data2arr[1]);
			if(strpos($username,'/')!==FALSE){
				$username=explode('/',$username);$username=trim($username[0]);
				$password=explode('/',$password);$password=trim($password[0]);
				$signature=explode('/',$signature);$signature=trim($signature[0]);
			}
		}else
			$sslcertpath=urldecode(@$data2arr[1]);
		if(strpos($username,'@AB@')!==FALSE){
			$isthreetoken=TRUE;
			$signature='AB';
		}
	}
	$sXML=ppsoapheader($username, $password, $signature) .
		'<soap:Body><GetExpressCheckoutDetailsReq xmlns="urn:ebay:api:PayPalAPI"><GetExpressCheckoutDetailsRequest><Version xmlns="urn:ebay:apis:eBLBaseComponents">60.00</Version>' .
		'  ' . addtag('Token',getget('token')) . 
		'</GetExpressCheckoutDetailsRequest></GetExpressCheckoutDetailsReq></soap:Body></soap:Envelope>';
	if($demomode) $sandbox=".sandbox"; else $sandbox='';
	if(callcurlfunction('https://api' . ($isthreetoken?'-3t':'') . $sandbox . '.paypal.com/2.0/', $sXML, $res, $sslcertpath, $errormsg, 25)){
		$xmlDoc=new vrXMLDoc($res);
		$nodeList=$xmlDoc->nodeList->childNodes[0];
		$success=FALSE;
		$ordPhone=$ordEmail=$ordEmail2=$ordName=$ordLastName='';
		$countryid=0;
		$ordPayProvider='19';
		$ordComLoc=0;
		$gotaddress=FALSE;
		$token=getget('token');
		if(abs(@$addshippinginsurance)==1) $ordComLoc+=2;
		for($i=0; $i < $nodeList->length; $i++){
			if($nodeList->nodeName[$i]=='SOAP-ENV:Body'){
				$e=$nodeList->childNodes[$i];
				for($j=0; $j < $e->length; $j++){
					if($e->nodeName[$j]=='GetExpressCheckoutDetailsResponse'){
						$ee=$e->childNodes[$j];
						for($jj=0; $jj < $ee->length; $jj++){
							if($ee->nodeName[$jj]=='Ack'){
								if($ee->nodeValue[$jj]=='Success' || $ee->nodeValue[$jj]=='SuccessWithWarning')
									$success=TRUE;
							}elseif($ee->nodeName[$jj]=='GetExpressCheckoutDetailsResponseDetails'){
								$ff=$ee->childNodes[$jj];
								for($kk=0; $kk < $ff->length; $kk++){
									if($ff->nodeName[$kk]=='PayerInfo'){
										$gg=$ff->childNodes[$kk];
										for($ll=0; $ll < $gg->length; $ll++){
											if($gg->nodeName[$ll]=='Payer'){
												$ordEmail2=$ordEmail=$gg->nodeValue[$ll];
											}elseif($gg->nodeName[$ll]=='PayerID'){
												$payerid=$gg->nodeValue[$ll];
											}elseif($gg->nodeName[$ll]=='PayerStatus'){
												$ordCVV='U';
												$payer_status=strtolower($gg->nodeValue[$ll]);
												if($payer_status=='verified') $ordCVV='Y';
												elseif($payer_status=='unverified') $ordCVV='N';
											}elseif($gg->nodeName[$ll]=='PayerName'){
											}elseif($gg->nodeName[$ll]=='Address'){
												$hh=$gg->childNodes[$ll];
												for($mm=0; $mm < $hh->length; $mm++){
													if($hh->nodeName[$mm]=='Name'){
														splitfirstlastname(trim($hh->nodeValue[$mm]),$ordName,$ordLastName);
													}elseif($hh->nodeName[$mm]=='Street1'){
														$ordAddress=$hh->nodeValue[$mm];
													}elseif($hh->nodeName[$mm]=='Street2'){
														$ordAddress2=$hh->nodeValue[$mm];
													}elseif($hh->nodeName[$mm]=='CityName'){
														$ordCity=$hh->nodeValue[$mm];
													}elseif($hh->nodeName[$mm]=='StateOrProvince'){
														$ordState=$hh->nodeValue[$mm];
													}elseif($hh->nodeName[$mm]=='Country'){
														$tmpcntry=str_replace("'",'',$hh->nodeValue[$mm]);
														$sSQL='SELECT countryName,countryID,countryOrder FROM countries WHERE countryEnabled=1 AND ';
														if($tmpcntry=='GB')
															$sSQL.='countryID=201';
														elseif($tmpcntry=='FR')
															$sSQL.='countryID=65';
														elseif($tmpcntry=='PT')
															$sSQL.='countryID=153';
														elseif($tmpcntry=='ES')
															$sSQL.='countryID=175';
														else
															$sSQL.="countryCode='" . escape_string($tmpcntry) . "'";
														$result=ect_query($sSQL) or ect_error();
														if($rs=ect_fetch_assoc($result)){
															$ordCountry=$rs['countryName'];
															$countryid=$rs['countryID'];
															$homecountry=($countryid==$origCountryID);
														}else{
															$errormsg='Purchasing from your country is not supported.';
															$success=FALSE;
														}
														ect_free_result($result);
													}elseif($hh->nodeName[$mm]=='PostalCode'){
														$ordZip=strtoupper($hh->nodeValue[$mm]);
													}elseif($hh->nodeName[$mm]=='AddressStatus'){
														$ordAVS='U';
														$address_status=strtolower($hh->nodeValue[$mm]);
														$gotaddress=($address_status!='none');
														if($address_status=='confirmed') $ordAVS='Y';
														elseif($address_status=='unconfirmed') $ordAVS='N';
													}
												}
											}
										}
									}elseif($ff->nodeName[$kk]=='Custom'){
										$customarr=explode(':', $ff->nodeValue[$kk]);
										$thesessionid=@$customarr[0];
										$ordAffiliate=@$customarr[1];
										if(@$GLOBALS['closeaffiliateprogram'])$ordAffiliate='';
										if(substr($thesessionid,0,3)=='cid'){
											$_SESSION['clientID']=str_replace("'",'',substr($thesessionid,3));
											$sSQL="SELECT clID,clUserName,clActions,clLoginLevel,clPercentDiscount FROM customerlogin WHERE clID='" . escape_string($_SESSION['clientID']) ."'";
											$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;
											}
										}else
											$thesessionid=str_replace("'",'',substr($thesessionid,3));
									}elseif($ff->nodeName[$kk]=='ContactPhone'){
										$ordPhone=$ff->nodeValue[$kk];
									}
								}
							}elseif($ee->nodeName[$jj]=="Errors"){
								$ff=$ee->childNodes[$jj];
								for($kk=0; $kk < $ff->length; $kk++){
									if($ff->nodeName[$kk]=="ShortMessage"){
										$errormsg=$ff->nodeValue[$kk].'<br>'.$errormsg;
									}elseif($ff->nodeName[$kk]=="LongMessage"){
										$errormsg.=$ff->nodeValue[$kk];
									}elseif($ff->nodeName[$kk]=="ErrorCode"){
										$errcode=$ff->nodeValue[$kk];
									}
								}
							}
						}
					}
				}
			}
		}
		if(! $gotaddress){
			if(ob_get_length()!==FALSE)
				header('Location: ' . $storeurl . 'cart' . $GLOBALS['extension']);
			else
				print '<meta http-equiv="Refresh" content="0; URL=' . $storeurl . 'cart' . $GLOBALS['extension'] . '">';
			$cartisincluded=TRUE;
		}elseif($success){
			$paypalexpress=TRUE;
			if($homecountry){
				if(($countryid==1 || $countryid==2) && @$usestateabbrev!=TRUE){
					$sSQL="SELECT stateName FROM states WHERE (stateCountryID=1 OR stateCountryID=2) AND stateAbbrev='" . escape_string($ordState) . "'";
					$result=ect_query($sSQL) or ect_error();
					if($rs=ect_fetch_assoc($result))
						$ordState=$rs['stateName'];
					ect_free_result($result);
				}
				if(requirevalidstate($shipType)){
					$sSQL="SELECT stateName FROM states WHERE stateCountryID='" . escape_string($countryid) . "' AND (stateName='" . escape_string($ordState) . "' OR stateAbbrev='" . escape_string($ordState) . "')";
					$result=ect_query($sSQL) or ect_error();
					if(ect_num_rows($result)==0) $ordState='';
					ect_free_result($result);
				}
			}
		}else{
			$carterror='PayPal Express Error: '.$errormsg;
			$checkoutmode='paypalcancel';
		}
	}else{
		$carterror='PayPal Express Error: '.$errormsg;
		$checkoutmode='paypalcancel';
	}
}elseif($checkoutmode=='paypalexpress1'||$checkoutmode=='billmelater'){ // PayPal Express
	if(getpayprovdetails(19,$username,$password,$data3,$demomode,$ppmethod)){
		$data2arr=explode('&',$password);
		$password=urldecode(@$data2arr[0]);
		$isthreetoken=(trim(urldecode(@$data2arr[2]))=='1');
		$signature=''; $sslcertpath='';
		if($isthreetoken){
			$signature=urldecode(@$data2arr[1]);
			if(strpos($username,'/')!==FALSE){
				$username=explode('/',$username);$username=trim($username[0]);
				$password=explode('/',$password);$password=trim($password[0]);
				$signature=explode('/',$signature);$signature=trim($signature[0]);
			}
		}else
			$sslcertpath=urldecode(@$data2arr[1]);
		if(strpos($username,'@AB@')!==FALSE){
			$isthreetoken=TRUE;
			$signature='AB';
		}
	}
	if($demomode) $sandbox='.sandbox'; else $sandbox='';
	$theestimate=round((float)getpost('estimate'),2);
	$sXML=ppsoapheader($username, $password, $signature) .
		'<soap:Body><SetExpressCheckoutReq xmlns="urn:ebay:api:PayPalAPI"><SetExpressCheckoutRequest><Version xmlns="urn:ebay:apis:eBLBaseComponents">72.00</Version>' .
		'<SetExpressCheckoutRequestDetails xmlns="urn:ebay:apis:eBLBaseComponents">' .
		($checkoutmode=='billmelater'?'<FundingSourceDetails><UserSelectedFundingSource>BML</UserSelectedFundingSource></FundingSourceDetails>':'') .
		'<OrderTotal currencyID="' . $countryCurrency . '">' . $theestimate . '</OrderTotal>' .
		'<ReturnURL>' . $storeurlssl . 'cart' . $GLOBALS['extension'] . '</ReturnURL><CancelURL>' . $storeurlssl . 'cart' . $GLOBALS['extension'] . '?action=paypalcancel</CancelURL>' .
		'<Custom>' . (@$_SESSION['clientID']!='' ? 'cid' . $_SESSION['clientID'] : 'sid' . $thesessionid) . ':' . strip_tags(getpost('PARTNER')) . '</Custom>' .
		addtag('PaymentAction',$ppmethod==1?'Authorization':'Sale');
	$itemtotal=0;
	$sXML.='<PaymentDetails>';
	$sSQL="SELECT cartID,cartProdID,cartProdName,cartProdPrice,cartQuantity,pShipping,pShipping2,pExemptions,pTax,pDescription FROM cart LEFT JOIN products ON cart.cartProdID=products.pId WHERE cartCompleted=0 AND " . getsessionsql();
	$result=ect_query($sSQL) or ect_error();
	while($rs=ect_fetch_assoc($result)){
		$itemtotal+=$rs['cartProdPrice']*$rs['cartQuantity'];
		$description=''; $addcomma='';
		$optiontotal=0;
		$sSQL="SELECT coOptGroup,coCartOption,coPriceDiff FROM cartoptions WHERE coCartID=" . $rs['cartID'];
		$result2=ect_query($sSQL) or ect_error();
		while($rs2=ect_fetch_assoc($result2)){
			$optiontotal+=$rs2['coPriceDiff'];
			$description.=$addcomma . vrxmlencode(strip_tags($rs2['coOptGroup'])) . ' : ' . vrxmlencode(strip_tags($rs2['coCartOption']));
			$addcomma=', ';
		}
		ect_free_result($result2);
		$itemtotal+=$optiontotal*$rs['cartQuantity'];
		$sXML.='<PaymentDetailsItem><Number>' . vrxmlencode(strip_tags($rs['cartProdID'])) . '</Number><Name>' . vrxmlencode(strip_tags($rs['cartProdName'])) . '</Name><Description>' . substr($description,0,122) . (strlen($description)>122?'...':'') . '</Description><Amount currencyID="' . $countryCurrency . '">' . ($rs['cartProdPrice']+$optiontotal) . '</Amount><Quantity>' . $rs['cartQuantity'] . '</Quantity></PaymentDetailsItem>';
	}
	ect_free_result($result);
	if($itemtotal!=$theestimate){
		$sXML.='<PaymentDetailsItem><Name>' . vrxmlencode($GLOBALS['xxPPEst1']) . '</Name><Description>' . vrxmlencode($GLOBALS['xxPPEst2']) . '</Description><Amount currencyID="' . $countryCurrency . '">' . round($theestimate-$itemtotal, 2) . '</Amount><Quantity>1</Quantity></PaymentDetailsItem>';
	}
	$sXML.='</PaymentDetails>';
	if(@$paypallc!='') $sXML.=addtag('LocaleCode',$paypallc);
	$sXML.='  </SetExpressCheckoutRequestDetails>' .
		'</SetExpressCheckoutRequest></SetExpressCheckoutReq></soap:Body></soap:Envelope>';
	if($username==''){
		print '<meta http-equiv="Refresh" content="0; URL=https://www.paypal.com/us/webapps/mpp/referral/paypal-payments-pro?partner_id=39HT54MCDMV8E">';
		print '<p align="center">' . $GLOBALS['xxAutFo'] . '</p>';
		print '<p align="center">' . $GLOBALS['xxForAut'] . ' <a class="ectlink" href="https://www.paypal.com/us/webapps/mpp/referral/paypal-payments-pro?partner_id=39HT54MCDMV8E">' . $GLOBALS['xxClkHere'] . '</a></p>';
	}elseif(callcurlfunction('https://api' . ($isthreetoken?'-3t':'') . $sandbox . '.paypal.com/2.0/', $sXML, $res, $sslcertpath, $errormsg, 25)){
		$xmlDoc=new vrXMLDoc($res);
		$nodeList=$xmlDoc->nodeList->childNodes[0];
		$success=FALSE;
		$token='';
		for($i=0; $i < $nodeList->length; $i++){
			if($nodeList->nodeName[$i]=="SOAP-ENV:Body"){
				$e=$nodeList->childNodes[$i];
				for($j=0; $j < $e->length; $j++){
					if($e->nodeName[$j]=="SetExpressCheckoutResponse"){
						$ee=$e->childNodes[$j];
						for($jj=0; $jj < $ee->length; $jj++){
							if($ee->nodeName[$jj]=='Ack'){
								if($ee->nodeValue[$jj]=='Success' || $ee->nodeValue[$jj]=='SuccessWithWarning')
									$success=TRUE;
							}elseif($ee->nodeName[$jj]=="Token"){
								$token=$ee->nodeValue[$jj];
							}elseif($ee->nodeName[$jj]=="Errors"){
								$ff=$ee->childNodes[$jj];
								for($kk=0; $kk < $ff->length; $kk++){
									if($ff->nodeName[$kk]=="ShortMessage"){
										$errormsg=$ff->nodeValue[$kk].'<br>'.$errormsg;
									}elseif($ff->nodeName[$kk]=="LongMessage"){
										$errormsg.=$ff->nodeValue[$kk];
									}elseif($ff->nodeName[$kk]=="ErrorCode"){
										$errcode=$ff->nodeValue[$kk];
									}
								}
							}
						}
					}
				}
			}
		}
		if($success){
			if(ob_get_length()===FALSE){
				print '<meta http-equiv="Refresh" content="0; URL=https://www'.$sandbox.'.paypal.com/webscr?cmd=_express-checkout&token=' . $token . '">';
			}else
				header('Location: https://www'.$sandbox.'.paypal.com/webscr?cmd=_express-checkout&token=' . $token);
			print '<p align="center">' . $GLOBALS['xxAutFo'] . '</p>';
			print '<p align="center">' . $GLOBALS['xxForAut'] . ' <a class="ectlink" href="https://www'.$sandbox.'.paypal.com/webscr?cmd=_express-checkout&token=' . $token . '">' . $GLOBALS['xxClkHere'] . '</a></p>';
		}else{
			print "PayPal Payment Pro error: " . $errormsg;
		}
	}else{
		print "PayPal Payment Pro error: " . $errormsg;
	}
}elseif($checkoutmode=='update' || $checkoutmode=='savecart' || $checkoutmode=='movetocart'){
	$_SESSION['xsshipping']=NULL; unset($_SESSION['xsshipping']);
	unset($_SESSION['tofreeshipquant']);
	unset($_SESSION['tofreeshipamount']);
	$_SESSION['discounts']=NULL; unset($_SESSION['discounts']);
	$_SESSION['xsstatetax']=NULL; unset($_SESSION['xsstatetax']);
	$_SESSION['xscountrytax']=NULL; unset($_SESSION['xscountrytax']);
	$sSQL="SELECT ordID FROM orders WHERE ordStatus>1 AND ordAuthNumber='' AND " . getordersessionsql();
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		release_stock($rs['ordID']);
		ect_query("UPDATE cart SET cartSessionID='".escape_string(getsessionid())."',cartClientID='" . (@$_SESSION['clientID']!='' ? escape_string($_SESSION['clientID']) : 0) . "' WHERE cartCompleted=0 AND cartOrderID=" . $rs['ordID']) or ect_error();
		ect_query("UPDATE orders SET ordAuthStatus='MODWARNOPEN',ordShipType='MODWARNOPEN' WHERE ordID=" . $rs['ordID']) or ect_error();
	}
	ect_free_result($result);
	$listid='';
	if($checkoutmode=='savecart' && getpost('listid')!='' && is_numeric(getpost('listid')) && @$_SESSION['clientID']!=''){
		$result=ect_query("SELECT listID FROM customerlists WHERE listID='".escape_string(getpost('listid'))."' AND listOwner='" . escape_string($_SESSION['clientID']) . "'") or ect_error();
		if($rs=ect_fetch_assoc($result)) $listid=$rs['listID'];
		ect_free_result($result);
	}
	foreach(@$_POST as $objItem=>$objValue){
		if(substr($objItem,0,5)=='quant' || substr($objItem,0,5)=='delet'){
			$thecartid=(int)substr($objItem, 5);
			$pPrice=0;
			$pID='';
			$sSQL='SELECT cartProdID,'.$WSP."pPrice FROM cart INNER JOIN products ON cart.cartProdId=products.pID WHERE cartID='" . $thecartid . "'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				$pID=trim($rs['cartProdID']);
				$pPrice=$rs['pPrice'];
			}
			ect_free_result($result);
			if($checkoutmode=='movetocart'){
				if(substr($objItem,0,5)=='delet'){
					$sSQL="UPDATE cart SET cartCompleted=0,cartListID=0,cartDateAdded='" . date('Y-m-d H:i:s', time() + ($GLOBALS['dateadjust']*60*60)) . "' WHERE cartCompleted=3 AND cartID='".escape_string($thecartid)."' AND " . getsessionsql();
					if(getget('pli')!='' && is_numeric(getget('pli')) && getget('pla')!=''){
						$sSQL="SELECT listID FROM customerlists WHERE listID='".escape_string(getget('pli'))."' AND listAccess='".escape_string(getget('pla'))."'";
						$result=ect_query($sSQL) or ect_error();
						if($rs=ect_fetch_assoc($result)) $sSQL="UPDATE cart SET cartCompleted=0,cartDateAdded='" . date('Y-m-d H:i:s', time() + ($GLOBALS['dateadjust']*60*60)) . "',cartSessionID='".escape_string(getsessionid())."',cartClientID='" . (@$_SESSION['clientID']!='' ? escape_string($_SESSION['clientID']) : 0) . "' WHERE cartCompleted=3 AND cartID='".escape_string($thecartid)."' AND cartListID=" . $rs['listID']; else $sSQL='';
						ect_free_result($result);
					}
					if($sSQL!='') ect_query($sSQL) or ect_error();
				}
			}elseif($checkoutmode=='savecart' && $pID!=@$giftwrappingid){
				if(substr($objItem,0,5)=='delet')
					ect_query("UPDATE cart SET cartOrderID=0,cartCompleted=3,cartListID='".escape_string($listid!=''?$listid:'0')."',cartDateAdded='" . date('Y-m-d H:i:s', time() + ($GLOBALS['dateadjust']*60*60)) . "' WHERE (cartCompleted=0 OR cartCompleted=3) AND cartID='".escape_string($thecartid)."' AND " . getsessionsql());
			}else{
				if(substr($objItem,0,5)=='quant'){
					if((int)$objValue==0){
						checkdeletecart($thecartid);
					}else{
						$thequant=abs((int)$objValue);
						if($thequant>99999)$thequant=99999;
						if($pID!='' && $pID!=@$giftwrappingid){
							ect_query('UPDATE cart SET cartQuantity=' . $thequant . ",cartDateAdded='" . date('Y-m-d H:i:s', time() + ($GLOBALS['dateadjust']*60*60)) . "' WHERE cartQuantity<>".abs((int)$objValue)." AND (cartCompleted=0 OR cartCompleted=3) AND cartID='" . $thecartid . "'") or ect_error();
						}
					}
				}elseif(substr($objItem,0,5)=='delet'){
					checkdeletecart(substr($objItem, 5));
				}
			}
			if($pID!=$giftcertificateid && $pID!=$donationid) checkpricebreaks($pID,$pPrice);
		}
	}
	updategiftwrap();
}
function additemtocart($ainame,$aiprice){
	global $thesessionid,$theid,$origid,$quantity;
	$cartListID=0;
	$cartCompleted=0;
	if(getpost('listid')==='0' && @$_SESSION['clientID']!=''){
		$cartCompleted=3;
	}elseif(getpost('listid')!='' && is_numeric(getpost('listid')) && @$_SESSION['clientID']!=''){
		$sSQL="SELECT listID FROM customerlists WHERE listOwner='".escape_string($_SESSION['clientID'])."' AND listID='".escape_string(getpost('listid'))."'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){ $cartListID=$rs['listID']; $cartCompleted=3; }
		ect_free_result($result);
	}
	$floodlevel=$GLOBALS['blockmaxcartadds']>0?$GLOBALS['blockmaxcartadds']:1000;
	$sSQL="SELECT COUNT(*) AS cartcnt FROM cart WHERE cartCompleted=0 AND " . getsessionsql();
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result))$cartfloodcontrol=$rs['cartcnt']>=$floodlevel;
	ect_free_result($result);
	if($cartfloodcontrol){
		if($GLOBALS['blockmaxcartadds']>0){
			$sSQL = "SELECT dcid FROM ipblocking WHERE dcip1=" . ip2signedlong($GLOBALS['REMOTE_ADDR']);
			$result=ect_query($sSQL) or ect_error();
			if(ect_num_rows($result)==0)
				ect_query('INSERT INTO ipblocking (dcip1) VALUES (' . ip2signedlong($GLOBALS['REMOTE_ADDR']) . ')') or ect_error();
			$orderid=$ordauthstatus='';
			$sSQL="SELECT ordID,ordAuthStatus FROM orders WHERE ordStatus>1 AND ordAuthNumber='' AND " . getordersessionsql();
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){ $orderid=$rs['ordID']; $ordauthstatus=$rs['ordAuthStatus']; }
			ect_free_result($result);
			if($orderid==''){
				if(TRUE){
					$sSQL="DELETE FROM cart WHERE cartCompleted=0 AND cartOrderID=0 AND " . getsessionsql();
					ect_query($sSQL) or ect_error();
				}else{
					$sSQL="INSERT INTO orders (ordSessionID,ordClientID,ordName,ordDate,ordStatusDate,ordStatus,ordAuthStatus,ordPayProvider,ordIP,ordAuthNumber) VALUES ('" . escape_string($thesessionid) . "'," .
						"'" . (@$_SESSION['clientID']!='' ? escape_string($_SESSION['clientID']) : 0) . "','MAX CART ITEMS','" . date('Y-m-d H:i:s', time() + ($GLOBALS['dateadjust']*60*60)) . "','" . date('Y-m-d H:i:s', time() + ($GLOBALS['dateadjust']*60*60)) . "',2,'MODWARNOPEN',4,'" . escape_string(getipaddress()) . "','')";
					ect_query($sSQL) or ect_error();
					$orderid=ect_insert_id();
					if($orderid!=0){
						$sSQL="UPDATE cart SET cartOrderID=". $orderid . " WHERE cartCompleted=0 AND " . getsessionsql();
						ect_query($sSQL) or ect_error();
					}
				}
			}elseif($ordauthstatus!='MODWARNOPEN'){
				release_stock($orderid);
				ect_query("UPDATE cart SET cartSessionID='".escape_string($thesessionid)."',cartClientID='" . (@$_SESSION['clientID']!='' ? escape_string($_SESSION['clientID']) : 0) . "' WHERE cartCompleted=0 AND cartOrderID=" . $orderid) or ect_error();
				ect_query("UPDATE orders SET ordAuthStatus='MODWARNOPEN',ordShipType='MODWARNOPEN' WHERE ordID=" . $orderid) or ect_error();
			}
		}
		return(0);
	}else{
		$sSQL='INSERT INTO cart (cartSessionID,cartClientID,cartProdID,cartOrigProdID,cartQuantity,cartCompleted,cartProdName,cartProdPrice,cartOrderID,cartDateAdded,cartListID) VALUES (' .
		"'" . escape_string($thesessionid) . "','" . (@$_SESSION['clientID']!='' ? escape_string($_SESSION['clientID']) : 0) . "','" . escape_string($theid) . "','" . ($theid!=$origid?escape_string($origid):'') . "'," . $quantity . ",".$cartCompleted.",'" . escape_string(strip_tags($ainame)) . "','" . round($aiprice,2) . "',0,'" . date('Y-m-d H:i:s', time() + ($GLOBALS['dateadjust']*60*60)) . "',".$cartListID.")";
		ect_query($sSQL) or ect_error();
	}
	return(ect_insert_id());
}
function addoption($opttoadd){
	global $theid,$origid,$cartID,$OWSP,$totalquantity,$thepname,$thepprice,$thepweight,$txtcollen;
	$optvalue=getpost($opttoadd);
	if(! is_numeric($optvalue)) $optvalue='';
	if((substr($opttoadd,0,4)=='optn' || substr($opttoadd,0,4)=='optm') && $optvalue!=''){
		if(substr($opttoadd,0,4)=='optm'){
			$optID=substr($opttoadd, 4);
			$quantity=$optvalue;
			if(is_numeric($optID) && is_numeric($quantity)){
				if($quantity>0){
					$totalquantity+=$quantity;
					if($theid==$origid || @$GLOBALS['addalternateoptions']){
						$sSQL="SELECT optID,".getlangid('optGrpName',16).','.getlangid('optName',32).',' . $OWSP . "optPriceDiff,optWeightDiff,optType,optFlags,optRegExp FROM options LEFT JOIN optiongroup ON options.optGroup=optiongroup.optGrpID WHERE optID='" . escape_string($optID) . "'";
						$result=ect_query($sSQL) or ect_error();
						if($rs=ect_fetch_assoc($result)){
							$sSQL='INSERT INTO cartoptions (coCartID,coOptID,coOptGroup,coCartOption,coPriceDiff,coWeightDiff) VALUES (' . $cartID . ',' . $rs['optID'] . ",'" . escape_string($rs[getlangid('optGrpName',16)]) . "','" . escape_string($rs[getlangid('optName',32)]) . "',";
							if(($rs['optFlags']&1)==0) $sSQL.=(trim_($rs['optRegExp'])!=''?0:$rs['optPriceDiff']) . ','; else $sSQL.=round(($rs['optPriceDiff'] * $thepprice)/100.0, 2) . ',';
							if(($rs['optFlags']&2)==0) $sSQL.=$rs['optWeightDiff'] . ')'; else $sSQL.=multShipWeight($thepweight,$rs['optWeightDiff']) . ')';
							ect_query($sSQL) or ect_error();
						}
						ect_free_result($result);
					}
					checkpricebreaks($theid,$thepprice);
				}
			}
		}elseif(getpost('v' . $opttoadd)==''){
			$sSQL='SELECT optID,'.getlangid('optGrpName',16).','.getlangid('optName',32).',' . $OWSP . "optPriceDiff,optWeightDiff,optType,optFlags,optRegExp FROM options LEFT JOIN optiongroup ON options.optGroup=optiongroup.optGrpID WHERE optID='" . escape_string($optvalue) . "'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				if(!@$GLOBALS['addalternateoptions'] && trim_($rs['optRegExp'])!='' && substr($rs['optRegExp'], 0, 1)!='!'){
					// Do nothing
				}elseif(abs($rs['optType'])!=3&&abs($rs['optType'])!=5){
					$sSQL='INSERT INTO cartoptions (coCartID,coOptID,coOptGroup,coCartOption,coPriceDiff,coWeightDiff) VALUES (' . $cartID . ',' . $rs['optID'] . ",'" . escape_string($rs[getlangid('optGrpName',16)]) . "','" . escape_string($rs[getlangid('optName',32)]) . "',";
					if(($rs['optFlags']&1)==0) $sSQL.=(@$GLOBALS['addalternateoptions'] && trim_($rs['optRegExp']) ? 0 : $rs['optPriceDiff']) . ','; else $sSQL.=round(($rs['optPriceDiff'] * $thepprice)/100.0, 2) . ',';
					if(($rs['optFlags']&2)==0) $sSQL.=$rs['optWeightDiff'] . ')'; else $sSQL.=multShipWeight($thepweight,$rs['optWeightDiff']) . ')';
				}else
					$sSQL='INSERT INTO cartoptions (coCartID,coOptID,coOptGroup,coCartOption,coPriceDiff,coWeightDiff) VALUES (' . $cartID . ',' . $rs['optID'] . ",'" . escape_string($rs[getlangid('optGrpName',16)]) . "','',0,0)";
				ect_query($sSQL) or ect_error();
			}
			ect_free_result($result);
		}else{
			$sSQL='SELECT optID,'.getlangid('optGrpName',16).','.getlangid('optName',32).",optTxtCharge,optMultiply,optAcceptChars,optType FROM options LEFT JOIN optiongroup ON options.optGroup=optiongroup.optGrpID WHERE optID='" . escape_string($optvalue) . "'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				$theopttoadd=getpost('v' . $opttoadd);
				$optPriceDiff=($rs['optTxtCharge']<0&&$theopttoadd!=''?abs($rs['optTxtCharge']):$rs['optTxtCharge']*strlen($theopttoadd));
				$optmultiply=0;
				if($rs['optMultiply']!=0&&abs($rs['optType'])==3){
					if(is_numeric($theopttoadd)) $optmultiply=(float)$theopttoadd; else $theopttoadd='#NAN';
				}
				$sSQL='INSERT INTO cartoptions (coCartID,coOptID,coOptGroup,coCartOption,coPriceDiff,coWeightDiff,coMultiply) VALUES (' . $cartID . ',' . $rs['optID'] . ",'" . escape_string($rs[getlangid('optGrpName',16)]) . "','" . escape_string(substr($theopttoadd,0,$txtcollen)) . "',".$optPriceDiff.',0,' . (abs($rs['optType'])==3?$rs['optMultiply']:0) . ')';
				ect_query($sSQL) or ect_error();
			}
			ect_free_result($result);
		}
	}
}
function addproduct($theid){
	global $thepname,$thepprice,$thepweight,$cartID,$objItem,$optarray,$numoptions,$WSP,$addedprods,$numaddedprods,$quantity;
	$idexists=1;
	$sSQL='SELECT '.getlangid('pName',1).','.$WSP.'pPrice,pWeight FROM products WHERE '.(!$GLOBALS['useStockManagement']?'(pSell<>0 OR pBackOrder<>0) AND':'')." pID='" . escape_string($theid) . "'";
	$result2=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result2)){
		$thepname=$rs[getlangid('pName',1)];
		$thepprice=round($rs['pPrice'],2);
		$thepweight=$rs['pWeight'];
	}else{
		$idexists=0;
		$thepname="Product ID Error";
		$thepprice=0;
		$thepweight=0;
	}
	ect_free_result($result2);
	$addedprods[$numaddedprods][0]=$theid;
	$addedprods[$numaddedprods][1]=$thepname;
	$addedprods[$numaddedprods][2]=$quantity;
	$addedprods[$numaddedprods][3]=$thepprice;
	$addedprods[$numaddedprods][4]=$idexists;
	$addedprods[$numaddedprods][5]='';
	if($idexists){
		$cartID=additemtocart($thepname,$thepprice);
		if($cartID==0) return;
		for($index=0; $index<$numoptions; $index++){
			if($optarray[$index]=='multioption') addoption($objItem); else addoption($optarray[$index]);
		}
		$addedprods[$numaddedprods][5]=$cartID;
	}
	$numaddedprods++;
}
if($checkoutmode=='add'){
	$origid=$theid;
	$optarray=[];
	$optgrouparray=[];
	$numoptgrouparray=0;
	$addedprods=[];
	$addtocarterror=FALSE;
	$addtocarterrortxt='';
	$thesessionid=getsessionid();
	if(@$_SESSION['clientID']!='' && getpost('listid')!='' && is_numeric(getpost('listid'))) $listid=getpost('listid'); else $listid='';
	$_SESSION['xsshipping']=NULL; unset($_SESSION['xsshipping']);
	unset($_SESSION['tofreeshipquant']);
	unset($_SESSION['tofreeshipamount']);
	$_SESSION['discounts']=NULL; unset($_SESSION['discounts']);
	$_SESSION['xsstatetax']=NULL; unset($_SESSION['xsstatetax']);
	$_SESSION['xscountrytax']=NULL; unset($_SESSION['xscountrytax']);
	$sSQL="SELECT ordID FROM orders WHERE ordStatus>1 AND ordAuthNumber='' AND " . getordersessionsql();
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		release_stock($rs['ordID']);
		ect_query("UPDATE cart SET cartSessionID='".escape_string(getsessionid())."',cartClientID='" . (@$_SESSION['clientID']!='' ? escape_string($_SESSION['clientID']) : 0) . "' WHERE cartCompleted=0 AND cartOrderID=" . $rs['ordID']) or ect_error();
		ect_query("UPDATE orders SET ordAuthStatus='MODWARNOPEN',ordShipType='MODWARNOPEN' WHERE ordID=" . $rs['ordID']) or ect_error();
	}
	ect_free_result($result);
	if(! is_numeric(getpost('quant'))) $quantity=1; else $quantity=abs((int)getpost('quant'));
	if($quantity<1)$quantity=1;
	if($quantity>99999)$quantity=99999;
	$hasmultioption=FALSE;
	$origquantity=$quantity;
	$altids='';
	$numoptions=0;
	$numaddedprods=0;
	foreach(@$_POST as $objItem=>$objValue){ // Check if the product id is modified
		if(substr($objItem,0,4)=='optn' && is_numeric($objValue)){
			$doaddoption=FALSE;
			$sSQL="SELECT optRegExp,optGroup,optDependants FROM options WHERE optID='" . escape_string($objValue) . "'";
			$result2=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result2)){
				$theexp=trim_($rs['optRegExp']);
				$optgrouparray[$numoptgrouparray][0]=$rs['optGroup'];
				$optgrouparray[$numoptgrouparray][1]=FALSE;
				$optgrouparray[$numoptgrouparray][2]=$rs['optDependants'];
				$numoptgrouparray++;
				if($theexp!='' && substr($theexp, 0, 1)!='!'){
					$theexp=str_replace('%s', $theid, $theexp);
					$altids.=':'.$objValue.':';
					if(strpos($theexp,' ')!==FALSE){ // Search and replace
						$exparr=explode(' ', $theexp, 2);
						$theid=str_replace($exparr[0], $exparr[1], $theid);
					}else
						$theid=$theexp;
					if(@$GLOBALS['addalternateoptions']) $doaddoption=TRUE;
				}else
					$doaddoption=TRUE;
				if($doaddoption){
					$optarray[$numoptions]=$objItem;
					$numoptions++;
				}
			}
			ect_free_result($result2);
		}elseif(substr($objItem,0,4)=='optm' && is_numeric($objValue)){
			if(is_numeric(substr($objItem, 4))){
				if(! $hasmultioption){
					$optarray[$numoptions]='multioption';
					$numoptions++;
				}
				$hasmultioption=TRUE;
			}
		}
	}
	
	if(@$GLOBALS['addtocartchecks']){
		$sSQL="SELECT poOptionGroup,optType,optGrpName FROM prodoptions INNER JOIN optiongroup ON prodoptions.poOptionGroup=optiongroup.optGrpID WHERE poProdID='" . escape_string($origid) . "'";
		$result2=ect_query($sSQL) or ect_error();
		while($rs=ect_fetch_assoc($result2)){
			$hasmatchingoption=FALSE;
			//print 'option: ' . $rs['poOptionGroup'] . " : " . $rs['optGrpName'] . "<br>";
			for($index=0;$index<$numoptgrouparray;$index++){
				if($optgrouparray[$index][0]==$rs['poOptionGroup']){
					$hasmatchingoption=TRUE;
					$optgrouparray[$index][1]=TRUE;
				}
			}
			if(!$hasmatchingoption&&$rs['optType']>0&&!($hasmultioption&&$rs['optType']==4)){
				$addtocarterror=TRUE;
				$addtocarterrortxt='The product could not be added because of a missing product option.';
				//print 'missing option<br>';
			}
		}
		ect_free_result($result2);
		for($index=0;$index<$numoptgrouparray;$index++){
			//print 'optgrouparray: ' . $optgrouparray[$index][0] . "<br>";
			if(!$optgrouparray[$index][1]){
				$isdependantoption=FALSE;
				for($index2=0;$index2<$numoptgrouparray;$index2++){
					if(strpos(','.$optgrouparray[$index2][2].',',','.$optgrouparray[$index][0].',')!==FALSE)
						$isdependantoption=TRUE;
				}
				if(!$isdependantoption){
					$addtocarterror=TRUE;
					$addtocarterrortxt='The product could not be added because of a mismatched product option.';
					//print 'mismatch option<br>';
				}
			}
		}
		if(getpost('ajaxadd')!='true'&&!@$GLOBALS['usehardaddtocart']){
			$addtocarterror=TRUE;
			$addtocarterrortxt='Hard add to cart is not allowed.';
		}
	}
	
	if($addtocarterror){
		if(@$GLOBALS['autoenabletrace']){
			$_SESSION['sqltrace']=TRUE;
			if(!@$_SESSION['parametertrace']){
				$_SESSION['parametertrace']=TRUE;
				debugparametertrace();
			}
		}
		if(getpost('ajaxadd')=='true')
			print 'error&' . jsurlencode(jsenc($addtocarterrortxt));
		else
			print '<div class="scerror ectwarning">' . $addtocarterrortxt . '</div>';
	}else{
		if($hasmultioption){
			foreach(@$_POST as $objItem=>$objValue){
				if(substr($objItem,0,4)=='optm' && is_numeric($objValue)){
					if(is_numeric(substr($objItem, 4))){
						$quantity=abs((int)$objValue);
						if($quantity>99999)$quantity=99999;
						$theid=$origid;
						$sSQL="SELECT optRegExp FROM options WHERE optID='" . escape_string(substr($objItem, 4)) . "'";
						$result2=ect_query($sSQL) or ect_error();
						if($rs=ect_fetch_assoc($result2)) $theexp=trim($rs['optRegExp']); else $theexp='';
						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;
						}
						ect_free_result($result2);
						addproduct($theid);
					}
				}
			}
		}else
			addproduct($theid);
		// Check duplicates
		$sSQL="SELECT cartID,cartProdID,cartQuantity FROM cart WHERE cartCompleted=".($listid==''?0:3)." AND " . getsessionsql() . ($listid==''?'':" AND cartListID='".$listid."'") . ' ORDER BY cartID';
		$result=ect_query($sSQL) or ect_error();
		while($rs=ect_fetch_assoc($result)){
			$hasoptions=FALSE;
			$thecartid='';
			$sSQL="SELECT cartID,cartQuantity FROM cart WHERE cartID>" . $rs['cartID'] . " AND cartCompleted=".($listid==''?0:3)." AND " . getsessionsql() . ($listid==''?'':" AND cartListID='".$listid."'") . " AND cartProdID='" . escape_string($rs['cartProdID']) . "'";
			$result2=ect_query($sSQL) or ect_error();
			while($rs2=ect_fetch_assoc($result2)){
				$thecartid=$rs2['cartID'];
				$thequant=$rs2['cartQuantity'];
				$hasoptions=TRUE;
				if($thecartid!=''){ // check options
					$optarr1cnt=0; $optarr2cnt=0;
					$sSQL="SELECT coOptID,coCartOption FROM cartoptions WHERE coCartID=" . $rs['cartID'];
					$result3=ect_query($sSQL) or ect_error();
					while($rs3=ect_fetch_assoc($result3))
						$optarr1[$optarr1cnt++]=$rs3;
					ect_free_result($result3);
					$sSQL="SELECT coOptID,coCartOption FROM cartoptions WHERE coCartID=" . $thecartid;
					$result3=ect_query($sSQL) or ect_error();
					while($rs3=ect_fetch_assoc($result3))
						$optarr2[$optarr2cnt++]=$rs3;
					ect_free_result($result3);
					if($optarr1cnt!=$optarr2cnt) $hasoptions=FALSE;
					if($optarr1cnt>0 && $optarr2cnt>0){
						if($hasoptions){
							for($index2=0; $index2 < $optarr1cnt; $index2++){
								$hasthisoption=FALSE;
								for($index3=0; $index3 < $optarr2cnt; $index3++){
									if($optarr1[$index2]['coOptID']==$optarr2[$index3]['coOptID'] && $optarr1[$index2]['coCartOption']==$optarr2[$index3]['coCartOption']) $hasthisoption=TRUE;
								}
								if(! $hasthisoption) $hasoptions=FALSE;
							}
						}
					}
				}
				if($hasoptions) break;
			}
			ect_free_result($result2);
			if($thecartid!='' && $hasoptions){
				ect_query("DELETE FROM cartoptions WHERE coCartID=".$thecartid) or ect_error();
				ect_query("DELETE FROM cart WHERE cartID=".$thecartid) or ect_error();
				ect_query("UPDATE cart SET cartQuantity=cartQuantity+".$thequant." WHERE cartID=".$rs['cartID']) or ect_error();
				for($index=0; $index<$numaddedprods; $index++){
					if($addedprods[$index][5]==$thecartid) $addedprods[$index][5]=$rs['cartID'];
				}
			}
		}
		ect_free_result($result);
		for($index=0; $index<$numaddedprods; $index++){
			if($addedprods[$index][4]) checkpricebreaks($theid,$thepprice); else{ $actionaftercart=0; $cartrefreshseconds=3; }
		}
		$failedprods=0;
		do_stock_check(TRUE,$backorder,$stockwarning);
		$scidnoexistflag=''; $scbackorderflag=$scinstockflag=0;
		for($index2=0; $index2<$numaddedprods; $index2++){
			if($addedprods[$index2][4]==0){ $scidnoexistflag=$addedprods[$index2][0]; $failedprods++; }
			if($addedprods[$index2][4]==2) $scinstockflag=1;
			if($addedprods[$index2][4]==3) $scbackorderflag=1;
		}
		$sSQL='SELECT cartID,cartProdPrice,cartQuantity,pExemptions,pTax FROM cart INNER JOIN products ON cart.cartProdId=products.pID WHERE cartCompleted=0 AND ' . getsessionsql();
		$result=ect_query($sSQL) or ect_error();
		$sctotquant=$totalgoods=0;
		while($rs=ect_fetch_assoc($result)){
			$optPriceDiff=0;
			$pexemptions=$rs['pExemptions'];
			$thetax=$homeCountryTaxRate;
			if(@$GLOBALS['perproducttaxrate'] && ! is_null($rs['pTax'])) $thetax=$rs['pTax'];
			$sSQL='SELECT SUM(coPriceDiff) AS sumDiff FROM cartoptions WHERE coCartID='.$rs['cartID'];
			$result2=ect_query($sSQL) or ect_error();
			$rs2=ect_fetch_assoc($result2);
			if(! is_null($rs2['sumDiff'])) $optPriceDiff=$rs2['sumDiff'];
			ect_free_result($result2);
			$subtot=(($rs['cartProdPrice']+$optPriceDiff)*$rs['cartQuantity']);
			$sctotquant+=$rs['cartQuantity'];
			$totalgoods+=$subtot;
			if(@$GLOBALS['perproducttaxrate']){
				if(($pexemptions & 2)!=2) $countryTax+=($subtot*$thetax/100.0);
			}else{
				if(($pexemptions & 2)==2) $countrytaxfree+=$subtot;
			}
			for($index=0; $index<$numaddedprods; $index++){
				if($addedprods[$index][5]==$rs['cartID']) $addedprods[$index][3]=$rs['cartProdPrice'];
			}
		}
		ect_free_result($result);
		calculatediscounts($totalgoods,FALSE,$rgcpncode);
		if($totaldiscounts>$totalgoods) $totaldiscounts=$totalgoods;
		if(@$GLOBALS['showtaxinclusive']!=0) calculatetaxandhandling(); else $countryTax=0;
		if(getpost('ajaxadd')=='true'){
			ob_clean();
			print jsurlencode(jsenc($scidnoexistflag)) . '&' . $scinstockflag . '&' . $scbackorderflag . '&' . ($numaddedprods-$failedprods);
			print '&'.$sctotquant.'&'.jsurlencode(jsenc(FormatEuroCurrency(@$GLOBALS['nopriceanywhere']?0:($totalgoods-$totaldiscounts)+$countryTax))).'&';
			$productimage='';
			$sSQL="SELECT imageSrc FROM productimages WHERE imageType=0 AND imageProduct='".escape_string($theid)."' ORDER BY imageNumber LIMIT 0,1";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)) $productimage=$rs['imageSrc'];
			ect_free_result($result);
			if($productimage==''&&$origid!=$theid){
				$sSQL="SELECT imageSrc FROM productimages WHERE imageType=0 AND imageProduct='".escape_string($origid)."' ORDER BY imageNumber LIMIT 0,1";
				$result=ect_query($sSQL) or ect_error();
				if($rs=ect_fetch_assoc($result)) $productimage=$rs['imageSrc'];
				ect_free_result($result);
			}
			print jsurlencode(jsenc($productimage));
			for($index=0; $index<$numaddedprods; $index++){
				if($addedprods[$index][5]!=''){
					$pexemptions=$totoptdiff=0;
					$thetax=$homeCountryTaxRate;
					$sSQL="SELECT pExemptions,pTax FROM products WHERE pID='".escape_string($theid)."'";
					$result=ect_query($sSQL) or ect_error();
					if($rs=ect_fetch_assoc($result)){
						$pexemptions=$rs['pExemptions'];
						if(@$GLOBALS['perproducttaxrate'] && ! is_null($rs['pTax'])) $thetax=$rs['pTax'];
					}
					ect_free_result($result);
					$sSQL='SELECT coOptGroup,coCartOption,coPriceDiff FROM cartoptions WHERE coCartID=' . $addedprods[$index][5] . ' ORDER BY coID';
					$result=ect_query($sSQL) or ect_error();
					if(($numitems=ect_num_rows($result))>0){
						$optresult='&'.$numitems;
						while($rs=ect_fetch_assoc($result)){
							$totoptdiff+=$rs['coPriceDiff'];
							$optresult.='&'.jsurlencode(jsenc($rs['coOptGroup'])).'&'.jsurlencode(jsenc($rs['coCartOption']));
						}
					}else
						$optresult='&0';
					ect_free_result($result);
					$totitemcost=$addedprods[$index][3]+$totoptdiff;
					for($index2=0; $index2<=4; $index2++){
						print '&';
						if($index2==3) print jsurlencode(jsenc(FormatEuroCurrency(@$GLOBALS['nopriceanywhere']?0:$totitemcost))); else print jsurlencode(jsenc($addedprods[$index][$index2]));
					}
					print $optresult;
				}
			}
			print '&'.jsurlencode(jsenc(FormatEuroCurrency(@$GLOBALS['nopriceanywhere']?0:$countryTax))).'&'.jsurlencode(jsenc(FormatEuroCurrency(@$GLOBALS['nopriceanywhere']?0:$totaldiscounts)));
			if($totaldiscounts==0){ $_SESSION['discounts']=NULL; unset($_SESSION['discounts']); print '&0&';} else{ $_SESSION['discounts']=$totaldiscounts; print '&1&';}
			$sSQL='SELECT cartID,cartProdID,cartProdName,cartProdPrice,cartQuantity FROM cart WHERE cartCompleted=0 AND ' . getsessionsql() . ' ORDER BY cartID';
			$result=ect_query($sSQL) or ect_error();
			while($rs=ect_fetch_assoc($result))
				print jsurlencode(jsenc('<div class="minicartcnt">'.$rs['cartQuantity'].' '.$rs['cartProdName'].'</div>'));
			ect_free_result($result);
		}else{
			print '<div style="text-align:center;padding:40px">';
			do_stock_check(FALSE,$backorder,$stockwarning);
			if($stockwarning) $actionaftercart=4;
			if(! @isset($cartrefreshseconds)) $cartrefreshseconds=3;
			if($listid!='') $listidurl='&mode=sc' . ($listid!='0'?'&lid='.$listid:''); else $listidurl='';
			if($thefrompage!='' && @$actionaftercart==3){
				if($cartrefreshseconds==0 && ob_get_length()!==FALSE)
					header('Location: ' . $thefrompage);
				else
					print '<meta http-equiv="Refresh" content="'.$cartrefreshseconds.'; URL=' . $thefrompage . '">';
			}elseif(@$actionaftercart==4 || $cartrefreshseconds==0){
				$urllink='?rp='.urlencode($thefrompage);
				if($listid!='' && @$_SESSION['clientID']!='')
					$urllink.=$listidurl;
				elseif($stockwarning)
					$urllink.='&mode=add';
				if(ob_get_length()===FALSE) print '<meta http-equiv="Refresh" content="0; URL=cart'.$GLOBALS['extension'].$urllink.'">'; else header('Location: '.$storeurl.'cart'.$GLOBALS['extension'].$urllink);
			}else
				print '<meta http-equiv="Refresh" content="'.$cartrefreshseconds.'; URL=cart'.$GLOBALS['extension'].'?rp='.urlencode($thefrompage).$listidurl.'">';
			print '<div class="hardcarttable" style="display:table;padding:10px;width:auto;margin-left:auto;margin-right:auto;border:1px solid grey">';
			if($stockwarning) print '<div class="hardcartstockwarn" style="text-align:center">' . $GLOBALS['xxInsMul'] . '</div>';
			for($index=0; $index<$numaddedprods; $index++){
				print '<div class="hardcartaddproductline" style="display:table-row"><div class="hardcartaddproductquant" style="display:table-cell;text-align:right;padding:6px">' . ($addedprods[$index][4]?$addedprods[$index][2]:'X') . '</div><div class="hardcartaddproduct" style="display:table-cell;text-align:left;padding:6px;">' . ($addedprods[$index][4] ? $addedprods[$index][1] . ' ' . $GLOBALS['xxAddOrd'] : '<span class="ectwarning">The product id <span style="color:#000000">' . htmlspecials($addedprods[$index][0]) . '</span> does not exist in the product database.</span></span>') . '</div></div>';
			}
			print '</div>';
			print '<div class="hardcartpleasewait" style="padding:10px;margin:50px 10px">' . $GLOBALS['xxPlsWait'] . ' <a class="ectlink" href="';
			if($thefrompage!='' && @$actionaftercart==3) print $thefrompage; else print 'cart'.$GLOBALS['extension'].'?rp='.urlencode($thefrompage).$listidurl;
			print '"><strong>' . $GLOBALS['xxClkHere'] . '</strong></a>.</div>';
			print '</div>';
		}
	}
}elseif($checkoutmode=='go' || $paypalexpress || $amazonpayment){
	getadminshippingparams();
	function setcheckouterr($coerrmsg){
		global $success,$checkoutmode,$returntocustomerdetails,$errormsg;
		$success=FALSE; $checkoutmode='checkout'; $returntocustomerdetails=TRUE; $errormsg.='<div class="checkoutwarning">' . $coerrmsg . '</div>';
		return(TRUE);
	}
	if(getget('action')=='termpp'&&getget('paymentID')!=''){
		if(getpayprovdetx(27,$data1,$data2,$data3,$data4,$data5,$data6,$ppflag1,$ppflag2,$ppflag3,$ppbits,$demomode,$ppmethod)){
			if($access_token=paypalaccesstoken($data1,$data2,$demomode,$data6,$errormsg)){
				$GLOBALS['xmlfnheaders']=array("Content-Type: application/json","PayPal-Partner-Attribution-Id: EcommerceTemplates_Ecom_PPCP","Authorization: Bearer " . $access_token);
				if(callcurlfunction('https://api-m.' . ($demomode?'sandbox.':'') . 'paypal.com/v2/checkout/orders/'.getget('paymentID'),'',$jres,'',$errormsg,FALSE)){
					$ordPayProvider=27;
					$paypalcheckoutexpress=TRUE;
					$jsarray=json_decode($jres);
					$ordEmail=$ordEmail2=@$jsarray->{'payer'}->{'email_address'};
					$ordName=@$jsarray->{'purchase_units'}[0]->{'shipping'}->{'name'}->{'full_name'};
					$ordLastName='';
					if(!@$jsarray->{'purchase_units'}[0]->{'shipping'}){
						$ordAddress=$ordAddress2=$ordCity=$ordState=$ordZip='DIGITAL';
						$ordCountryCode=@$jsarray->{'payer'}->{'address'}->{'country_code'};
						$ordName=trim_(@$jsarray->{'payer'}->{'name'}->{'given_name'} . ' ' . @$jsarray->{'payer'}->{'name'}->{'surname'});
					}else{
						$ordAddress=@$jsarray->{'purchase_units'}[0]->{'shipping'}->{'address'}->{'address_line_1'};
						$ordAddress2=@$jsarray->{'purchase_units'}[0]->{'shipping'}->{'address'}->{'address_line_2'};
						$ordCity=@$jsarray->{'purchase_units'}[0]->{'shipping'}->{'address'}->{'admin_area_2'};
						$ordState=@$jsarray->{'purchase_units'}[0]->{'shipping'}->{'address'}->{'admin_area_1'};
						$ordZip=@$jsarray->{'purchase_units'}[0]->{'shipping'}->{'address'}->{'postal_code'};
						$ordCountryCode=@$jsarray->{'purchase_units'}[0]->{'shipping'}->{'address'}->{'country_code'};
					}
					if(@$GLOBALS['usefirstlastname']) splitname($ordName,$ordName,$ordLastName);
					$sSQL="SELECT countryName FROM countries WHERE countryEnabled=1 AND countryCode='" . escape_string($ordCountryCode) . "'";
					if($ordCountryCode=='GB') $sSQL.=' AND countryID=' . (strtoupper(substr($ordState,0,7))=='COUNTY ' ? '142' : '201');
					$result=ect_query($sSQL) or ect_error();
					if($rs=ect_fetch_assoc($result)) $ordCountry=$rs['countryName']; else $GLOBALS['avalarastate']=0;
					$ordPhone='xxx-xxx-xxxx';
					$ordExtra1='';
					$ordExtra2='';
					$GLOBALS['xxCOTxt3']=$GLOBALS['xxClkCom'];
				}else{
					// handle error
				}
			}
		}
	}elseif(getpost('orderid')!='' && is_numeric(getpost('orderid')) && getpost('sessionid')!=''){
		retrieveorderdetails(getpost('orderid'), getpost('sessionid'));
	}elseif(! ($paypalexpress || $amazonpayment)){
		if(@$GLOBALS['enableclientlogin'] && @$_SESSION['clientID']!=''){
			$sSQL="SELECT clEmail FROM customerlogin WHERE clEmail<>'' AND clID='" . escape_string($_SESSION['clientID']) . "'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)) $ordEmail=trim($rs['clEmail']); else $ordEmail=cleanupemail(getpost('email'));
			ect_free_result($result);
		}else{
			$ordEmail=cleanupemail(getpost('email'));
			$ordEmail2=cleanupemail(getpost('email2'));
		}
		if(@$GLOBALS['enableclientlogin'] && is_numeric(getpost('addressid')) && getpost('addaddress')=='' && @$_SESSION['clientID']!=''){
			$sSQL="SELECT addName,addLastName,addAddress,addAddress2,addCity,addState,addZip,addCountry,addPhone,addExtra1,addExtra2 FROM address WHERE addCustID='" . escape_string($_SESSION['clientID']) . "' AND addID='" . escape_string(getpost('addressid')) . "'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				$ordName=$rs['addName'];
				$ordLastName=$rs['addLastName'];
				$ordAddress=$rs['addAddress'];
				$ordAddress2=$rs['addAddress2'];
				$ordCity=$rs['addCity'];
				$ordState=$rs['addState'];
				$ordZip=$rs['addZip'];
				$ordCountry=$rs['addCountry'];
				$ordPhone=str_replace('xxx-xxx-xxxx','',$rs['addPhone']);
				$ordExtra1=$rs['addExtra1'];
				$ordExtra2=$rs['addExtra2'];
				ect_query("UPDATE address SET addIsDefault=0 WHERE addCustID='" . escape_string($_SESSION['clientID']) . "'") or ect_error();
				ect_query("UPDATE address SET addIsDefault=1 WHERE addCustID='" . escape_string($_SESSION['clientID']) . "' AND addID='" . escape_string(getpost('addressid')) . "'") or ect_error();
			}
			ect_free_result($result);
		}else{
			$ordName=substr(strip_tags(getpost('ordname')),0,100);
			$ordLastName=substr(strip_tags(getpost('lastname')),0,100);
			$ordAddress=substr(strip_tags(getpost('address')),0,150);
			$ordAddress2=substr(strip_tags(getpost('address2')),0,150);
			$ordCity=substr(strip_tags(getpost('city')),0,75);
			$ordState=getstatefromid(substr(strip_tags(getpost('state'.(getpost('state')==''?'2':''))),0,75));
			$ordZip=substr(strip_tags(getpost('zip')),0,50);
			$ordCountry=substr(getcountryfromid(getpost('country')),0,50);
			$ordPhone=str_replace('xxx-xxx-xxxx','',substr(strip_tags(getpost('phone')),0,50));
			$ordExtra1=substr(strip_tags(getpost('ordextra1')),0,255);
			$ordExtra2=substr(strip_tags(getpost('ordextra2')),0,255);
		}
		if(getpost('allowemail')=='ON') addtomailinglist($ordEmail,trim($ordName.' '.$ordLastName));
		if(@$GLOBALS['enableclientlogin'] && is_numeric(getpost('saddressid')) && getpost('saddaddress')=='' && @$_SESSION['clientID']!=''){
			$sSQL="SELECT addName,addLastName,addAddress,addAddress2,addCity,addState,addZip,addCountry,addPhone,addExtra1,addExtra2 FROM address WHERE addCustID='" . escape_string($_SESSION['clientID']) . "' AND addID='" . escape_string(getpost('saddressid')) . "'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				$ordShipName=$rs['addName'];
				$ordShipLastName=$rs['addLastName'];
				$ordShipAddress=$rs['addAddress'];
				$ordShipAddress2=$rs['addAddress2'];
				$ordShipCity=$rs['addCity'];
				$ordShipState=$rs['addState'];
				$ordShipZip=$rs['addZip'];
				$ordShipCountry=$rs['addCountry'];
				$ordShipPhone=str_replace('xxx-xxx-xxxx','',$rs['addPhone']);
				$ordShipExtra1=$rs['addExtra1'];
				$ordShipExtra2=$rs['addExtra2'];
				if((trim($ordShipName . $ordShipLastName)=='' || $ordShipAddress=='' || $ordShipCity=='' || $ordShipZip=='' || $ordShipPhone=='') && trim($ordShipName . $ordShipLastName . $ordShipAddress . $ordShipCity . $ordShipState . $ordShipZip . $ordShipPhone)!='')
					$errordshipaddress=setcheckouterr('If you enter a separate ship address you must enter all address details.');
			}
			ect_free_result($result);
		}else{
			if(getpost('shipdiff')=='1' || (getpost('addressarray')=='1' && (getpost('saddaddress')=='add' || getpost('saddaddress')=='edit'))){
				$ordShipName=substr(strip_tags(getpost('sordname')),0,100);
				$ordShipLastName=substr(strip_tags(getpost('slastname')),0,100);
				$ordShipAddress=substr(strip_tags(getpost('saddress')),0,150);
				$ordShipAddress2=substr(strip_tags(getpost('saddress2')),0,150);
				$ordShipCity=substr(strip_tags(getpost('scity')),0,75);
				$ordShipState=getstatefromid(substr(strip_tags(getpost('sstate'.(getpost('sstate')==''?'2':''))),0,75));
				$ordShipZip=substr(strip_tags(getpost('szip')),0,50);
				$ordShipCountry=substr(getcountryfromid(getpost('scountry')),0,50);
				$ordShipPhone=str_replace('xxx-xxx-xxxx','',substr(strip_tags(getpost('sphone')),0,50));
				$ordShipExtra1=substr(strip_tags(getpost('ordsextra1')),0,255);
				$ordShipExtra2=substr(strip_tags(getpost('ordsextra2')),0,255);
				if((trim($ordShipName . $ordShipLastName)=='' || $ordShipAddress=='' || $ordShipCity=='' || $ordShipZip=='' || $ordShipPhone=='') && trim($ordShipName . $ordShipLastName . $ordShipAddress . $ordShipCity . $ordShipState . $ordShipZip . $ordShipPhone)!='')
					$errordshipaddress=setcheckouterr('If you enter a separate ship address you must enter all address details.');
			}
		}
		$ordZip=strtoupper($ordZip);
		$ordShipZip=strtoupper($ordShipZip);
		if(!@$GLOBALS['usefirstlastname']){
			$ordName=trim($ordName.' '.$ordLastName); $ordLastName='';
			$ordShipName=trim($ordShipName.' '.$ordShipLastName); $ordShipLastName='';
		}
		if(@$_SESSION['clientID']!=''){
			if(trim($ordName . $ordLastName)!='' && $ordAddress!='' && $ordCity!='' && $ordState!='' && $ordCountry!='' && $ordZip!='' && $ordPhone!=''){
				if(getpost('addaddress')=='add'){
					$sSQL="SELECT addID FROM address WHERE addCustID='" . escape_string(@$_SESSION['clientID']) . "' AND addName='".escape_string($ordName)."' AND addLastName='".escape_string($ordLastName)."' AND addAddress='".escape_string($ordAddress)."' AND addAddress2='".escape_string($ordAddress2)."' AND addCity='".escape_string($ordCity)."' AND addState='".escape_string($ordState)."' AND addZip='".escape_string($ordZip)."' AND addCountry='".escape_string($ordCountry)."' AND addPhone='".escape_string($ordPhone)."' AND addExtra1='".escape_string($ordExtra1)."' AND addExtra2='".escape_string($ordExtra2)."'";
					$result=ect_query($sSQL) or ect_error();
					$hasaddress=(ect_num_rows($result)>0);
					ect_free_result($result);
					$sSQL="INSERT INTO address (addCustID,addIsDefault,addName,addLastName,addAddress,addAddress2,addCity,addState,addZip,addCountry,addPhone,addExtra1,addExtra2) VALUES ('" . escape_string($_SESSION['clientID']) . "',0,'".escape_string($ordName)."','".escape_string($ordLastName)."','".escape_string($ordAddress)."','".escape_string($ordAddress2)."','".escape_string($ordCity)."','".escape_string($ordState)."','".escape_string($ordZip)."','".escape_string($ordCountry)."','".escape_string($ordPhone)."','".escape_string($ordExtra1)."','".escape_string($ordExtra2)."')";
					if(! $hasaddress) ect_query($sSQL) or ect_error();
				}elseif(getpost('addaddress')=='edit'){
					$sSQL="UPDATE address SET addName='".escape_string($ordName)."',addLastName='".escape_string($ordLastName)."',addAddress='".escape_string($ordAddress)."',addAddress2='".escape_string($ordAddress2)."',addCity='".escape_string($ordCity)."',addState='".escape_string($ordState)."',addZip='".escape_string($ordZip)."',addCountry='".escape_string($ordCountry)."',addPhone='".escape_string($ordPhone)."',addExtra1='".escape_string($ordExtra1)."',addExtra2='".escape_string($ordExtra2)."' WHERE addCustID='" . escape_string(@$_SESSION['clientID']) . "' AND addID='" . escape_string(getpost('addressid')) . "'";
					ect_query($sSQL) or ect_error();
				}
			}
			if(trim($ordShipName . $ordShipLastName)!='' && $ordShipAddress!='' && $ordShipCity!='' && $ordShipState!='' && $ordShipCountry!='' && $ordShipZip!=''){
				if(getpost('saddaddress')=='add'){
					$sSQL="SELECT addID FROM address WHERE addCustID='" . escape_string(@$_SESSION['clientID']) . "' AND addName='".escape_string($ordShipName)."' AND addLastName='".escape_string($ordShipLastName)."' AND addAddress='".escape_string($ordShipAddress)."' AND addAddress2='".escape_string($ordShipAddress2)."' AND addCity='".escape_string($ordShipCity)."' AND addState='".escape_string($ordShipState)."' AND addZip='".escape_string($ordShipZip)."' AND addCountry='".escape_string($ordShipCountry)."' AND addPhone='".escape_string($ordShipPhone)."' AND addExtra1='".escape_string($ordShipExtra1)."' AND addExtra2='".escape_string($ordShipExtra2)."'";
					$result=ect_query($sSQL) or ect_error();
					$hasaddress=(ect_num_rows($result)>0);
					ect_free_result($result);
					$sSQL="INSERT INTO address (addCustID,addIsDefault,addName,addLastName,addAddress,addAddress2,addCity,addState,addZip,addCountry,addPhone,addExtra1,addExtra2) VALUES ('" . escape_string($_SESSION['clientID']) . "',0,'".escape_string($ordShipName)."','".escape_string($ordShipLastName)."','".escape_string($ordShipAddress)."','".escape_string($ordShipAddress2)."','".escape_string($ordShipCity)."','".escape_string($ordShipState)."','".escape_string($ordShipZip)."','".escape_string($ordShipCountry)."','".escape_string($ordShipPhone)."','".escape_string($ordShipExtra1)."','".escape_string($ordShipExtra2)."')";
					if(! $hasaddress) ect_query($sSQL) or ect_error();
				}elseif(getpost('saddaddress')=='edit'){
					$sSQL="UPDATE address SET addName='".escape_string($ordShipName)."',addLastName='".escape_string($ordShipLastName)."',addAddress='".escape_string($ordShipAddress)."',addAddress2='".escape_string($ordShipAddress2)."',addCity='".escape_string($ordShipCity)."',addState='".escape_string($ordShipState)."',addZip='".escape_string($ordShipZip)."',addCountry='".escape_string($ordShipCountry)."',addPhone='".escape_string($ordShipPhone)."',addExtra1='".escape_string($ordShipExtra1)."',addExtra2='".escape_string($ordShipExtra2)."' WHERE addCustID='" . escape_string(@$_SESSION['clientID']) . "' AND addID='" . escape_string(getpost('saddressid')) . "'";
					ect_query($sSQL) or ect_error();
				}
			}
		}
		$ordAddInfo=substr(strip_tags(getpost('ordAddInfo')),0,4096);
		if($commercialloc_) $ordComLoc=1; else $ordComLoc=0;
		if($wantinsurance_ || abs(@$addshippinginsurance)==1) $ordComLoc+=2;
		if($saturdaydelivery_) $ordComLoc+=4;
		if($signaturerelease_) $ordComLoc+=8;
		if($insidedelivery_) $ordComLoc+=16;
		$ordAffiliate=trim(strip_tags(substr(getpost('PARTNER'),0,48)));
		if(@$GLOBALS['closeaffiliateprogram'])$ordAffiliate='';
		$ordCheckoutExtra1=trim(strip_tags(substr(getpost('ordcheckoutextra1'),0,255)));
		$ordCheckoutExtra2=trim(strip_tags(substr(getpost('ordcheckoutextra2'),0,255)));
	}
	if(@$GLOBALS['avalaraaddressvalidation']&&($ordCountry=='United States of America'||$ordCountry=='Canada')){
		$sJSON='{"line1":' . json_encode($ordAddress) . ',"line2":' . json_encode($ordAddress2) . ',"city":' . json_encode($ordCity) . ',"region":' . json_encode($ordState) . ',"postalCode":' . json_encode($ordZip) . ',"country":' . json_encode($ordCountry) . '}';
		avalaraheaders();
		if(callcurlfunction('https://sandbox-rest.avatax.com/api/v2/addresses/resolve',$sJSON,$jres,'',$errormsg,FALSE)){
			$jsarray=json_decode($jres);
			if(@$jsarray->{'validatedAddresses'}[0]->{'postalCode'}&&!@$jsarray->{'messages'}[0]->{'severity'}=='Error')
				$ordZip=$jsarray->{'validatedAddresses'}[0]->{'postalCode'};
			else
				setcheckouterr('Your address could not be validated. Please check your address details carefully.');
		}
	}
	if($ordShipAddress!=''){
		if(@$GLOBALS['avalaraaddressvalidation']&&($ordShipCountry=='United States of America'||$ordShipCountry=='Canada')){
			$sJSON='{"line1":' . json_encode($ordShipAddress) . ',"line2":' . json_encode($ordShipAddress2) . ',"city":' . json_encode($ordShipCity) . ',"region":' . json_encode($ordShipState) . ',"postalCode":' . json_encode($ordShipZip) . ',"country":' . json_encode($ordShipCountry) . '}';
			avalaraheaders();
			if(callcurlfunction('https://sandbox-rest.avatax.com/api/v2/addresses/resolve',$sJSON,$jres,'',$errormsg,FALSE)){
				$jsarray=json_decode($jres);
				if(@$jsarray->{'validatedAddresses'}[0]->{'postalCode'}&&!@$jsarray->{'messages'}[0]->{'severity'}=='Error')
					$ordShipZip=$jsarray->{'validatedAddresses'}[0]->{'postalCode'};
				else
					setcheckouterr('Your shipping address could not be validated. Please check your shipping address details carefully.');
			}
		}
		$shipcountry=$ordShipCountry;
		$shipstate=$ordShipState;
		$destZip=$ordShipZip;
	}else{
		$shipcountry=$ordCountry;
		$shipstate=$ordState;
		$destZip=$ordZip;
		if(@$GLOBALS['autobillingtoshipping']){
			$ordShipName=@$ordName;
			$ordShipLastName=@$ordLastName;
			$ordShipAddress=@$ordAddress;
			$ordShipAddress2=@$ordAddress2;
			$ordShipCity=@$ordCity;
			$ordShipState=@$ordState;
			$ordShipZip=@$ordZip;
			$ordShipCountry=@$ordCountry;
			$ordShipPhone=@$ordPhone;
			$ordShipExtra1=@$ordExtra1;
			$ordShipExtra2=@$ordExtra2;
		}
	}
	$sSQL="SELECT countryID,countryCode,countryCode3,loadStates FROM countries WHERE countryName='" . escape_string($ordCountry) . "'";
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		$countryID=$rs['countryID'];
		$countryCode=$rs['countryCode'];
		$countryCode3=$rs['countryCode3'];
		$homecountry=($rs['countryID']==$origCountryID);
		if($rs['loadStates']!=-1 && $ordState=='' && !$paypalcheckoutexpress) $errordstate=setcheckouterr(str_replace('%s',getstatetext($countryID),$GLOBALS['xxMusSta']));
	}else
		$success=FALSE;
	ect_free_result($result);
	if(! $homecountry) $GLOBALS['perproducttaxrate']=FALSE;
	$sSQL="SELECT countryID,countryTax,countryTaxThreshold,countryCode,countryCode3,countryFreeShip,loadStates FROM countries WHERE countryName='" . escape_string($shipcountry) . "'";
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		$countryTaxRate=$rs['countryTax'];
		$GLOBALS['countrytaxthreshold']=$rs['countryTaxThreshold'];
		$shipCountryID=$rs['countryID'];
		$shipCountryCode=$rs['countryCode'];
		$shipCountryCode3=$rs['countryCode3'];
		$freeshipavailtodestination=($rs['countryFreeShip']==1);
		$shiphomecountry=($rs['countryID']==$origCountryID) || (($rs['countryID']==1 || $rs['countryID']==2) && @$GLOBALS['usandcasplitzones']);
		if($rs['loadStates']!=-1 && $shipstate=='' && $ordShipAddress!='') $errordshipstate=setcheckouterr(str_replace('%s',getstatetext($shipCountryID),$GLOBALS['xxMusSta']));
	}else{
		if($shipcountry!=$ordCountry) $errordshipcountry=setcheckouterr('You must select a ship country.');
		if($shipcountry!='') $errormsg.='<div>Invalid countryName:' . htmldisplay($shipcountry) . '</div>';
	}
	ect_free_result($result);
	$sSQL='SELECT shipInsurance'.($shiphomecountry?'Dom':'Int').',insurance'.($shiphomecountry?'Dom':'Int').'Min,insurance'.($shiphomecountry?'Dom':'Int').'Percent,noCarrier'.($shiphomecountry?'Dom':'Int').'Ins FROM admin WHERE adminID=1';
	$result=ect_query($sSQL) or ect_error();
	$rs=ect_fetch_assoc($result);
	$addshippinginsurance=$rs['shipInsurance'.($shiphomecountry?'Dom':'Int')];
	$shipinsurancemin=$rs['insurance'.($shiphomecountry?'Dom':'Int').'Min'];
	$shipinsurancepercent=$rs['insurance'.($shiphomecountry?'Dom':'Int').'Percent'];
	if($addshippinginsurance==3){ $forceinsuranceselection=TRUE; $addshippinginsurance=2; }
	$nocarrierinsurancerates=$rs['noCarrier'.($shiphomecountry?'Dom':'Int').'Ins']!=0;
	ect_free_result($result);
	$allcart=$orderid=$ordauthstatus='';
	if($success){
		if($countryID==1||$countryID==2) $stateAbbrev=getstateabbrev($ordState);
		if($shipCountryID==1||$shipCountryID==2) $shipStateAbbrev=getstateabbrev($shipstate);
		if($shipCountryID!=''){
			$sSQL="SELECT stateID,stateTax,stateAbbrev,stateFreeShip FROM states WHERE stateCountryID='" . $shipCountryID . "' AND (stateName='" . escape_string($shipstate) . "'";
			if($shipCountryID==1||$shipCountryID==2) $sSQL.=" OR stateAbbrev='" . escape_string($shipstate) . "')"; else $sSQL.=')';
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				if($shiphomecountry) {
					if($shipCountryID==$origCountryID || (($shipCountryID==1||$shipCountryID==2) && @$GLOBALS['usandcasplitzones'])) $stateTaxRate=$rs['stateTax']; else $stateTaxRate=0;
					$freeshipavailtodestination=($freeshipavailtodestination && ($rs['stateFreeShip']==1));
				}
				$shipstateid=$rs['stateID'];
			}
			ect_free_result($result);
			if($shiphomecountry&&$willpickup_){
				if(@isset($GLOBALS['homestatetaxrate']))
					$stateTaxRate=$GLOBALS['homestatetaxrate'];
				else{
					$result=ect_query("SELECT MAX(stateTax) as maxtax FROM states WHERE stateCountryID='" . $shipCountryID . "' AND stateEnabled=1") or ect_error();
					if($rs=ect_fetch_assoc($result)) $stateTaxRate=$rs['maxtax'];
					ect_free_result($result);
				}
			}
		}
		if(($shipType==4 || $shipType==7 || $shipType==8 || $shipType==11) && $shipCountryID==1 && @$shipStateAbbrev=='GU') $shipCountryCode='GU';
		if(trim_(@$_SESSION["clientUser"])!=''){
			if(((int)$_SESSION["clientActions"] & 1)==1) $stateTaxRate=0;
			if(((int)$_SESSION["clientActions"] & 2)==2) $countryTaxRate=0;
		}
		getpayprovhandling();
		$shipType=getshiptype();
		if(! initshippingmethods()){ $success=FALSE; $checkoutmode='checkout'; }
		$sSQL="SELECT ordID,ordAuthStatus FROM orders WHERE ordStatus>1 AND ordAuthNumber='' AND " . getordersessionsql();
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){ $orderid=$rs['ordID']; $ordauthstatus=$rs['ordAuthStatus']; }
		ect_free_result($result);
		$sSQL='SELECT cartID,cartProdID,cartOrigProdID,cartProdName,cartProdPrice,cartQuantity,pWeight,pShipping,pShipping2,pExemptions,pSection,topSection,pDims,pTax,pMinQuant,pID FROM cart LEFT JOIN products ON cart.cartProdID=products.pId LEFT OUTER JOIN sections ON products.pSection=sections.sectionID WHERE cartCompleted=0 AND ' . getsessionsql() . ' ORDER BY cartID';
		$allcart=ect_query($sSQL) or ect_error();
	}
	if($ordCountry=='')
		$errordcountry=setcheckouterr('You must select a country.');
	else{
		if($ordEmail==''&&!$amazonpayment) $errordemail=setcheckouterr($GLOBALS['xxValEm']);
		if(@$GLOBALS['verifyemail']&&@$_SESSION['clientID']==''&&$ordEmail2!=$ordEmail&&getpost('shipselectoraction')==''&&!$amazonpayment) $errordemailv=setcheckouterr('Email verify does not match.');
		if(trim($ordName . $ordLastName)==''&&!$amazonpayment) $errordname=setcheckouterr('You must enter your name.');
		if(!$paypalcheckoutexpress){
			if($ordAddress==''&&!$amazonpayment) $errordaddress=setcheckouterr('You must enter your address.');
			if($ordCity=='') $errordcity=setcheckouterr('You must enter a city.');
			if($ordZip==''&&!zipisoptional($shipCountryID)) $errordzip=setcheckouterr('You must enter a zip / postal code.');
			if($ordPhone==''&&!$amazonpayment&&!$paypalexpress) $errordphone=setcheckouterr('You must enter a phone number.');
		}
	}
	//if(@$GLOBALS['extracheckoutfield1']!='' && @$GLOBALS['extracheckoutfield1required'] && $ordCheckoutExtra1=='' && ! $paypalcheckoutexpress) setcheckouterr($GLOBALS['xxPlsEntr'] . ' &quot;' . $GLOBALS['extracheckoutfield1'] . '&quot;');
	//if(@$GLOBALS['extracheckoutfield2']!='' && @$GLOBALS['extracheckoutfield2required'] && $ordCheckoutExtra2=='' && ! $paypalcheckoutexpress) setcheckouterr($GLOBALS['xxPlsEntr'] . ' &quot;' . $GLOBALS['extracheckoutfield2'] . '&quot;');
	if(! is_numeric($ordPayProvider)) $errordpayprovider=setcheckouterr('You must select a payment method.');
	if(($orderid=='' && getpost('shipselectoraction')!='')){
		$success=FALSE;
		$errormsg='Invalid Data';
	}
	if(@$GLOBALS['termsandconditions'] && getpost("license")!="1" && getpost("shipselectoraction")=='' && $ordPayProvider!='19' && $ordPayProvider!='21' && $ordPayProvider!='26' && !$paypalcheckoutexpress) $errtermsandconditions=setcheckouterr("Please proceed only if you are in acceptance of our terms and conditions.");
	$blockuser=checkuserblock($ordPayProvider);
	if($blockuser){
		$orderid=0;
		$thesessionid='';
		$errormsg=$multipurchaseblockmessage;
		$data1=$data2=$data3=$data4=$data5=$data6='';
		$ppbits=0;
		$success=FALSE;
	}else
		$success=getpayprovdetx($ordPayProvider,$data1,$data2,$data3,$data4,$data5,$data6,$ppflag1,$ppflag2,$ppflag3,$ppbits,$demomode,$ppmethod);
	if($success && (($GLOBALS['itemsincart']=ect_num_rows($allcart))>0)){
		$rowcounter=0;
		$index=0;
		while($rsCart=ect_fetch_assoc($allcart))
			$GLOBALS['cartrows'][$index++]=$rsCart;
		for($index=0;$index<$GLOBALS['itemsincart'];$index++){
			$rsCart=$GLOBALS['cartrows'][$index];
			if(is_null($rsCart['pWeight'])) $rsCart['pWeight']=0;
			if(($rsCart['cartProdID']==$giftcertificateid || $rsCart['cartProdID']==$donationid) && is_null($rsCart['pExemptions'])) $rsCart['pExemptions']=15;
			if($rsCart['cartProdID']==$giftwrappingid && is_null($rsCart['pExemptions'])) $rsCart['pExemptions']=12;
			$sSQL='SELECT SUM(coPriceDiff) AS coPrDff FROM cartoptions WHERE coCartID='. $rsCart['cartID'];
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				$rsCart['cartProdPrice']+=(float)$rs['coPrDff'];
				$GLOBALS['cartrows'][$index]['cartProdPrice']=$rsCart['cartProdPrice'];
			}
			ect_free_result($result);
			$sSQL='SELECT SUM(coWeightDiff) AS coWghtDff FROM cartoptions WHERE coCartID='. $rsCart['cartID'];
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				$rsCart['pWeight']+=(float)$rs['coWghtDff'];
				$GLOBALS['cartrows'][$index]['pWeight']=$rsCart['pWeight'];
			}
			ect_free_result($result);
			$runTot=$rsCart['cartProdPrice'] * (int)($rsCart['cartQuantity']);
			$totalquantity+=(int)($rsCart['cartQuantity']);
			$totalgoods+=$runTot;
			$thistopcat=0;
			if(trim_(@$_SESSION['clientID'])!=''){ $rsCart['pExemptions']=((int)$rsCart['pExemptions'] | ((int)$_SESSION['clientActions'] & 7)); if(((int)$_SESSION['clientActions'] & 32)==32) $rsCart['pExemptions']|=8; }
			if(($shipType==2 || $shipType==3 || $shipType==4 || $shipType>=6) && (float)$rsCart['pWeight']<=0.0)
				$rsCart['pExemptions']=($rsCart['pExemptions'] | 4);
			if(($rsCart['pExemptions'] & 1)==1) $statetaxfree+=$runTot;
			if(($rsCart['pExemptions'] & 8)!=8){ $handlingeligableitem=TRUE; $handlingeligablegoods+=$runTot; }
			if(@$GLOBALS['perproducttaxrate']){
				if(is_null($rsCart['pTax'])) $rsCart['pTax']=$countryTaxRate;
				if(($rsCart['pExemptions'] & 2)!=2) $countryTax+=(($rsCart['pTax'] * $runTot) / 100.0);
			}else{
				if(($rsCart['pExemptions'] & 2)==2) $countrytaxfree+=$runTot;
			}
			if(($rsCart['pExemptions'] & 4)==4) $shipfreegoods+=$runTot;
			if($rsCart['cartProdID']==$giftcertificateid || $rsCart['cartProdID']==$donationid){ $shipdiscountexempt+=$runTot; $numshipdiscountexempt+=$rsCart['cartQuantity']; }
			addproducttoshipping($rsCart,$index);
			if($rsCart['cartQuantity']<=$rsCart['pMinQuant']) setcheckouterr(str_replace(array('%pname%','%quant%'),array($rsCart['cartProdName'],$rsCart['pMinQuant']+1),$GLOBALS['xxMinQuw']));
			if(is_null($rsCart['pID'])&&$rsCart['cartProdID']!=$giftcertificateid&&$rsCart['cartProdID']!=$donationid&&$rsCart['cartProdID']!=$giftwrappingid) setcheckouterr($GLOBALS['xxHasDel']);
		}
		$loyaltypointsused=0;
		if($success){
			calculatediscounts(round($totalgoods,2),TRUE,$rgcpncode);
			calculateshipping();
			if(! $fromshipselector) insuranceandtaxaddedtoshipping();
			calculateshippingdiscounts(TRUE);
			if(@$_SESSION['clientID']!='' && @$_SESSION['clientActions']!=0) $cpnmessage.=$GLOBALS['xxLIDis'] . strip_tags(str_replace('"','',$_SESSION['clientUser'])) . '<br>';
			$cpnmessage=substr($cpnmessage,4);
			if(@$GLOBALS['loyaltypoints']!='' && @$_SESSION['clientID']!='' && @$_SESSION['noredeempoints']!=TRUE){
				if(! ((@$GLOBALS['loyaltypointsnowholesale'] && (@$_SESSION['clientActions'] & 8)==8) || (@$GLOBALS['loyaltypointsnopercentdiscount'] && (@$_SESSION['clientActions'] & 16)==16))){
					if($orderid!=''){
						$pointsRedeemed=0;
						$result=ect_query("SELECT pointsRedeemed FROM orders WHERE ordID=" . $orderid) or ect_error();
						if($rs=ect_fetch_assoc($result))
							$pointsRedeemed=$rs['pointsRedeemed'];
						ect_free_result($result);
						if($pointsRedeemed>0){
							ect_query("UPDATE customerlogin SET loyaltyPoints=loyaltyPoints+" . $pointsRedeemed . " WHERE clID=" . $_SESSION['clientID']) or ect_error();
							ect_query("UPDATE orders SET loyaltyPoints=0 WHERE ordID=" . $orderid) or ect_error();
						}
					}
					$result=ect_query("SELECT loyaltyPoints FROM customerlogin WHERE clID=" . $_SESSION['clientID']) or ect_error();
					if($rs=ect_fetch_assoc($result))
						$loyaltypointsused=$rs['loyaltyPoints'];
					ect_free_result($result);
					if(round($loyaltypointsused*$loyaltypointvalue,2)>=(@$GLOBALS['loyaltypointminimum']!=''?$GLOBALS['loyaltypointminimum']:0.05)){
						$loyaltypointdiscount=$loyaltypointsused*$loyaltypointvalue;
						if($loyaltypointdiscount>$totalgoods+(@$GLOBALS['showtaxinclusive']==3?$countryTax:0)-$totaldiscounts){
							$loyaltypointdiscount=$totalgoods+(@$GLOBALS['showtaxinclusive']==3?$countryTax:0)-$totaldiscounts;
							$loyaltypointsused=(int)($loyaltypointdiscount/$loyaltypointvalue);
						}
						$totaldiscounts+=round($loyaltypointdiscount,2);
						ect_query("UPDATE customerlogin SET loyaltyPoints=loyaltyPoints-" . $loyaltypointsused . " WHERE clID=" . $_SESSION['clientID']) or ect_error();
						$cpnmessage.=$GLOBALS['xxLoyPod'] . ': ' . FormatEuroCurrency($loyaltypointdiscount) . "<br>";
					}else
						$loyaltypointsused=0;
				}
			}
			calculatetaxandhandling();
			$totalgoods=round($totalgoods,$GLOBALS['currDecimals']);
			$shipping=round($shipping,$GLOBALS['currDecimals']);
			$freeshipamnt=round($freeshipamnt,$GLOBALS['currDecimals']);
			if($totaldiscounts>$totalgoods+(@$GLOBALS['showtaxinclusive']==3?$countryTax:0)) $totaldiscounts=$totalgoods+(@$GLOBALS['showtaxinclusive']==3?$countryTax:0);
			if(@$addshippingtodiscounts){
				$totaldiscounts+=$freeshipamnt;
				$freeshipamnt=0;
			}
			$totaldiscounts=round($totaldiscounts,$GLOBALS['currDecimals']);
			$grandtotal=round(($totalgoods + $shipping + $stateTax + $countryTax + $handling) - ($totaldiscounts + $freeshipamnt),$GLOBALS['currDecimals']);
			if($grandtotal < 0) $grandtotal=0;
			if($ordShipName=='' && $ordShipLastName=='' && $ordShipAddress=='' && $ordShipAddress2=='' && $ordShipCity=='') $ordShipCountry='';
			do_stock_check(FALSE,$backorder,$stockwarning);
			if(getpost('shipselectoraction')!=''){ $stockwarning=FALSE; $backorder=FALSE; }
			if($stockwarning){
				$checkoutmode='';
				if(ob_get_length()!==FALSE)
					header('Location: ' . $storeurl . 'cart' . $GLOBALS['extension']);
				else
					print '<meta http-equiv="Refresh" content="0; URL=' . $storeurl . 'cart' . $GLOBALS['extension'] . '"></body></html>';
				flush();
				exit;
			}
		}
		if(($success || getpost('shipselectoraction')=='') && ! $stockwarning){
			if(in_array(strtolower($ordEmail),$GLOBALS['bad_emails'],TRUE)||$ordAddress=='3137 Laguna Street'){
				$sSQL="DELETE FROM cart WHERE cartCompleted=0 AND cartOrderID=0 AND " . getsessionsql();
				ect_query($sSQL) or ect_error();
				$orderid=0;
			}elseif($orderid==''){
				$isneworder=TRUE;
				$referer=@$GLOBALS['ectdemostore']?'':@$_SESSION['httpreferer'];
				$storeurlpos=strpos(strtolower($referer), str_replace(array('http://','https://'),'',strtolower($storeurl)));
				if($storeurlssl!='')$storeurlsslpos=strpos(strtolower($referer), str_replace(array('http://','https://'),'',strtolower($storeurlssl)));else $storeurlsslpos=FALSE;
				if(($storeurlpos!==FALSE&&$storeurlpos<10) || ($storeurlssl!=''&&$storeurlsslpos!==FALSE&&$storeurlsslpos<10)) $referer='';
				$referarr=explode('?', $referer, 2);
				$sSQL='INSERT INTO orders (ordSessionID,ordClientID,ordName,ordLastName,ordAddress,ordAddress2,ordCity,ordState,ordZip,ordCountry,ordEmail,ordPhone,ordShipName,ordShipLastName,ordShipAddress,ordShipAddress2,ordShipCity,ordShipState,ordShipZip,ordShipCountry,ordShipPhone,ordPayProvider,ordAuthNumber,ordShipping,ordStateTax,ordCountryTax,ordHSTTax,ordHandling,ordShipType,ordShipCarrier,ordTotal,ordDate,ordStatus,ordAuthStatus,pointsRedeemed,ordStatusDate,ordComLoc,ordIP,ordAffiliate,ordExtra1,ordExtra2,ordShipExtra1,ordShipExtra2,ordCheckoutExtra1,ordCheckoutExtra2,ordAVS,ordCVV,ordLang,ordReferer,ordQuerystr,ordDiscount,ordDiscountText,ordUserAgent,ordAddInfo) VALUES (' .
					"'" . escape_string($thesessionid) . "'," .
					"'" . (@$_SESSION['clientID']!='' ? escape_string($_SESSION['clientID']) : 0) . "'," .
					"'" . escape_string($ordName) . "','" . escape_string($ordLastName) . "','" . escape_string($ordAddress) . "','" . escape_string($ordAddress2) . "'," .
					"'" . escape_string($ordCity) . "','" . escape_string($ordState) . "','" . escape_string($ordZip) . "','" . escape_string($ordCountry) . "'," .
					"'" . escape_string($ordEmail) . "','" . escape_string($ordPhone) . "'," .
					"'" . escape_string($ordShipName) . "','" . escape_string($ordShipLastName) . "','" . escape_string($ordShipAddress) . "','" . escape_string($ordShipAddress2) . "'," .
					"'" . escape_string($ordShipCity) . "','" . escape_string($ordShipState) . "','" . escape_string($ordShipZip) . "','" . escape_string($ordShipCountry) . "'," .
					"'" . escape_string($ordShipPhone) . "'," .
					"'" . escape_string($ordPayProvider) . "','','" . escape_string($shipping-$freeshipamnt) . "'," .
					($usehst?'0,0,' . ($stateTax + $countryTax) . ',' : "'" . escape_string($stateTax) . "','" . escape_string($countryTax) . "',0,") .
					"'" . escape_string($handling) . "','" . escape_string($shipMethod) . "','" . escape_string($shipType) . "','" . escape_string($totalgoods) . "'," .
					"'" . date("Y-m-d H:i:s", time() + ($GLOBALS['dateadjust']*60*60)) . "',2,''," . $loyaltypointsused . ",'" . date("Y-m-d H:i:s", time() + ($GLOBALS['dateadjust']*60*60)) . "'," .
					"'" . $ordComLoc . "','" . escape_string(getipaddress()) . "','" . escape_string($ordAffiliate) . "'," .
					"'" . escape_string($ordExtra1) . "','" . escape_string($ordExtra2) . "','" . escape_string($ordShipExtra1) . "','" . escape_string($ordShipExtra2) . "','" . escape_string($ordCheckoutExtra1) . "','" . escape_string($ordCheckoutExtra2) . "'," .
					"'" . escape_string($ordAVS) . "','" . escape_string($ordCVV) . "'," .
					"'" . escape_string((@$languageid==''?1:$languageid)-1) . "'," .
					"'" . escape_string($referarr[0]) . "','" . escape_string(@$referarr[1]) . "'," .
					"'" . escape_string($totaldiscounts) . "'," .
					"'" . escape_string(substr($cpnmessage,0,255)) . "'," .
					"'" . escape_string(substr(@$GLOBALS['captureuseragent']?$_SERVER['HTTP_USER_AGENT']:'',0,255)) . "'," .
					"'" . escape_string($ordAddInfo) . "')";
				ect_query($sSQL) or ect_error();
				$orderid=ect_insert_id();
			}else{
				$isneworder=FALSE;
				$sSQL='UPDATE orders SET ';
				if(getpost('shipselectoraction')==''){
					$sSQL.="ordSessionID='" . escape_string($thesessionid) . "'," .
						"ordClientID='" . (@$_SESSION['clientID']!='' ? escape_string($_SESSION['clientID']) : 0) . "'," .
						"ordName='" . escape_string($ordName) . "',ordLastName='" . escape_string($ordLastName) . "',ordAddress='" . escape_string($ordAddress) . "',ordAddress2='" . escape_string($ordAddress2) . "'," .
						"ordCity='" . escape_string($ordCity) . "',ordState='" . escape_string($ordState) . "',ordZip='" . escape_string($ordZip) . "',ordCountry='" . escape_string($ordCountry) . "'," .
						"ordEmail='" . escape_string($ordEmail) . "',ordPhone='" . escape_string($ordPhone) . "'," .
						"ordShipName='" . escape_string($ordShipName) . "',ordShipLastName='" . escape_string($ordShipLastName) . "',ordShipAddress='" . escape_string($ordShipAddress) . "',ordShipAddress2='" . escape_string($ordShipAddress2) . "'," .
						"ordShipCity='" . escape_string($ordShipCity) . "',ordShipState='" . escape_string($ordShipState) . "',ordShipZip='" . escape_string($ordShipZip) . "',ordShipCountry='" . escape_string($ordShipCountry) . "',ordShipPhone='" . escape_string($ordShipPhone) . "'," .
						"ordPayProvider='" . escape_string($ordPayProvider) . "',ordAuthNumber=''," .
						"ordComLoc=" . $ordComLoc . ",ordIP='" . escape_string(getipaddress()) . "',ordAffiliate='" . escape_string($ordAffiliate) . "'," .
						"ordExtra1='" . escape_string($ordExtra1) . "',ordExtra2='" . escape_string($ordExtra2) . "'," .
						"ordShipExtra1='" . escape_string($ordShipExtra1) . "',ordShipExtra2='" . escape_string($ordShipExtra2) . "'," .
						"ordCheckoutExtra1='" . escape_string($ordCheckoutExtra1) . "',ordCheckoutExtra2='" . escape_string($ordCheckoutExtra2) . "'," .
						"ordAVS='" . escape_string($ordAVS) . "',ordCVV='" . escape_string($ordCVV) . "'," .
						"ordLang='" . escape_string((@$languageid==''?1:$languageid)-1) . "'," .
						"ordDiscount='" . $totaldiscounts . "'," .
						"ordAddInfo='" . escape_string($ordAddInfo) . "',";
				}
				$sSQL.="ordDate='" . date("Y-m-d H:i:s", time() + ($GLOBALS['dateadjust']*60*60)) . "',ordStatusDate='" . date("Y-m-d H:i:s", time() + ($GLOBALS['dateadjust']*60*60)) . "'," .
					"ordShipping='" . ($shipping - $freeshipamnt) . "'," .
					"ordDiscountText='" . escape_string(substr($cpnmessage,0,255)) . "',ordTotal='" . $totalgoods . "',ordStateTax=" . ($usehst ? "0,ordCountryTax=0,ordHSTTax=" . ($stateTax + $countryTax) : "'" . $stateTax . "',ordCountryTax='" . $countryTax . "',ordHSTTax=0") . ",ordHandling='" . $handling . "'," .
					"ordShipType='" . escape_string($shipMethod) . "',ordShipCarrier='" . $shipType . "',ordAuthStatus='',pointsRedeemed=" . $loyaltypointsused .
					" WHERE ordID='" . $orderid . "'";
				ect_query($sSQL) or ect_error();
			}
			if($orderid!=0){
				$sSQL="UPDATE cart SET cartOrderID=". $orderid . " WHERE cartCompleted=0 AND " . getsessionsql();
				ect_query($sSQL) or ect_error();
				if($isneworder || $ordauthstatus=='MODWARNOPEN') stock_subtract($orderid);
				$sSQL="SELECT gcaGCID,gcaAmount FROM giftcertsapplied WHERE gcaOrdID='" . $orderid . "'";
				$result=ect_query($sSQL) or ect_error();
				while($rs=ect_fetch_assoc($result)){
					ect_query("UPDATE giftcertificate SET gcRemaining=gcRemaining+".round($rs['gcaAmount'], 2)." WHERE gcID='".$rs['gcaGCID']."'");
				}
				ect_free_result($result);
				ect_query("DELETE FROM giftcertsapplied WHERE gcaOrdID='" . $orderid . "'");
				if(@$_SESSION['giftcerts']!='' && $grandtotal>0){
					$sSQL="SELECT gcID,gcRemaining FROM giftcertificate WHERE gcRemaining>0 AND gcAuthorized<>0 AND gcID IN ('" . str_replace(' ',"','",escape_string(@$_SESSION['giftcerts'])) . "')";
					$result=ect_query($sSQL) or ect_error();
					while($rs=ect_fetch_assoc($result)){
						if($giftcertsamount>=$grandtotal) break;
						$thiscertamount=min($grandtotal-$giftcertsamount, $rs['gcRemaining']);
						ect_query("INSERT INTO giftcertsapplied (gcaGCID,gcaOrdID,gcaAmount) VALUES ('" . $rs['gcID'] . "','" . $orderid . "'," . $thiscertamount . ')');
						ect_query("UPDATE giftcertificate SET gcRemaining=gcRemaining-" . round($thiscertamount, 2) . ",gcDateUsed='" . date("Y-m-d", time() + ($GLOBALS['dateadjust']*60*60)) . "' WHERE gcID='" . $rs['gcID'] . "'");
						$giftcertsamount+=$thiscertamount;
					}
					ect_free_result($result);
					$totaldiscounts+=$giftcertsamount;
					$grandtotal -= $giftcertsamount;
					$cpnmessage.=$GLOBALS['xxAppGC'] . ' ' . FormatEuroCurrency($giftcertsamount) . ($cpnmessage!='' ? '<br>' : '');
					$sSQL="UPDATE orders SET ordDiscount=" . $totaldiscounts . ",ordDiscountText='" . escape_string($cpnmessage) . "' WHERE ordID='" . $orderid . "'";
					ect_query($sSQL) or ect_error();
				}
				$descstr='';
				$addcomma='';
				$sSQL="SELECT cartID,cartProdID,cartQuantity,cartProdName FROM cart WHERE cartOrderID=" . $orderid . " AND cartCompleted=0";
				$result=ect_query($sSQL) or ect_error();
				while($rs=ect_fetch_assoc($result)){
					if($rs['cartProdID']==$giftcertificateid){
						$sSQL="SELECT gcID FROM giftcertificate WHERE gcCartID='" . $rs['cartID'] . "'";
						$result2=ect_query($sSQL) or ect_error();
						if(ect_num_rows($result2)==0){
							$errormsg='You have a gift certificate added to the cart but unfortunately the certificate was not created correctly. Please remove the certificate from the cart and add it again.';
							$success=FALSE;
						}
						ect_query("UPDATE giftcertificate SET gcOrderID='" . $orderid . "' WHERE gcCartID='" . $rs['cartID'] . "'") or ect_error();
					}
					$descstr.=$addcomma . $rs['cartQuantity'] . ' ' . strip_tags($rs['cartProdName']);
					$addcomma=', ';
				}
				ect_free_result($result);
				$descstr=str_replace('"','',$descstr);
				if(! $fromshipselector){
					ect_query("DELETE FROM shipoptions WHERE soOrderID=".$orderid." OR soDateAdded<'".date('Y-m-d', time() - (24*60*60))."'") or ect_error();
					saveshippingoptions();
				}
				if(@$_SESSION['clientID']==''){
					setacookie('ectordid',$orderid,0);
					setacookie('ectsessid',$thesessionid,0);
					setacookie('ecthash',hash('sha256',$orderid.$thesessionid.$adminSecret),0);
				}
				ect_query("DELETE FROM couponsapplied WHERE cpaOrdID=" . $orderid);
				for($index=0;$index<$numdiscountarray;$index++){
					$sSQL="INSERT INTO couponsapplied (cpaCpnID,cpaOrdID,cpaAmount,cpaTxt) VALUES (" . $discountarray[$index][0] . "," . $orderid . "," . $discountarray[$index][2] . ",'" . escape_string($discountarray[$index][1]) . "')";
					ect_query($sSQL);
				}
			}else
				$success=FALSE;
		}
	}else
		$success=FALSE;
	if($allcart) ect_free_result($allcart);
	if($stockwarning||$returntocustomerdetails){
		$success=FALSE;
	}elseif($success&&$ordPayProvider!=''){
		if(@$wpconfirmpage=='') $wpconfirmpage='wpconfirm.php';
		if(@$GLOBALS['nopriceanywhere']) $grandtotal=0;
		if($success==FALSE){
			print '<form method="post" action="cart' . $GLOBALS['extension'] . '">';
		}elseif($grandtotal==0 || $ordPayProvider=='4' || $ordPayProvider=='17'){ // Email
			if($grandtotal==0&&$ordPayProvider!='17') $ordPayProvider='4';
			print '<form method="post" name="checkoutform" id="ectemailform" action="thanks' . $GLOBALS['extension'] . '"'.(recaptchaenabled(256)?' onsubmit="return docheckform(this)"':'').'>' . whv(($grandtotal>0&&$ordPayProvider=='17'?'second':'').'emailorder', $orderid) . whv('thesessionid', $thesessionid);
		}elseif($ordPayProvider=='1'){ // PayPal
			$php_version=explode('.',phpversion());
			if(((int)$php_version[0])<5) print 'Please note, you are using PHP 4 and PHP 5 is required for PayPal.';
			if(strpos($data1,'/')!==FALSE){
				$data1arr=explode('/',$data1);
				if($grandtotal<12) $data1=trim($data1arr[1]); else $data1=trim($data1arr[0]);
			}
			if(@$paypalhostedsolution){
				print '<form method="post" action="https://securepayments.' . ($demomode ? 'sandbox.' : '') . 'paypal.com/cgi-bin/acquiringweb">';
				print whv('cmd','_hosted-payment');
			}else{
				print '<form method="post" action="https://www.'.($demomode?'sandbox.':'').'paypal.com/cgi-bin/webscr">';
				print whv('cmd','_ext-enter') . whv('redirect_cmd','_xclick') . whv('rm','2');
			}
			print whv('business',$data1) . whv('return',$storeurlssl.'thanks'.$GLOBALS['extension']);
			print whv('notify_url',$storeurlssl.'vsadmin/ppconfirm.php') . whv('item_name',substr(@$GLOBALS['cartdescription']!=''?$GLOBALS['cartdescription']:$descstr,0,127)) . whv('custom',$orderid) . whv('invoice',$orderid) . whv('no_note','1');
			if(@$paypallc!='') print whv('lc',$paypallc);
			if(@$paypalhostedsolution){
				print whv('subtotal',number_format($grandtotal,getDPs($countryCurrency),'.',''));
			}elseif(@$splitpaypalshipping){
				print whv('shipping',number_format(($shipping + $handling) - $freeshipamnt,getDPs($countryCurrency),'.',''));
				print whv('amount',number_format(($totalgoods + $stateTax + $countryTax) - $totaldiscounts,getDPs($countryCurrency),'.',''));
			}else{
				print whv('amount',number_format($grandtotal,getDPs($countryCurrency),'.',''));
			}
			print whv('currency_code',$countryCurrency) . whv('bn','ecommercetemplates_Cart_WPS_US');
			if(@$GLOBALS['usefirstlastname']){
				print whv('first_name',$ordName) . whv('last_name',$ordLastName);
				if(@$paypalhostedsolution) print whv('billing_first_name',$ordName) . whv('billing_last_name',$ordLastName);
			}elseif(strpos(trim($ordName),' ')!==FALSE){
				$namearr=explode(' ',trim($ordName),2);
				print whv('first_name',$namearr[0]) . whv('last_name',@$namearr[1]);
				if(@$paypalhostedsolution) print whv('billing_first_name',$namearr[0]) . whv('billing_last_name',@$namearr[1]);
			}else{
				print whv('last_name',$ordName);
				if(@$paypalhostedsolution) print whv('billing_last_name',$ordName);
			}
			if((trim($ordShipName)!='' || trim($ordShipLastName)!='' || trim($ordShipAddress)!='') && @$paypalhostedsolution)
				print whv('address1',$ordShipAddress) . whv('address2',$ordShipAddress2) . whv('city',$ordShipCity) . whv('state',$shipCountryID==1 && $shipStateAbbrev!='' ? $shipStateAbbrev : $ordShipState) . whv('country',$shipCountryCode) . whv('zip',$ordShipZip);
			else
				print whv('address1',$ordAddress) . whv('address2',$ordAddress2) . whv('city',$ordCity) . whv('state',$countryID==1 && $stateAbbrev!='' ? $stateAbbrev : $ordState) . whv('country',$countryCode) . whv('zip',$ordZip);
			print whv('email',$ordEmail);
			if(@$paypalhostedsolution) print whv('billing_address1',$ordAddress) . whv('billing_address2',$ordAddress2) . whv('billing_city',$ordCity) . whv('billing_state',$countryID==1 && $stateAbbrev!='' ? $stateAbbrev : $ordState) . whv('billing_country',$countryCode) . whv('buyer_email',$ordEmail) . whv('billing_zip',$ordZip);
			print whv('cancel_return',$GLOBALS['storeurlssl'].'cart'.$GLOBALS['extension']);
			if($countryCode!='US' && $countryCode!='CA') print whv('night_phone_b',$ordPhone);
			if($ppmethod==1) print whv('paymentaction','authorization');
		}elseif($ordPayProvider=='2'){ // 2Checkout
			function twocoready($tcoinput){
				return substr(trim(str_replace(array('<','>'),'',preg_replace("(\r\n|\n|\r)",'\\n',strip_tags($tcoinput)))),0,200);
			}
			$courl='https://' . ($demomode?'sandbox':'www') . '.2checkout.com/checkout/purchase';
			print '<form method="post" action="' . $courl . '">';
			print whv('merchant_order_id', $orderid) . whv('sid', $data1) . whv('mode', '2CO');
			print whv('card_holder_name', trim($ordName.' '.$ordLastName)) . whv('street_address', $ordAddress) . (trim($ordAddress2)!=''?whv('ship_street_address2', $ordAddress2):'');
			print whv('city', $ordCity) . whv('state', $ordState) . whv('zip', $ordZip) . whv('country', $countryCode) . whv('email', $ordEmail) . whv('phone', $ordPhone);
			$index=0;
			$sSQL='SELECT cartID,cartProdID,cartProdName,cartProdPrice,cartQuantity,' . (@$digidownloads==TRUE ? 'pDownload,' : '') . 'pDescription FROM cart LEFT JOIN products on cart.cartProdID=products.pID WHERE cartCompleted=0 AND ' . getsessionsql();
			$result=ect_query($sSQL) or ect_error();
			while($rs=ect_fetch_assoc($result)){
				$thedesc=twocoready($rs['pDescription']);
				print whv('li_' . $index . '_product_id', twocoready($rs['cartProdID']));
				print whv('li_' . $index . '_name', twocoready($rs['cartProdName']));
				if($thedesc!='') print whv('li_' . $index . '_description', $thedesc);
				print whv('li_' . $index . '_price', number_format($rs['cartProdPrice'],2,'.',''));
				print whv('li_' . $index . '_quantity',$rs['cartQuantity']);
				if(@$digidownloads) print whv('li_' . $index . '_tangible',trim($rs['pDownload'])!=''?'N':'Y'); else print whv('li_' . $index . '_tangible','Y');
					$sSQL='SELECT coOptGroup,coCartOption,coPriceDiff FROM cartoptions WHERE coCartID=' . $rs['cartID'];
					$result2=ect_query($sSQL) or ect_error();
					$index2=0;
					while($rs2=ect_fetch_assoc($result2)){
						print whv('li_' . $index . '_option_' . $index2 . '_name', twocoready($rs2['coOptGroup']));
						print whv('li_' . $index . '_option_' . $index2 . '_value', twocoready($rs2['coCartOption']));
						print whv('li_' . $index . '_option_' . $index2 . '_surcharge', number_format($rs2['coPriceDiff'],2,'.',''));
					}
					ect_free_result($result2);
				$index++;
			}
			ect_free_result($result);
			print whv('li_' . $index . '_type', 'shipping');
			print whv('li_' . $index . '_price', number_format($shipping + $handling,2,'.',''));
			$index++;
			if(@$GLOBALS['showtaxinclusive']!=3 && $stateTax+$countryTax>0){
				print whv('li_' . $index . '_type', 'tax');
				print whv('li_' . $index . '_price', number_format($stateTax+$countryTax,2,'.',''));
				$index++;
			}
			if($totaldiscounts + $freeshipamnt>0){
				print whv('li_' . $index . '_type', 'coupon');
				print whv('li_' . $index . '_price', number_format($totaldiscounts + $freeshipamnt,2,'.',''));
				print whv('li_' . $index . '_name', 'Discounts');
				$index++;
			}
			if(trim($ordShipName)!='' || trim($ordShipLastName)!='' || trim($ordShipAddress)!='')
				print whv('ship_name', trim($ordShipName.' '.$ordShipLastName)) . whv('ship_street_address', $ordShipAddress) . ($ordShipAddress2!='' ? whv('ship_street_address2', $ordShipAddress2) : '') . whv('ship_city', $ordShipCity) . whv('ship_state', $ordShipState) . whv('ship_zip', $ordShipZip) . whv('ship_country', $ordShipCountry);
			else
				print whv('ship_name', trim($ordName.' '.$ordLastName)) . whv('ship_street_address', $ordAddress) . ($ordAddress2!='' ? whv('ship_street_address2', $ordAddress2) : '') . whv('ship_city', $ordCity) . whv('ship_state', $ordState) . whv('ship_zip', $ordZip) . whv('ship_country', $ordCountry);
			if($demomode) print whv('demo', 'Y');
			print whv('purchase_step', 'payment-method') . whv('currency_code', $countryCurrency). whv('x_receipt_link_url', $storeurl . 'thanks' . $GLOBALS['extension']);
		}elseif($ordPayProvider=='3'){ // Authorize.net SIM
			if(@$authnetemulateurl=='') $authnetemulateurl='https://secure.authorize.net/gateway/transact.dll';
			if(@$secretword!=''){
				$data1=upsdecode($data1, $secretword);
				$data2=upsdecode($data2, $secretword);
			}
			if($ppflag1==1){
				$firstname=''; $lastname=trim($ordName);
				if(@$GLOBALS['usefirstlastname']){
					$firstname=$ordName; $lastname=$ordLastName;
				}elseif(strpos(trim($ordName), ' ')!==FALSE){
					$namearr=explode(' ',trim($ordName),2);
					$firstname=$namearr[0]; $lastname=@$namearr[1];
				}
				$fingerprint=strtoupper(hash_hmac('sha512',$data1 . '^' . $orderid . '^' . $GLOBALS['adminSecret'] . '^' . $data2 . '^',hex2bin($data3)));
				$sjson='{
	"getHostedPaymentPageRequest": {
		"merchantAuthentication":{"name":' . json_encode($data1) . ',"transactionKey":' . json_encode($data2) . '},
		"refId":' . json_encode($orderid) . ',
		"transactionRequest":{
			"transactionType":"auth' . ($ppmethod==1?'Only':'Capture') . 'Transaction",
			"amount":"' . number_format($grandtotal,getDPs($countryCurrency),'.','') . '",
			' . ($demomode?'':'"solution":{"id":' . json_encode('AAA172582') . '},') . '
			"order":{"invoiceNumber":' . json_encode($orderid) . ',"description":' . json_encode(substr($descstr,0,255)) . '},
			"tax":{"amount":' . number_format($stateTax+$countryTax,getDPs($countryCurrency),'.','') . '},
			"shipping":{"amount":' . number_format($shipping + (@$GLOBALS['combineshippinghandling']?$handling:0) - $freeshipamnt,getDPs($countryCurrency),'.','') . '},
			"customer":{"email":' . json_encode($ordEmail) . '},
			"billTo":{
				"firstName":' . json_encode($firstname) . ',"lastName":' . json_encode($lastname) . ',
				"address":' . json_encode($ordAddress) . ',"city":' . json_encode($ordCity) . ',"state":' . json_encode($countryID==1 && $stateAbbrev!='' ? $stateAbbrev : $ordState) . ',"zip":' . json_encode($ordZip) . ',"country":' . json_encode($countryCode3) . ',"phoneNumber":' . json_encode($ordPhone) . '
			}';
			if(trim($ordShipName)!='' || trim($ordShipLastName)!='' || trim($ordShipAddress)!=''){
				$firstname=''; $lastname=trim($ordShipName);
				if(@$GLOBALS['usefirstlastname']){
					$firstname=$ordShipName; $lastname=$ordShipLastName;
				}elseif(strpos(trim($ordShipName), ' ')!==FALSE){
					$namearr=explode(' ',trim($ordShipName),2);
					$firstname=$namearr[0]; $lastname=@$namearr[1];
				}
				$sjson.=',"shipTo":{
					"firstName":' . json_encode($firstname) . ',"lastName":' . json_encode($lastname) . ',
					"address":' . json_encode($ordShipAddress) . ',"city":' . json_encode($ordShipCity) . ',"state":' . json_encode($shipCountryID==1 && $shipStateAbbrev!='' ? $shipStateAbbrev : $ordShipState) . ',"zip":' . json_encode($ordShipZip) . ',"country":' . json_encode($shipCountryCode3) . '
				}';
			}
		$sjson.='},
		"hostedPaymentSettings":{
			"setting": [{"settingName":"hostedPaymentReturnOptions","settingValue":"{\"showReceipt\":false,\"url\":\"' . str_replace('/','\\/',$storeurlssl) . 'thanks' . $GLOBALS['extension'] . '?method=anethosted%26ordid=' . $orderid . '%26fp=' . $fingerprint . '\", \"urlText\": \"' . $GLOBALS['xxContin'] . '\", \"cancelUrl\": \"' . str_replace('/','\\/',$storeurl) . 'cart' . $GLOBALS['extension'] . '\", \"cancelUrlText\": \"' . $GLOBALS['xxCancel'] . '\"}"
			}, {"settingName":"hostedPaymentButtonOptions","settingValue":"{\"text\": \"Pay\"}"
			}, {"settingName": "hostedPaymentPaymentOptions","settingValue":"{\"cardCodeRequired\":true,\"showCreditCard\":true,\"showBankAccount\":false}"
			}, {"settingName": "hostedPaymentSecurityOptions","settingValue": "{\"captcha\": false}"
			}, {"settingName": "hostedPaymentBillingAddressOptions","settingValue": "{\"show\": true, \"required\": true}"
			}]}}}';
				if($success=callcurlfunction('https://api' . ($demomode?'test':'') . '.authorize.net/xml/v1/request.api',$sjson,$jres,'',$errormsg,FALSE)){
					$index=0;
					while($index<strlen($jres)&&ord($jres[$index])>127)
						$index++;
					if($index>0) $jres=substr($jres,$index);
					$jsarray=json_decode((string)$jres);
					if(@$jsarray->{'messages'}->{'resultCode'}=='Ok')
						$token=$jsarray->{'token'};
					else{
						if(@$jsarray->{'messages'}->{'message'}[0]->{'text'})
							$errormsg=$jsarray->{'messages'}->{'message'}[0]->{'text'};
						elseif(trim($jres)!='')
							$errormsg=trim($jres);
						$success=FALSE;
					}
				}
				print '<form method="post" action="https://' . ($demomode?'test':'accept') . '.authorize.net/payment/payment">';
				print '<input type="hidden" id="popupToken" name="token" value="' . $token . '" />';
			}else{
				print '<form method="post" action="' . $authnetemulateurl . '">';
				print whv('x_Version', '3.0') . whv('x_Login', $data1) . whv('x_Show_Form', 'PAYMENT_FORM');
				if($ppmethod==1) print whv('x_type', 'AUTH_ONLY');
				if(@$GLOBALS['usefirstlastname']){
					print whv('x_first_name', $ordName) . whv('x_last_name', $ordLastName);
				}elseif(strpos(trim($ordName), ' ')!==FALSE){
					$namearr=explode(' ',trim($ordName),2);
					print whv('x_first_name', $namearr[0]) . whv('x_last_name', @$namearr[1]);
				}else
					print whv('x_last_name', $ordName);
				$sequence=$orderid;
				if(@$authnetadjust!='') $tstamp=time() + $authnetadjust; else $tstamp=time();
				if(strlen($data3)>100)
					$fingerprint=strtoupper(hash_hmac('sha512',$data1 . '^' . $sequence . '^' . $tstamp . '^' . number_format($grandtotal,2,'.','') . '^',hex2bin($data3)));
				else
					$fingerprint=vrhmac2($data2, $data1 . '^' . $sequence . '^' . $tstamp . '^' . number_format($grandtotal,2,'.','') . '^');
				print whv('x_fp_sequence', $sequence) . whv('x_fp_timestamp', $tstamp) . whv('x_fp_hash', $fingerprint);
				print whv('x_address', $ordAddress . (trim($ordAddress2)!='' ? ', ' . $ordAddress2 : '')) . whv('x_city', $ordCity) . whv('x_country', $ordCountry);
				print whv('x_phone', $ordPhone) . whv('x_state', $ordState) . whv('x_zip', $ordZip);
				print whv('x_invoice_num', $orderid) . whv('x_email', $ordEmail) . whv('x_description', substr($descstr,0,255));
				if(@$_SESSION['clientID']!='') print whv('x_cust_id', $_SESSION['clientID']);
				if(trim($ordShipName)!='' || trim($ordShipLastName)!='' || trim($ordShipAddress)!=''){
					if(@$GLOBALS['usefirstlastname']){
						print whv('x_ship_to_first_name', $ordShipName) . whv('x_ship_to_last_name', $ordShipLastName);
					}elseif(strpos(trim($ordName), ' ')!==FALSE){
						$namearr=explode(' ',trim($ordShipName),2);
						print whv('x_ship_to_first_name', $namearr[0]) . whv('x_ship_to_last_name', @$namearr[1]);
					}else
						print whv('x_ship_to_last_name', $ordShipName);
					print whv('x_ship_to_address', $ordShipAddress . (trim($ordShipAddress2)!='' ? ', ' . $ordShipAddress2 : '')) . whv('x_ship_to_city', $ordShipCity) . whv('x_ship_to_country', $ordShipCountry) . whv('x_ship_to_state', $ordShipState) . whv('x_ship_to_zip', $ordShipZip);
				}
				print whv('x_Amount',number_format($grandtotal,2,'.','')) . whv('x_Relay_Response','TRUE') . whv('x_Relay_URL',$storeurl.'vsadmin/'.$wpconfirmpage) . whv('x_solution_id','AAA172582');
				if($demomode) print whv('x_Test_Request','TRUE');
			}
		}elseif($ordPayProvider=='5'){ // WorldPay
			print '<form method="post" action="https://secure' . ($demomode ? '-test' : '') . '.worldpay.com/wcc/purchase">';
			print whv('instId', $data1) . whv('cartId', $orderid) . whv('amount', number_format($grandtotal,2,'.','')) . whv('currency', $countryCurrency);
			print whv('desc', substr($descstr,0,255));
			print whv('name', trim($ordName.' '.$ordLastName)) . whv('address', $ordAddress . (trim($ordAddress2)!='' ? ', ' . $ordAddress2 : '') . "\n" . $ordCity . "\n" . $ordState);
			print whv('postcode', $ordZip) . whv('country', $countryCode) . whv('tel', $ordPhone) . whv('email', $ordEmail);
			print whv('authMode', $ppmethod==1 ? 'E' : 'A') . whv('testMode', $demomode ? '100' : '0');
			$data2arr=explode('&',$data2);
			$data2=@$data2arr[0];
			if($data2!=''){
				$sigfields='amount:currency:cartId:testMode';
				print whv('signatureFields', $sigfields) . whv('signature', md5($data2 . ';' . $sigfields . ';' . number_format($grandtotal,2,'.','') . ';' . $countryCurrency . ';' . $orderid . ';' . ($demomode?'100':'0')));
			}
		}elseif($ordPayProvider=="6"){ // NOCHEX
			print '<form method="post" action="https://secure.nochex.com/">';
			print whv('merchant_id', $data1);
			print whv('success_url', $storeurl . 'thanks' . $GLOBALS['extension'] . '?ncretval=' . $orderid . '&ncsessid=' . $thesessionid) . whv('callback_url', $storeurl.'vsadmin/ncconfirm.php');
			print whv('description', substr($descstr,0,255));
			print whv('order_id', $orderid) . whv('amount', number_format($grandtotal,2,'.',''));
			print whv('billing_fullname', trim($ordName.' '.$ordLastName)) . whv('billing_address', $ordAddress . (trim($ordAddress2)!='' ? ', ' . $ordAddress2 : '')) . whv('billing_postcode', $ordZip) . whv('email_address', $ordEmail) . whv('customer_phone_number', $ordPhone);
			if(trim($ordShipName)!='' || trim($ordShipAddress)!=''){
				print whv('delivery_fullname', trim($ordShipName.' '.$ordShipLastName)) . whv('delivery_address', $ordShipAddress . (trim($ordShipAddress2)!='' ? ', ' . $ordShipAddress2 : '')) . whv('delivery_postcode', $ordShipZip);
			}
			if($demomode) print whv('test_transaction', '100');
		}elseif($ordPayProvider=="7"){ // Payflow Pro
			print '<form method="post" action="cart' . $GLOBALS['extension'] . '" onsubmit="return isvalidcard(this)">';
			print whv('mode', 'authorize') . whv('method', '7') . whv('ordernumber', $orderid);
		}elseif($ordPayProvider=="8"){ // Payflow Link
			if(strpos($data1,'&')!==FALSE){
				print '<form method="post" action="cart' . $GLOBALS['extension'] . '" onsubmit="return isvalidcard(this)">';
				print whv('mode', 'authorize') . whv('method', '8') . whv('ordernumber', $orderid);
			}else{
				$paymentlink='https://payflowlink.paypal.com';
				print '<form method="post" action="' . $paymentlink . '">';
				print whv('LOGIN', $data1) . whv('PARTNER', $data2) . whv('CUSTID', $orderid) . whv('AMOUNT', number_format($grandtotal,2,'.',''));
				print whv('TYPE',$ppmethod==1?'A':'S');
				print whv('DESCRIPTION', substr($descstr,0,255));
				print whv('NAME', trim($ordName.' '.$ordLastName)) . whv('ADDRESS', $ordAddress . (trim($ordAddress2)!='' ? ', ' . $ordAddress2 : '')) . whv('CITY', $ordCity) . whv('STATE', $ordState) . whv('ZIP', $ordZip) . whv('COUNTRY', ($countryCode=='US'?'USA':$ordCountry));
				print whv('EMAIL', $ordEmail) . whv('PHONE', $ordPhone);
				print whv('METHOD', 'CC') . whv('ORDERFORM', 'TRUE') . whv('SHOWCONFIRM', 'FALSE') . whv('BUTTONSOURCE', 'EcommerceTemplatesUS_Cart_PPA');
				if(trim($ordShipName)!='' || trim($ordShipAddress)!=''){
					print whv('NAMETOSHIP', trim($ordShipName.' '.$ordShipLastName)) . whv('ADDRESSTOSHIP', $ordShipAddress . (trim($ordShipAddress2)!='' ? ', ' . $ordShipAddress2 : '')) . whv('CITYTOSHIP', $ordShipCity) . whv('STATETOSHIP', $ordShipState) . whv('ZIPTOSHIP', $ordShipZip) . whv('COUNTRYTOSHIP', ($shipCountryCode=='US'?'USA':$ordShipCountry));
				}
			}
		}elseif($ordPayProvider=="9"){ // PayPoint.net
			print '<form method="post" action="https://www.secpay.com/java-bin/ValCard">';
			print whv('merchant', $data1) . whv('trans_id', $orderid) . whv('amount', number_format($grandtotal,2,'.',''));
			print whv('callback', $storeurl.'vsadmin/'.$wpconfirmpage) . whv('currency', $countryCurrency) . whv('cb_post', 'true');
			print whv('bill_name', trim($ordName.' '.$ordLastName)) . whv('bill_addr_1', $ordAddress) . whv('bill_addr_2', $ordAddress2) . whv('bill_city', $ordCity) . whv('bill_state', $ordState) . whv('bill_post_code', $ordZip) . whv('bill_country', $ordCountry) . whv('bill_email', $ordEmail) . whv('bill_tel', $ordPhone);
			if(trim($ordShipName)!='' || trim($ordShipLastName)!='' || trim($ordShipAddress)!=''){
				print whv('ship_name', trim($ordShipName.' '.$ordShipLastName)) . whv('ship_addr_1', $ordShipAddress) . whv('ship_addr_2', $ordShipAddress2) . whv('ship_city', $ordShipCity) . whv('ship_state', $ordShipState) . whv('ship_post_code', $ordShipZip) . whv('ship_country', $ordShipCountry);
			}
			$data2arr=explode('&',$data2);
			$data2md5=@$data2arr[0];
			$data2tpl=urldecode(@$data2arr[1]);
			if(trim($data2md5)!=''){
				print whv('digest', md5($orderid . number_format($grandtotal,2,'.','') . $data2md5));
				print whv('md_flds', 'trans_id:amount:callback');
			}
			print whv('mpi_description', substr($descstr,0,125));
			if(trim($data2tpl)!='') print whv('template', $data2tpl);
			if($ppmethod==1) print whv('deferred', 'reuse:5:5');
			print whv('req_cv2', 'true');
			if($data3=='1') print whv('ssl_cb', 'true');
			if($demomode) print whv('options', 'test_status=true,dups=false');
		}elseif($ordPayProvider=='10'){ // Capture Card
			print 'DISABLED!!<br>';
		}elseif($ordPayProvider=="11" || $ordPayProvider=="12"){ // PSiGate
			print '<form method="post" action="https://' . ($demomode ? 'staging' : 'checkout') . '.psigate.com/HTMLPost/HTMLMessenger"' . ($ordPayProvider=='12' ? ' onsubmit="return isvalidcard(this)"' : '') . '>';
			print whv('MerchantID', $data1) . whv('Oid', $orderid) . whv('FullTotal', number_format($grandtotal,2,'.','')) . whv('ThanksURL',$storeurl.'thanks'.$GLOBALS['extension']) . whv('NoThanksURL', $storeurl.'thanks'.$GLOBALS['extension']) . whv('CustomerRefNo', substr(md5($orderid.':'.@$secretword), 0, 24)) . whv('ChargeType', $ppmethod=='1' ? '1' : '0');
			if($ordPayProvider=='11') print whv('Bname', trim($ordName.' '.$ordLastName));
			print whv('Baddr1', $ordAddress) . whv('Baddr2', $ordAddress2) . whv('Bcity', $ordCity) . whv('IP', $GLOBALS['REMOTE_ADDR']) . whv('Bstate', $countryID==1 && $stateAbbrev!='' ? $stateAbbrev : $ordState) . whv('Bzip', $ordZip) . whv('Bcountry', $countryCode) . whv('Email', $ordEmail) . whv('Phone', $ordPhone);
			if(trim($ordShipName)!='' || trim($ordShipLastName)!='' || trim($ordShipAddress)!=''){
				print whv('Sname', trim($ordShipName.' '.$ordShipLastName)) . whv('Saddr1', $ordShipAddress) . whv('Saddr2', $ordShipAddress2) . whv('Scity', $ordShipCity) . whv('Sstate', $ordShipState) . whv('Szip', $ordShipZip) . whv('Scountry', $ordShipCountry);
			}
			if($demomode) print whv('Result', '1');
		}elseif($ordPayProvider=="13"){ // Auth.net AIM
			print '<div id="ppcoverdiv" class="ectopaque" style="display:none;text-align:center"><img src="images/preloader.gif" style="margin-top:250px" class="ectpreloader"></div>';
			print '<form method="post" action="cart'.$GLOBALS['extension'].'" onsubmit="return isvalidcard(this)">';
			print whv('mode', 'authorize') . whv('method', '13') . whv('ordernumber', $orderid) . whv('description', substr($descstr,0,254));
		}elseif($ordPayProvider=="14"){ // Custom Pay Provider
			include './vsadmin/inc/customppsend.php';
		}elseif($ordPayProvider=='15'){ // Netbanx
			$sequence=rand(1000000,9999999);
			print '<form method="post" action="https://pay.netbanx.com/' . $data1 . '">';
			print whv('nbx_merchant_reference', $orderid.'.' . $sequence) . whv('nbx_payment_amount', (int)($grandtotal*100)) . whv('nbx_currency_code', $countryCurrency) . whv('nbx_cardholder_name', trim($ordName.' '.$ordLastName)) . whv('nbx_email', $ordEmail) . whv('nbx_postcode', $ordZip);
			print whv('nbx_return_url', $storeurl.'categories'.$GLOBALS['extension']);
			print whv('nbx_success_url', $storeurl.'vsadmin/ncconfirm.php');
			if($data2!='') print whv('nbx_checksum', sha1((int)($grandtotal*100).$countryCurrency.$orderid.'.'.$sequence.$data2));
		}elseif($ordPayProvider=='16'){ // Linkpoint
			$lpsubtotal=round($totalgoods - $totaldiscounts, 2);
			$lpshipping=round(($shipping + $handling) - $freeshipamnt, 2);
			$lptax=round($stateTax + $countryTax, 2);
			$sequence='.'.time();
			if($data3!='')
				$payurl='https://connect.'.($demomode?'merchanttest.':'').'firstdataglobalgateway.com/IPGConnect/gateway/processing';
			else
				$payurl='https://www.'.($demomode?'staging.':'').'linkpointcentral.com/lpc/servlet/lppay';
			print '<form action="' . $payurl . '" method="post"' . ($data2=='1'?' onsubmit="return isvalidcard(this)"':'') . '>';
			print whv('storename', $data1) . whv('mode', 'payonly') . whv('ponumber', $orderid) . whv('oid', $orderid.$sequence) . whv('responseURL', $storeurl.'thanks'.$GLOBALS['extension']);
			print whv('subtotal', number_format($lpsubtotal,2,'.','')) . whv('chargetotal', number_format($lpsubtotal+$lpshipping+$lptax,2,'.','')) . whv('shipping', number_format($lpshipping,2,'.','')) . whv('tax', number_format($lptax,2,'.',''));
			if($data2!='1') print whv('bname', trim($ordName.' '.$ordLastName));
			print whv('baddr1', $ordAddress) . whv('baddr2', $ordAddress2) . whv('bcity', $ordCity);
			if($countryID==1 && $stateAbbrev!='') print whv('bstate', $stateAbbrev); else print whv('bstate2', $ordState);
			print whv('bzip', $ordZip) . whv('bcountry', $countryCode) . whv('email', $ordEmail) . whv('phone', $ordPhone);
			print whv('txntype', $ppmethod==1?'preauth':'sale');
			if(trim($ordShipName)!='' || trim($ordShipLastName)!='' || trim($ordShipAddress)!=''){
				print whv('sname', trim($ordShipName.' '.$ordShipLastName)) . whv('saddr1', $ordShipAddress) . whv('saddr2', $ordShipAddress2) . whv('scity', $ordShipCity) . whv('sstate', $ordShipState) . whv('szip', $ordShipZip) . whv('scountry', $shipCountryCode);
			}
			if($data3!=''){
				$formattedDate=gmdate('Y:m:d-H:i:s');
				$str=$data1 . $formattedDate . number_format($lpsubtotal+$lpshipping+$lptax,2,'.','') . $data3;
				$hex_str='';
				for($i=0; $i < strlen($str); $i++){
					$hex_str.=dechex(ord($str[$i]));
				}
				print whv('txndatetime' ,$formattedDate);
				ect_query("UPDATE orders SET ordPrivateStatus='" . escape_string($formattedDate) . "' WHERE ordID='" . escape_string($orderid) . "'") or ect_error();
				print whv('timezone', 'UTC');
				print whv('hash', hash('sha256', $hex_str));
			}
		}elseif($ordPayProvider=="18"){ // PayPal Direct Payment
			$php_version=explode('.', phpversion());
			if(((int)$php_version[0])<5) print 'Please note, you are using PHP 4 and PHP 5 is required for PayPal.';
			print '<form method="post" action="cart'.$GLOBALS['extension'].'" onsubmit="return isvalidcard(this)">';
			print whv('mode', 'authorize') . whv('method', '18') . whv('ordernumber', $orderid) . whv('description', substr($descstr,0,254));
		}elseif($ordPayProvider=="19"){ // PayPal Express Payment
			$php_version=explode('.', phpversion());
			if(((int)$php_version[0])<5) print 'Please note, you are using PHP 4 and PHP 5 is required for PayPal.';
			print '<form method="post" action="thanks'.$GLOBALS['extension'].'" onsubmit="return docheckform(this)">';
			print whv('token', $token) . whv('method', 'paypalexpress') . whv('ordernumber', $orderid) . whv('payerid', $payerid) . whv('email', $ordEmail);
		}elseif($ordPayProvider=='21'){ // Amazon Pay
			print '<form method="post" action="thanks'.$GLOBALS['extension'].'" onsubmit="return docheckform(this)">';
			print whv('pprov', '21') . whv('ordernumber', $orderid) . whv('amzrefid', $amzrefid_);
			$sSQL="UPDATE orders SET ordTransID='" . escape_string($amzrefid_) . "' WHERE ordID='" . escape_string($orderid) . "' AND ordSessionID='" . escape_string($thesessionid) . "'";
			if($amazonpayment) ect_query($sSQL) or ect_error();
		}elseif($ordPayProvider=='22'){ // Old PayPal Advanced
			print '<form method="post" action="cart'.$GLOBALS['extension'].'">';
			print whv('mode', 'authorize') . whv('method', '22') . whv('ordernumber', $orderid) . whv('sessionid', $thesessionid);
		}elseif($ordPayProvider=='23'){ // Stripe.com
			if($ppflag1==2){
				$customerid='';
				$sXML='name=' . urlencode(trim($ordName.' '.$ordLastName)) .
					'&address[postal_code]=' . urlencode($ordZip) .
					'&address[city]=' . urlencode($ordCity) .
					'&address[country]=' . urlencode($countryCode) .
					'&address[line1]=' . urlencode($ordAddress) .
					($ordAddress2!=''?'&address[line2]=' . urlencode($ordAddress):'') .
					'&address[state]=' . urlencode($ordState) .
					'&email=' . urlencode($ordEmail) .
					'&phone=' . urlencode($ordPhone);
				$GLOBALS['xmlfnheaders']=array("User-Agent: Stripe/v1 RubyBindings/1.12.0","Authorization: Bearer ".$data1,"Content-Type: application/x-www-form-urlencoded");
				if(callcurlfunction('https://api.stripe.com/v1/customers', $sXML, $jres, '', $errormsg, FALSE)){
					$piarray=json_decode($jres);
					$customerid=@$piarray->{'id'};
				}
				$sXML='amount=' . round($grandtotal*100) . '&currency=' . strtolower($countryCurrency) . '&metadata[order_id]=' . $orderid . '&description=' . $orderid . ', ' . urlencode(trim_($ordName . ' ' . $ordLastName)) .
					($ppmethod==1?'&payment_method_options[card[capture_method]]=manual':'') . 
					($customerid!=''?'&customer=' . $customerid:'');
				if(($ppbits&1)==1 || $ppbits==0) $sXML.='&payment_method_types[]=card';
				if(($ppbits&2)==2) $sXML.='&payment_method_types[]=ideal';
				if(($ppbits&4)==4) $sXML.='&payment_method_types[]=bancontact';
				if(($ppbits&8)==8) $sXML.='&payment_method_types[]=giropay';
				if(($ppbits&16)==16) $sXML.='&payment_method_types[]=p24';
				if(($ppbits&32)==32) $sXML.='&payment_method_types[]=eps';
				if(($ppbits&64)==64) $sXML.='&payment_method_types[]=fpx';
				if(($ppbits&128)==128) $sXML.='&payment_method_types[]=bacs_debit';
				if(($ppbits&256)==256) $sXML.='&payment_method_types[]=klarna';
				if(($ppbits&512)==512 && $grandtotal>=50) $sXML.='&payment_method_types[]=affirm';
				//if(($ppbits&1024)==1024) $sXML.='&payment_method_types[]=sofort';
				$GLOBALS['xmlfnheaders']=array("User-Agent: Stripe/v1 RubyBindings/1.12.0","Authorization: Bearer ".$data1,"Content-Type: application/x-www-form-urlencoded");
				if(callcurlfunction('https://api.stripe.com/v1/payment_intents', $sXML, $jres, '', $errormsg, FALSE)){
					$piarray=json_decode($jres);
					$paymentintent=@$piarray->{'client_secret'};
					if($paymentintent==''){
						$success=FALSE;
						$stripeerror=@$piarray->{'error'}->{'message'};
						if($stripeerror!='') $errormsg=$stripeerror;
					}else{
						$sSQL="UPDATE orders SET ordTransSession='" . escape_string($paymentintent) . "' WHERE ordID='" . escape_string($orderid) . "' AND ordSessionID='" . escape_string($thesessionid) . "'";
						ect_query($sSQL) or ect_error();
					}
				}
				print '<script src="https://js.stripe.com/v3/"></script><form id="payment-form" data-secret="' . $paymentintent . '">';
			}elseif($ppflag1==0){
				print '<form method="post" action="thanks'.$GLOBALS['extension'].'">';
				print whv('pprov', '23') . whv('ordernumber', $orderid);
			}else{
				print '<form method="post" action="thanks'.$GLOBALS['extension'].'">';
				print whv('method', 'striperedirect');
				$sXML='';
				if(($ppbits&1)==1 || $ppbits==0) $sXML.='payment_method_types[]=card';
				if(($ppbits&2)==2) $sXML.=($sXML!=''?'&':'').'payment_method_types[]=ideal';
				if(($ppbits&4)==4) $sXML.=($sXML!=''?'&':'').'payment_method_types[]=bancontact';
				if(($ppbits&8)==8) $sXML.=($sXML!=''?'&':'').'payment_method_types[]=giropay';
				if(($ppbits&16)==16) $sXML.=($sXML!=''?'&':'').'payment_method_types[]=p24';
				if(($ppbits&32)==32) $sXML.=($sXML!=''?'&':'').'payment_method_types[]=eps';
				if(($ppbits&64)==64) $sXML.=($sXML!=''?'&':'').'payment_method_types[]=fpx';
				if(($ppbits&128)==128) $sXML.=($sXML!=''?'&':'').'payment_method_types[]=bacs_debit';
				if(($ppbits&512)==512 && $grandtotal>=50) $sXML.=($sXML!=''?'&':'').'payment_method_types[]=affirm';
				//if(($ppbits&1024)==1024) $sXML.=($sXML!=''?'&':'').'payment_method_types[]=sofort';
				$sXML.='&line_items[0][price_data][product_data][name]=Cart Items Total' .
					'&line_items[0][price_data][unit_amount]=' . round($grandtotal*100) .
					'&line_items[0][price_data][currency]='.strtolower($countryCurrency) . 
					'&line_items[0][quantity]=1';
				$sSQL='SELECT cartID,cartProdID,cartProdName,cartProdPrice,cartQuantity FROM cart WHERE cartCompleted=0 AND ' . getsessionsql();
				$result=ect_query($sSQL) or ect_error();
				$itemno=1;
				if(ect_num_rows($result)<32){
					while($rs=ect_fetch_assoc($result)){
						$sSQL='SELECT coOptGroup,coCartOption FROM cartoptions WHERE coCartID=' . $rs['cartID'];
						$result2=ect_query($sSQL) or ect_error();
						$optionnames='';
						while($rs2=ect_fetch_assoc($result2)){
							$optionnames.=' ' . $rs2['coCartOption'] . ',';
						}
						$optionnames=substr(trim($optionnames),0,-1);
						$sXML.='&line_items[' . $itemno . '][price_data][product_data][name]=' . urlencode(substr($rs['cartProdName'] . ($optionnames!=''?' ('.$optionnames.')':''), 0, 255)) .
							'&line_items[' . $itemno . '][price_data][unit_amount]=0' .
							'&line_items[' . $itemno . '][price_data][currency]='.strtolower($countryCurrency) . 
							'&line_items[' . $itemno . '][quantity]=' . $rs['cartQuantity'];
						$sSQL="SELECT imageSrc FROM productimages WHERE imageProduct='" . escape_string($rs['cartProdID']) . "' AND imageSrc NOT LIKE '% %' ORDER BY imageType,imageNumber";
						$result2=ect_query($sSQL) or ect_error();
						$optionnames='';
						if($rs2=ect_fetch_assoc($result2)){
							$sXML.='&line_items[' . $itemno . '][price_data][product_data][images][]=' . urlencode((strpos($rs2['imageSrc'],'//')!==FALSE ? '' : $storeurl) . $rs2['imageSrc']);
						}
						$itemno++;
					}
				}
				$sXML.='&payment_intent_data[capture_method]=' . ($ppmethod==1?'manual':'automatic') .
					'&payment_intent_data[metadata[order_id]]=' . $orderid .
					'&payment_intent_data[description]=' . $orderid . ', ' . urlencode(trim_($ordName . ' ' . $ordLastName)) .
					'&billing_address_collection=auto' .
					'&customer_email=' . urlencode($ordEmail) .
					'&mode=payment' .
					'&success_url=' . $storeurlssl . urlencode('thanks'.$GLOBALS['extension'].'?method=stripe&sid={CHECKOUT_SESSION_ID}&soid=' . $orderid) .
					'&cancel_url=' . $storeurlssl . 'cart'.$GLOBALS['extension'];
				$GLOBALS['xmlfnheaders']=array("User-Agent: Stripe/v1 RubyBindings/1.12.0","Authorization: Bearer ".$data1,"Content-Type: application/x-www-form-urlencoded");
				if(callcurlfunction('https://api.stripe.com/v1/checkout/sessions', $sXML, $jres, '', $errormsg, FALSE)){
					$jsarray=json_decode((string)$jres);
					if(@$jsarray->{'error'}){
						$success=FALSE;
						$errormsg=$jsarray->{'error'}->{'message'};
					}else{
						$stripeid=$jsarray->{'id'};
						$sSQL="UPDATE orders SET ordTransSession='" . escape_string($stripeid) . "' WHERE ordID='" . escape_string($orderid) . "' AND ordSessionID='" . escape_string($thesessionid) . "'";
						ect_query($sSQL) or ect_error();
						print whv('url',$jsarray->{'url'});
					}
				}else{
					$success=FALSE;
				}
			}
		}elseif($ordPayProvider=='24'){ // Opayo
			$twoletterstateerr="Please Enter a 2 Letter State Code for US States";
			function spchkalphanum($ectinstr){
				$ectinstr=preg_replace('/[^a-zA-Z0-9]/', '', $ectinstr);
				return($ectinstr);
			}
			function randomise(){
				list($usec, $sec)=explode(' ', microtime());
				return (float) $sec + ((float) $usec * 100000);
			}
			$ordAddress=substr(@$ordAddress,0,50);
			$ordAddress2=substr(@$ordAddress2,0,50);
			$ordShipAddress=substr(@$ordShipAddress,0,50);
			$ordShipAddress2=substr(@$ordShipAddress2,0,50);
			if(trim(@$ordShipAddress)==''){
				$ordShipName=@$ordName;
				$ordShipLastName=@$ordLastName;
				$ordShipAddress=@$ordAddress;
				$ordShipAddress2=@$ordAddress2;
				$ordShipCity=@$ordCity;
				$ordShipState=@$ordState;
				$ordShipZip=@$ordZip;
				$ordShipCountry=@$ordCountry;
				$ordShipPhone=@$ordPhone;
				$ordShipExtra1=@$ordExtra1;
				$ordShipExtra2=@$ordExtra2;
				$shipStateAbbrev=@$stateAbbrev;
			}
			srand(time());
			$randid=rand(1000000,9999999);
			$sSQL='SELECT cartID,cartProdID,cartProdName,cartProdPrice,cartQuantity FROM cart WHERE cartCompleted=0 AND ' . getsessionsql();
			$result=ect_query($sSQL) or ect_error();
			$index=0;
			$thecart='';
			while($rs=ect_fetch_assoc($result)){
				$sSQL='SELECT SUM(coPriceDiff) as totpricediff FROM cartoptions WHERE coCartID=' . $rs['cartID'];
				$result2=ect_query($sSQL) or ect_error();
				$rs2=ect_fetch_assoc($result2);
				$totpricediff=(float)$rs2['totpricediff'];
				$thecart .= ':[' . str_replace(array(':','&'),'',$rs['cartProdID']) . ']' . strip_tags(str_replace(array(':','&'),'',$rs['cartProdName'])) . ':' . $rs['cartQuantity'] . ':' . number_format($rs['cartProdPrice']+$totpricediff,2,'.','') . ':0.00:' . number_format($rs['cartProdPrice']+$totpricediff,2,'.','') . ':' . number_format(($rs['cartProdPrice']+$totpricediff)*$rs['cartQuantity'],2,'.','');
				$index++;
			}
			if($stateTax + $countryTax > 0){
				$thecart.=':Taxes:---:---:---:---:' . number_format($stateTax + $countryTax,2,'.','');
				$index++;
			}
			if($totaldiscounts > 0){
				$thecart.=':Discounts:---:---:---:---:' . number_format(0 - $totaldiscounts,2,'.','');
				$index++;
			}
			if(($shipping + $handling) - $freeshipamnt){
				$thecart.=':Delivery:---:---:---:---:' . number_format(($shipping + $handling) - $freeshipamnt,2,'.','');
				$index++;
			}
			$thecart=str_replace('&pound;','£',$thecart);
			$thecart=($index.$thecart);
			$spzipcode=trim($ordZip);
			if($spzipcode=='') $spzipcode='NA';
			$spshipzipcode=trim($ordShipZip);
			if($spshipzipcode=='') $spshipzipcode='NA';
			$stuff='VendorTxCode=' . $orderid . '-' . $randid;
			$stuff.='&Amount=' . number_format($grandtotal,2,'.','') . '&Currency=' . $countryCurrency . '&Description=' . substr($descstr, 0, 99);
			$stuff.='&Basket=' . $thecart . '&SuccessURL=' . $storeurl . 'thanks'.$GLOBALS['extension'].'&FailureURL=' . $storeurl . 'thanks'.$GLOBALS['extension'];
			$stuff.=(@$GLOBALS['nosagepayemail']?'':'&CustomerEMail=' . $ordEmail) . '&CustomerName=' . trim($ordName.' '.@$ordLastName);
			$stuff.='&ContactNumber=' . spchkalphanum($ordPhone) . (@$GLOBALS['nosagepayemail']?'':'&VendorEMail=' . $emailAddr);
			if(@$GLOBALS['usefirstlastname']){
				$stuff.='&BillingFirstnames=' . $ordName . '&BillingSurname=' . $ordLastName;
			}elseif(strpos(trim($ordName), ' ')!==FALSE){
				$namearr=explode(' ',trim($ordName),2);
				$stuff.='&BillingFirstnames=' . $namearr[0] . '&BillingSurname=' . @$namearr[1];
			}else
				$stuff.='&BillingFirstnames=&BillingSurname=' . $ordName;
			$stuff.='&BillingAddress1=' . $ordAddress;
			if(trim($ordAddress2)!='') $stuff.='&BillingAddress2=' . $ordAddress2;
			$stuff.='&BillingCity=' . $ordCity;
			if($countryID==1){
				$spstatefield=strtoupper($stateAbbrev!=''?$stateAbbrev:$ordState);
				if(strlen($spstatefield)!=2){
					$success=FALSE;
					$errormsg=$twoletterstateerr . '<br><div style="text-align:center"><input type="button" class="ectbutton" onclick="history.go(-1)" value="'.$GLOBALS['xxGoBack'].'" /></div>';
				}
				$stuff.='&BillingState=' . $spstatefield;
			}
			$stuff.='&BillingCountry=' . $countryCode . '&BillingPostCode=' . $spzipcode . '&BillingPhone=' . spchkalphanum($ordPhone);
			if(@$GLOBALS['usefirstlastname']&&$ordShipLastName!=''){
				$stuff.='&DeliveryFirstnames=' . $ordShipName . '&DeliverySurname=' . $ordShipLastName;
			}elseif(strpos(trim($ordShipName), ' ')!==FALSE){
				$namearr=explode(' ',trim($ordShipName),2);
				$stuff.='&DeliveryFirstnames=' . $namearr[0] . '&DeliverySurname=' . @$namearr[1];
			}else
				$stuff.='&DeliveryFirstnames=' . $ordShipName . '&DeliverySurname=' . $ordShipName;
			$stuff.='&DeliveryAddress1=' . $ordShipAddress;
			if(trim($ordShipAddress2)!='') $stuff.='&DeliveryAddress2=' . $ordShipAddress2;
			$stuff.='&DeliveryCity=' . $ordShipCity;
			if($shipCountryID==1){
				$spstatefield=strtoupper($shipStateAbbrev!=''?$shipStateAbbrev:$ordShipState);
				if(strlen($spstatefield)!=2){
					$success=FALSE;
					$errormsg=$twoletterstateerr . '<br><div style="text-align:center"><input type="button" class="ectbutton" onclick="history.go(-1)" value="'.$GLOBALS['xxGoBack'].'" /></div>';
				}
				$stuff.='&DeliveryState=' . $spstatefield;
			}
			$stuff.='&DeliveryCountry=' . $shipCountryCode . '&DeliveryPostCode=' . $spshipzipcode . '&DeliveryPhone=' . spchkalphanum($ordShipPhone);
			$stuff.='&ReferrerID=7B0AD331-0388-44EA-BE3A-D05D3FB9FE28';
			function encryptAes($string, $key){
				return '@' . bin2hex(openssl_encrypt($string, 'AES-128-CBC', $key, OPENSSL_PKCS1_PADDING, $key));
			}
			if(strtolower($GLOBALS['adminencoding'])=='utf-8') $stuff=mb_convert_encoding($stuff,'ISO-8859-1','UTF-8');
			$crypt=encryptAes($stuff,$data2);
			if($ppflag1==0){
				print '<form action="https://' . ($demomode?'sandbox':'live') . '.opayo.eu.elavon.com/gateway/service/vspform-register.vsp" method="post" id="form1">' . "\r\n";
				print whv('VPSProtocol','4.00') . whv('TxType',$ppmethod==1?'DEFERRED':'PAYMENT') . whv('Vendor',$data1) . whv('Crypt',$crypt);
			}else{
				$hashchk=strtolower(md5($orderid.$GLOBALS['adminSecret'].'opayoisrubbish'));
				$NextURL=$SecurityKey=$Status=$StatusDetail='';
				$stuff.='&VPSProtocol=4.00&TxType=' . ($ppmethod==1?'DEFERRED':'PAYMENT') . '&Vendor=' . $data1 .
					'&Profile=LOW&Apply3DSecure=1' .
					'&NotificationURL=' . $storeurlssl . 'vsadmin/ajaxservice.php?opayo='.$hashchk;
				if(callcurlfunction('https://' . ($demomode?'sandbox':'live') . '.opayo.eu.elavon.com/gateway/service/vspserver-register.vsp',$stuff,$res,'',$errormsg,FALSE)){
					$resarray=explode("\n",$res);
					foreach($resarray as $key=>$value){
						$param=explode('=',$value,2);
						if($param[0]=='NextURL') $NextURL=trim($param[1]);
						elseif($param[0]=='Status') $Status=trim($param[1]);
						elseif($param[0]=='SecurityKey') $SecurityKey=trim($param[1]);
						elseif($param[0]=='StatusDetail') $errormsg=trim($param[1]);
					}
					if($Status=='OK'){
						$sSQL="UPDATE orders SET ordTransSession='" . escape_string($SecurityKey) . "' WHERE ordID='" . escape_string($orderid) . "'";
						ect_query($sSQL) or ect_error();
					}else
						$success=FALSE;
				}else
					$success=FALSE;
			}
		}elseif($ordPayProvider=='25'||$ordPayProvider=='26'){ // Braintree
			print '<form method="post" id="ectcheckoutform" action="thanks'.$GLOBALS['extension'].'"' . ($ordPayProvider=='26'?' onsubmit="return docheckform(this)"':'') . '>';
			print whv('mode', 'authorize') . whv('method',$ordPayProvider) . whv('ordernumber', $orderid) . whv('sessionid', $thesessionid);
			writehiddenidvar('payment_method_nonce',getpost('nonce'));
		}elseif($ordPayProvider=='27'){ // PayPal Checkout
			print '<div id="ppcoverdiv" class="ectopaque" style="display:none;text-align:center"><img src="images/preloader.gif" style="margin-top:250px" class="ectpreloader"></div>';
			if(getget('action')=='termpp'&&$ppflag1==1){  // Express Checkout
				$sSQL="UPDATE orders SET ordTransID='" . escape_string(getget('paymentID')) . "',ordTransSession='' WHERE ordID='" . escape_string($orderid) . "'";
				ect_query($sSQL) or ect_error();
				print '<form method="post" id="ectcheckoutform" action="thanks'.$GLOBALS['extension'].'?action=ppexpress" onsubmit="return docheckform(this)">';
				print whv('ordid',$orderid) . whv('paymentID',getget('paymentID'));
			}elseif($ppflag2==1){ // Advanced Checkout
				$GLOBALS['client_token']='';
				if($access_token=paypalaccesstoken($data1,$data2,$demomode,$data6,$errormsg)){
					$GLOBALS['xmlfnheaders']=array("Authorization: Bearer ".$access_token,"Content-Type: application/json","PayPal-Partner-Attribution-Id: EcommerceTemplates_Ecom_PPCP");
					if(callcurlfunction('https://api-m.' . ($demomode?'sandbox.':'') . 'paypal.com/v1/identity/generate-token', '{}', $jres, '', $errormsg, FALSE)){
						$jsarray=json_decode((string)$jres);
						$GLOBALS['client_token']=@$jsarray->{'client_token'};
					}
					if($GLOBALS['client_token']==''){
						$success=FALSE;
						$errormsg=$jres;
					}
				}
			}
		}elseif($ordPayProvider=='28'){ // SquareUp
			print '<form method="post" id="ectcheckoutform" action="thanks'.$GLOBALS['extension'].'">';
			print whv('mode', 'authorize') . whv('method',28) . whv('ordernumber', $orderid) . whv('sessionid', $thesessionid);
			writehiddenidvar('payment_method_nonce','');
			writehiddenidvar('txnid','');
		}elseif($ordPayProvider=='29'){ // NMI
			if($data2!=''){ ?>
<form method="post" action="thanks<?php print $GLOBALS['extension']?>" onsubmit="return isvalidcard(this)">
<?php
				print whv('mode','authorize') . whv('method','29') . whv('ordernumber',$orderid);
			}else{
				$GLOBALS['xmlfnheaders']=array('Content-Type: text/xml');
				$sXML='<?xml version="1.0" encoding="UTF-8"?><sale>' . vrxmltag('api-key',$data1);
				$sXML.=vrxmltag('redirect-url',$storeurlssl.'thanks'.$GLOBALS['extension'].'?mode=authorize&method=29&ordernumber='.$orderid);
				$sXML.=vrxmltag('amount',$grandtotal) . vrxmltag('ip-address',$GLOBALS['REMOTE_ADDR']) . vrxmltag('currency',$countryCurrency);
				$sXML.=vrxmltag('order-id',$orderid);
				$sXML.=vrxmltag('order-description',substr($descstr, 0, 99));
				$sXML.=vrxmltag('tax-amount',number_format($stateTax+$countryTax,2,'.',''));
				$sXML.=vrxmltag('shipping-amount',number_format(($shipping + $handling) - $freeshipamnt,2,'.',''));
				$sXML.='<billing>';
					splitname(trim($ordName.' '.$ordLastName), $firstname, $lastname);
					$sXML.=vrxmltag('first-name',$firstname) . vrxmltag('last-name',$lastname);
					$sXML.=vrxmltag('address1',$ordAddress) . vrxmltag('address2',$ordAddress2) . vrxmltag('city',$ordCity) . vrxmltag('state',$ordState) . vrxmltag('postal',$ordZip) . vrxmltag('country',$countryCode);
					$sXML.=vrxmltag('email',$ordEmail) . vrxmltag('phone',$ordPhone);
				$sXML.='</billing></sale>';
				if(callcurlfunction('https://secure.networkmerchants.com/api/v2/three-step',$sXML,$data,'',$errormsg,FALSE)){
					$gwResponse = @new SimpleXMLElement($data);
					if((string)$gwResponse->result==1)
						print '<form method="post" action="' . $gwResponse->{'form-url'} . '" onsubmit="return isvalidcard(this)">';
					else{
						$success=FALSE;
						$errormsg=$gwResponse->{'result-text'};
					}
				}else
					$success=FALSE;
			}
		}elseif($ordPayProvider=='30'){ // eWay
			$GLOBALS['xmlfnheaders']=array('Content-Type: application/json');
			$GLOBALS['xmlfnuser']=$data1;
			$GLOBALS['xmlfnpassword']=$data2;
			splitname(trim($ordName.' '.$ordLastName), $firstname, $lastname);
			$sjson='{"Customer":{ 
					"FirstName":' . json_encode($firstname) . ',"LastName":' . json_encode($lastname) . ', 
					"Street1":' . json_encode($ordAddress) . ',"Street2":' . json_encode($ordAddress2) . ', 
					"City":' . json_encode($ordCity) . ',"State":' . json_encode($ordState) . ',"PostalCode":' . json_encode($ordZip) . ',"Country":' . json_encode(strtolower($countryCode)) . ', 
					"Phone":' . json_encode($ordPhone) . ',"Email":' . json_encode($ordEmail) . ',
				}, 
				"Payment":{
					"TotalAmount":' . ($grandtotal*100) . ',"InvoiceReference":"' . $orderid . '","CurrencyCode":"' . $countryCurrency . '"
				},
				"RedirectUrl":"' . $storeurlssl . 'thanks' . $GLOBALS['extension'] . '","Method":"ProcessPayment","TransactionType":"Purchase"}';
			if($success=callcurlfunction('https://api.' . ($demomode?'sandbox.':'') . 'ewaypayments.com/AccessCodes', $sjson, $jres, '', $errormsg, TRUE)){
				$jsarray=json_decode((string)$jres);
				$accesscode=@$jsarray->{'AccessCode'};
				$formactionurl=@$jsarray->{'FormActionURL'};
				$formerrors=@$jsarray->{'Errors'};
?>			<form method="POST" action="<?php print $formactionurl?>" id="payment_form" onsubmit="return isvalidcard(this)">
					<input type="hidden" name="EWAY_ACCESSCODE" value="<?php print $accesscode?>" />
					<input type="hidden" name="EWAY_PAYMENTTYPE" value="Credit Card" />
<?php			if($formerrors!=''){
					$success=FALSE;
					$errormsg=$formerrors;
				}
			}
		}elseif($ordPayProvider=='31'){ // Pay360 ?>
<div id="ppcoverdiv" class="ectopaque" style="display:none;text-align:center"><img src="images/preloader.gif" style="margin-top:250px" class="ectpreloader"></div>
<script>
var p3ajaxobj;
function ppajaxcallback(){
	if(p3ajaxobj.readyState==4){
		var restxt=p3ajaxobj.responseText;
		if(restxt.substr(0,1)=='1')
			document.location=restxt.substr(2);
		else
			alert(restxt.substr(2));
	}
}
function payprovscript(){
	document.getElementById('ppcoverdiv').style.display='';
	p3ajaxobj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
	p3ajaxobj.onreadystatechange=ppajaxcallback;
	p3ajaxobj.open("GET", "vsadmin/ajaxservice.php?action=pay360&orderid=<?php print $orderid?>", true);
	p3ajaxobj.send(null);
}
</script>
<?php	}elseif($ordPayProvider=='32'){ // Global Payments
			$timestamp=gmdate("YmdHis", time());
			$grandtotalrnd=round($grandtotal*100);
			$gporderid=$orderid.'-'.rand(1000,9999);
			$hashstring=$timestamp.'.'.$data1.'.'.$gporderid.'.'.$grandtotalrnd.'.'.$countryCurrency;
			$hashstring=sha1(sha1($hashstring).'.'.$data2);
?>
<script>
function payprovscript(){
	document.getElementById('gpiform').submit();
	document.getElementById('gpicoverdiv').style.display='';
}
</script>
<div id="gpicoverdiv" class="ectopaque" style="display:none">
	<iframe id="gpiframe" name="gpiframe" style="margin-top:100px;width:600px;height:580px;border:none"></iframe>
</div>
			<form id="gpiform" action="https://pay.<?php print $demomode?'sandbox.':''?>realexpayments.com/pay" method="POST" target="gpiframe">
			<input type="hidden" name="TIMESTAMP" value="<?php print $timestamp?>">
			<input type="hidden" name="MERCHANT_ID" value="<?php print $data1?>">
			<input type="hidden" name="ORDER_ID" value="<?php print $gporderid?>">
			<input type="hidden" name="AMOUNT" value="<?php print $grandtotalrnd?>">
			<input type="hidden" name="CURRENCY" value="<?php print $countryCurrency?>">
			<input type="hidden" name="AUTO_SETTLE_FLAG" value="<?php print $ppmethod?>">
			<input type="hidden" name="HPP_VERSION" value="2">
			<input type="hidden" name="HPP_CHANNEL" value="ECOM">
			<input type="hidden" name="HPP_CUSTOMER_EMAIL" value="<?php print htmlspecials($ordEmail)?>">
<?php	if(FALSE){ ?>
			<input type="hidden" name="HPP_CUSTOMER_PHONENUMBER_MOBILE" value="<?php print htmlspecials($ordPhone)?>">
<?php	} ?>
			<input type="hidden" name="HPP_BILLING_STREET1" value="<?php print htmlspecials($ordAddress)?>">
			<input type="hidden" name="HPP_BILLING_STREET2" value="<?php print htmlspecials($ordAddress2)?>">
			<input type="hidden" name="HPP_BILLING_CITY" value="<?php print htmlspecials($ordCity)?>">
<?php		if($countryCode=='US' || $countryCode=='CA') print whv('HPP_BILLING_STATE',getstateabbrev($ordState)); ?>
			<input type="hidden" name="HPP_BILLING_POSTALCODE" value="<?php print htmlspecials($ordZip)?>">
<?php		if($data3!='') print whv('ACCOUNT',$data3);
			$sSQL="SELECT countryNumCurrency FROM countries WHERE countryCode='" . escape_string($countryCode) . "'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)) print whv('HPP_BILLING_COUNTRY',$rs['countryNumCurrency']);
			if($shipCountryCode!=''&&$ordShipName!=''&&$ordShipAddress!=''){ ?>
			<input type="hidden" name="HPP_SHIPPING_STREET1" value="<?php print htmlspecials($ordShipAddress)?>">
			<input type="hidden" name="HPP_SHIPPING_STREET2" value="<?php print htmlspecials($ordShipAddress2)?>">
			<input type="hidden" name="HPP_SHIPPING_CITY" value="<?php print htmlspecials($ordShipCity)?>">
<?php			if($countryCode=='US' || $countryCode=='CA') print whv('HPP_SHIPPING_STATE',getstateabbrev($ordShipState)); ?>
			<input type="hidden" name="HPP_SHIPPING_POSTALCODE" value="<?php print htmlspecials($ordShipZip)?>">
<?php			$sSQL="SELECT countryNumCurrency FROM countries WHERE countryCode='" . escape_string($shipCountryCode) . "'";
				$result=ect_query($sSQL) or ect_error();
				if($rs=ect_fetch_assoc($result)) print whv('HPP_SHIPPING_COUNTRY',$rs['countryNumCurrency']);
			} ?>
			<input type="hidden" name="HPP_ADDRESS_MATCH_INDICATOR" value="FALSE">
			<input type="hidden" name="HPP_CHALLENGE_REQUEST_INDICATOR" value="NO_PREFERENCE">
			<input type="hidden" name="MERCHANT_RESPONSE_URL" value="<?php print $storeurlssl.'vsadmin/ajaxservice.php?action=globalpayments'?>">
			<input type="hidden" name="SHA1HASH" value="<?php print $hashstring?>">
<?php	}elseif($ordPayProvider=='33'){ // Checkout.com
			print '<form method="post" action="cart' . $GLOBALS['extension'] . '">';
			print whv('mode','authorize').whv('method',33).whv('ordernumber',$orderid);
		}elseif($ordPayProvider=='34'){ // Moneris Checkout
			srand(time());
			$sequence=rand(100000,999999);
			splitname(trim($ordName.' '.$ordLastName), $firstname, $lastname);
			$ticketno='';
			$sjson='{
				"store_id":' . json_encode($data1) . ',
				"api_token":' . json_encode($data2) . ',
				"checkout_id":' . json_encode($data3) . ',
				"txn_total":' . json_encode(number_format($grandtotal,2,'.','')) . ',
				"environment":' . json_encode($demomode?'qa':'prod') . ',
				"action":"preload",
				"order_no":' . json_encode($orderid.'_'.$sequence) . ',
				"contact_details":{
					"first_name":' . json_encode($firstname) . ',
					"last_name":' . json_encode($lastname) . ',
					"email":' . json_encode($ordEmail) . ',
					"phone":' . json_encode($ordPhone) . '
				},
				"shipping_details":{
					"address_1":' . json_encode($ordShipAddress) . ',
					"address_2":' . json_encode($ordShipAddress2) . ',
					"city":' . json_encode($ordShipCity) . ',
					"province":' . json_encode($ordShipState) . ',
					"country":' . json_encode($shipCountryCode) . ',
					"postal_code":' . json_encode($ordShipZip) . '
				},
				"billing_details":{
					"address_1":' . json_encode($ordAddress) . ',
					"address_2":' . json_encode($ordAddress2) . ',
					"city":' . json_encode($ordCity) . ',
					"province":' . json_encode($ordState) . ',
					"country":' . json_encode($countryCode) . ',
					"postal_code":' . json_encode($ordZip) . '
				}
			}';
			$monerisurl='https://gateway' . ($demomode?'t':'') . '.moneris.com/chktv2/request/request.php';
			//print "sjson: " . $sjson . "<hr>";
			if(callcurlfunction($monerisurl,$sjson,$jres,'',$errormsg,FALSE)){
				//print "jres: " . $jres . "<hr>";
				$jsarray=json_decode($jres);
				if($jsarray->{'response'}->{'success'}=='true'){
					$ticketno=$jsarray->{'response'}->{'ticket'};
					$sSQL="UPDATE orders SET ordTransID='" . escape_string($ticketno) . "' WHERE ordID='" . escape_string($orderid) . "'";
					ect_query($sSQL) or ect_error();
				}else{
					$errormsg='Could not initialize Moneris Checkout.';
					$success=FALSE;
				}
			}
		}
		eval('$payprovextraparams=@$payprovextraparams' . $ordPayProvider . ';');
		print $payprovextraparams;
	}
	if(!$returntocustomerdetails&&!(@$GLOBALS['nopriceanywhere']&&$success)){
		if(getpost('payprovider')=='27'&&($GLOBALS['adminPayLater'] & 128)==128){
			print '<div data-pp-message data-pp-placement="cart" data-pp-amount="" data-pp-style-layout="flex" data-pp-style-ratio="20x1" class="paylaterbanner cartpaylaterbanner"></div>';
		}
		if(@$GLOBALS['xxCoStp3']!='') print '<div class="checkoutsteps">' . $GLOBALS['xxCoStp3'] . '</div>'; ?>
			<div class="cart3details">
<?php	showcartresumeheader(3);
		if(($rgcpncode!='' || $ordPayProvider=='19' || $paypalcheckoutexpress) && (! $gotcpncode || @$cpnerror!='') && !@$GLOBALS['nogiftcertificate']){ ?>
			  <div class="cart3row">
				<div class="cobhl cobhl3"><?php if($rgcpncode!='' && ($ordPayProvider=='19' || $paypalcheckoutexpress) && ! $gotcpncode) print '<span style="color:#FF0000">' . $GLOBALS['xxCpnNoF'] . '</span>'; else print labeltxt($GLOBALS['xxGifCer'],'cpncode').':'?></div>
				<div class="cobll cobll3"><?php
			if(($ordPayProvider=='19' || $paypalcheckoutexpress) && ! $gotcpncode){
				print '<input type="text" class="ecttextinput cdformcoupon" name="cpncode" id="cpncode" size="20" value="' . htmlspecials($rgcpncode) . '" autocomplete="off" /> <input type="button" class="ectbutton" value="' . $GLOBALS['xxAppCpn'] . '" onclick="document.location=\'cart'.$GLOBALS['extension'].'?token='.getget('token').'&cpncode=\'+document.getElementById(\'cpncode\').value" />';
			}else{
				print $cpnerror;
				if($rgcpncode!='' && ! $gotcpncode) printf('<div class="expiredcoupon">' . str_replace('history.go(-%s)','checkcustdetails()',$GLOBALS['xxNoGfCr']) . '</div>',$rgcpncode);
			} ?></div>
			  </div>
<?php	}
		if(($ordPayProvider=='19' || $paypalcheckoutexpress) && @$GLOBALS['noadditionalinfo']!=TRUE){
			if(getpost('shipformaddinfo')!='') $ordAddInfo=getpost('shipformaddinfo'); ?>
			  <div class="cart3row">
				<div class="cobhl cobhl3"><?php print labeltxt($GLOBALS['xxAddInf'],'ordAddInfo')?></div>
				<div class="cobll cobll3"><textarea name="ordAddInfo" id="ordAddInfo" class="addinfo"<?php if(@$GLOBALS['addinfplaceholder']!='') print ' placeholder="' . placeholder($GLOBALS['addinfplaceholder']) . '"'?>><?php print htmlspecials(@$ordAddInfo)?></textarea></div>
			  </div>
<?php	}
		if($paypalcheckoutexpress){
			if(trim_(@$GLOBALS['extracheckoutfield1'])!=''){
				$checkoutfield1=(@$GLOBALS['extracheckoutfield1required'] ? $redstar : '') . labeltxt($GLOBALS['extracheckoutfield1'],'ordcheckoutextra1');
				$checkoutfield2=(@$GLOBALS['extracheckoutfield1html']!='' ? str_replace('ectfield','ordcheckoutextra1',$GLOBALS['extracheckoutfield1html']) : '<input type="text" name="ordcheckoutextra1" class="cdform2fixw ecttextinput cdformextraco1" id="ordcheckoutextra1" size="20" value="' . htmlspecials(@$ordCheckoutExtra1) . '" placeholder="' . placeholder($GLOBALS['extracheckoutfield1']) . '" autocomplete="false" aria-required="' . (@$GLOBALS['extracheckoutfield1required']?'true':'false') . '">');
?>				<div class="checkoutadditionals checkoutadds2col">
				  <div class="cobhl cobhl2 cdformtextraco1"><?php if(@$GLOBALS['extracheckoutfield1reverse']) print $checkoutfield2; else print $checkoutfield1 ?></div>
				  <div class="cobll cobll2 cdformextraco1"><?php if(@$GLOBALS['extracheckoutfield1reverse']) print $checkoutfield1; else print $checkoutfield2 ?></div>
				</div>
<?php
			}
			if(trim_(@$GLOBALS['extracheckoutfield2'])!=''){
				$checkoutfield1=(@$GLOBALS['extracheckoutfield2required'] ? $redstar : '') . labeltxt($GLOBALS['extracheckoutfield2'],'ordcheckoutextra2');
				$checkoutfield2=(@$GLOBALS['extracheckoutfield2html']!='' ? str_replace('ectfield','ordcheckoutextra2',$GLOBALS['extracheckoutfield2html']) : '<input type="text" name="ordcheckoutextra2" class="cdform2fixw ecttextinput cdformextraco1" id="ordcheckoutextra2" size="20" value="' . htmlspecials(@$ordCheckoutExtra2) . '" placeholder="' . placeholder($GLOBALS['extracheckoutfield2']) . '" autocomplete="false" aria-required="' . (@$GLOBALS['extracheckoutfield2required']?'true':'false') . '">');
?>				<div class="checkoutadditionals checkoutadds2col">
				  <div class="cobhl cobhl2 cdformtextraco2"><?php if(@$GLOBALS['extracheckoutfield2reverse']) print $checkoutfield2; else print $checkoutfield1 ?></div>
				  <div class="cobll cobll2 cdformextraco2"><?php if(@$GLOBALS['extracheckoutfield2reverse']) print $checkoutfield1; else print $checkoutfield2 ?></div>
				</div>
<?php
			}
		}
		if($backorder){ ?>
			  <div class="cart3row">
				<div class="cobll cart2column ectwarning cartbackorder"><?php print $GLOBALS['xxBakOrW']?></div>
			  </div>
<?php	}
		if(($warncheckspamfolder==TRUE || getpost('warncheckspamfolder')=='true') && @$noconfirmationemail!=TRUE){ ?>
			  <div class="cart3row">
				<div class="cobhl cobhl3"><?php print $GLOBALS['xxThkSub']?></div>
				<div class="cobll cobll3 ectwarning"><?php print $GLOBALS['xxSpmWrn']?></div>
			  </div>
<?php	}
		if($cpnmessage!=''){ ?>
			  <div class="cart3row cart3discountsrow">
				<div class="cobhl cobhl3"><?php print $GLOBALS['xxAppDs']?></div>
				<div class="cobll cobll3"><?php print $cpnmessage?></div>
			  </div>
<?php	} ?>
			  <div class="cart3row cart3totgoodsrow">
				<div class="cobhl cobhl3 cart3totgoodst"><?php print $GLOBALS['xxTotGds']?></div>
				<div class="cobll cobll3 cart3totgoods"><?php print FormatEuroCurrency($totalgoods)?>
<script><?php print $GLOBALS['wpjavascriptcomments']?>/* <![CDATA[ */
function updateshiprate(obj,theselector){
	if(obj.value!=''){
		document.getElementById("shipselectoridx").value=theselector;
		document.getElementById("shipselectoraction").value="selector";
		if(document.getElementById('ordAddInfo')) document.getElementById("shipformaddinfo").value=document.getElementById('ordAddInfo').value;
		document.forms.shipform.submit();
	}
}
function selaltrate(id){
	document.getElementById('altrates').value=id;
	document.getElementById('shipselectoraction').value='altrates';
	document.forms.shipform.submit();
}
function setchangeflag(tisset,tname){
	if(tname=='w')
		document.getElementById('willpickup').value=tisset?'Y':'';
	else
		document.getElementById('changeaction').value=tname+(tisset?'y':'n');
	document.getElementById('shipselectoraction').value='altrates';
	document.forms.shipform.submit();
}
<?php	if(@$GLOBALS['closeorderimmediately']){
		$_SESSION['sessionid']=$thesessionid; ?>
function docloseorder(){
	ajaxobj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
	ajaxobj.open("GET", "vsadmin/ajaxservice.php?action=clord", false);
	ajaxobj.send(null);
}
<?php	}
	if(@$adminAltRates==2){
		$sSQL='SELECT altrateid FROM alternaterates WHERE usealtmethod'.$international.'<>0 AND altrateid<>'.$shipType.' ORDER BY altrateorder'.$international.',altrateid';
		$result=ect_query($sSQL) or ect_error();
		if(ect_num_rows($result)>0){
			print 'var extraship=[';
			$addcomma='';
			while($rs=ect_fetch_assoc($result)){
				print $addcomma . $rs['altrateid'];
				$addcomma=',';
			}
			print "];\r\n" ?>
function acajaxcallback(){
	if(ajaxobj.readyState==4){
		var restxt=ajaxobj.responseText;
		var gssr=restxt.split('SHIPSELPARAM=');
		var iserr=decodeURIComponent(gssr[2])=='ERROR';
		if(!iserr){
			document.getElementById('shipoptionstable').innerHTML+='<div class="shiptableline2"><div class="shiplogo2">'+decodeURIComponent(gssr[1])+'</div><div class="shiptablerates2' + (iserr?' ectwarning':'') + '">'+gssr[0]+'</div></div>';
			document.getElementById('numshiprate').value=gssr[4];
		}
		getalternatecarriers();
	}
}
function getalternatecarriers(){
	if(extraship.length>0){
		var shiptype=extraship.shift();
		ajaxobj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
		ajaxobj.onreadystatechange=acajaxcallback;
		ajaxobj.open("GET", "vsadmin/shipservice.php?shiptype="+shiptype+"&numshiprate="+document.getElementById('numshiprate').value+"&sessionid=<?php print urlencode($thesessionid)?>&destzip=<?php print urlencode($destZip)?>&sc=<?php print urlencode($shipCountryID)?>&sta=<?php print urlencode($shipstateid)?>&orderid=<?php print $orderid?>", true);
		ajaxobj.send(null);
	}
}
<?php	}
		ect_free_result($result);
	} ?>
var checkouterrtxt='';
function chkextra(isship,ob,fldtxt){
	var hasselected=false,fieldtype='';
	if(ob){
		fieldtype=(ob.type?ob.type:'radio');
		if(fieldtype=='text'||fieldtype=='textarea'||fieldtype=='password'){
			hasselected=ob.value!='';
		}else if(fieldtype=='select-one'){
			hasselected=ob.selectedIndex!=0;
		}else if(fieldtype=='radio'){
			for(var ii=0;ii<ob.length;ii++)if(ob[ii].checked)hasselected=true;
		}else if(fieldtype=='checkbox')
			hasselected=ob.checked;
		if(!hasselected){
			if(checkouterrtxt==''){
				if(ob.focus)ob.focus();else ob[0].focus();
				if(isship){
					chkconfship(true,ob,"<?php print jscheck($GLOBALS['xxPlsEntr'].' "'.$GLOBALS['xxShpDet'].' / ')?>"+fldtxt+"\".\n\n<?php print jscheck($GLOBALS['xxNoShip'])?>");
				}else
					chkfocus(true,ob,"<?php print jscheck($GLOBALS['xxPlsEntr'])?> \""+fldtxt+"\".");
				return(false);
			}
			if(fieldtype!='radio')ectaddclass(ob,'ectwarning');
		}else
			if(fieldtype!='radio')ectremoveclass(ob,'ectwarning');
	}else{
		alert("Invalid: " + fldtxt);
		return(false);
	}
	return(true);
}
function chkfocus(ttest,tobj,ttxt){
	if(ttest){
		if(checkouterrtxt==''){
			if(tobj.focus)tobj.focus();
			checkouterrtxt=ttxt;
		}
		ectaddclass(tobj,'ectwarning');
	}else
		ectremoveclass(tobj,'ectwarning');
	return false;
}
function chkconfship(ttest,tobj,ttxt){
	if(ttest) isshipcheckouterr=true;
	return chkfocus(ttest,tobj,ttxt);
}
function docheckform(frm){
<?php	if($paypalcheckoutexpress){
			print "checkouterrtxt='';\n";
			if(trim_(@$GLOBALS['extracheckoutfield1'])!='' && @$GLOBALS['extracheckoutfield1required']) print 'chkextra(false,frm.ordcheckoutextra1,"'.jsspecials(strip_tags($GLOBALS['extracheckoutfield1'])).'");'."\n";
			if(trim_(@$GLOBALS['extracheckoutfield2'])!='' && @$GLOBALS['extracheckoutfield2required']) print 'chkextra(false,frm.ordcheckoutextra2,"'.jsspecials(strip_tags($GLOBALS['extracheckoutfield2'])).'");'."\n";
			print "if(checkouterrtxt!=''){alert(checkouterrtxt);return false;}\n";
		}
		if(@$GLOBALS['termsandconditions']&&($ordPayProvider=='19'||$ordPayProvider=='21'||$ordPayProvider=='26'||$paypalcheckoutexpress)){ ?>
if(document.getElementById('ecttnccheckbox').checked==false){
	alert("<?php print jscheck($GLOBALS['xxPlsProc'])?>");
	document.getElementById('ecttnccheckbox').focus();
	ectaddclass(ectById('ecttnccheckbox'),'ectwarning');
	return(false);
}
<?php	}elseif(recaptchaenabled(256) && ($grandtotal==0 || $ordPayProvider=='4' || $ordPayProvider=='17')){
			print 'if(!cardentrycaptchaok){ alert("' . jscheck($GLOBALS['xxRecapt']) . '");return(false); }';
		} ?>
return(true);
}
<?php	if(@$GLOBALS['termsandconditions']&&($ordPayProvider=='19'||$ordPayProvider=='21'||$ordPayProvider=='26'||$paypalcheckoutexpress)) gettermsjsfunction() ?>
/* ]]> */<?php print $GLOBALS['wpjavascriptendcomments']?></script>
				</div>
			  </div>
<?php	//displayintshipping();
		if($shipType==0) $GLOBALS['combineshippinghandling']=FALSE;
		if($shipType!=0||$willpickup_){
			if($currShipType=='') $currShipType=$shipType;
			if(!$willpickup_){
?>			  <div id="cart3shipselrow" class="<?php print ($adminAltRates==0?'cart3row ':'')?>cart3shipselrow">
<?php			if($adminAltRates==0){
					print '<div class="cobhl cobhl3 cart3shippingt"><div class="shiplogo">' . getshiplogo($currShipType) . '</div></div>';
?>				<div class="cobll cobll3 cart3shipping"><?php
					print '<div class="shipoptionstable' . (! $success?' ectwarning':'') . '" id="shipoptionstable">';
					if(! $success)
						print $errormsg;
					else{
						if($shipType!=0 || ($shipping-$freeshipamnt)!=0 || $willpickup_){
							if(! $multipleoptions) print FormatEuroCurrency(((float)$shipping+(@$GLOBALS['combineshippinghandling'] ? $handling : 0))-$freeshipamnt) . ($shipMethod!='' ? ' - ' . $shipMethod : ''); else showshippingselect();
						}
					}
					print '</div></div>';
				}elseif($adminAltRates==1){
					print '<div class="cobhl cobhl3 cart3shippingt"><div class="shipaltrates">';
					$sSQL='SELECT altrateid,altratename,'.getlangid('altratetext',65536).',usealtmethod,usealtmethodintl FROM alternaterates WHERE usealtmethod'.$international.'<>0 ORDER BY altrateorder'.$international.',altrateid';
					$result=ect_query($sSQL) or ect_error();
					if(ect_num_rows($result)>0){ ?>
						<div class="cart3shiphead"><?php print 'Compare Carriers'?></div>
						<div id="cart3alratelines" class="cart3alratelines"><?php
						while($rs=ect_fetch_assoc($result)){
							writealtshipline($rs[getlangid('altratetext',65536)],$rs['altrateid'],'','',FALSE);
						}
?>						</div>
<?php				}
					ect_free_result($result);
					print '</div></div>';
?>					<div class="cobll cobll3 cart3shipping">
						<div class="flexvertalign"><div class="shiplogo"><?php print getshiplogo($currShipType)?></div><div class="cart3shiphead"><?php print $GLOBALS['xxSeShMe']?></div></div><?php
					print '<div class="shipoptionstable' . (! $success?' ectwarning':'') . '" id="shipoptionstable">';
					if(! $success)
						print $errormsg;
					else{
						if($shipType!=0 || ($shipping-$freeshipamnt)!=0 || $willpickup_){
							if(! $multipleoptions) print FormatEuroCurrency(((float)$shipping+(@$GLOBALS['combineshippinghandling'] ? $handling : 0))-$freeshipamnt) . ($shipMethod!='' ? ' - ' . $shipMethod : ''); else showshippingselect();
						}
					}
					print '</div></div>';
				}else{
					print '<div class="shipoptionstable2" id="shipoptionstable">';
					if($success){
						print '<div class="shiptableline2"><div class="shiplogo2">' . getshiplogo($currShipType) . '</div><div class="shiptablerates2' . (! $success?' ectwarning':'') . '">';
						if($shipType!=0 || ($shipping-$freeshipamnt)!=0 || $willpickup_){
							if(! $multipleoptions) print FormatEuroCurrency(((float)$shipping+(@$GLOBALS['combineshippinghandling'] ? $handling : 0))-$freeshipamnt) . ($shipMethod!='' ? ' - ' . $shipMethod : ''); else showshippingselect();
						}
						print '</div></div>';
					}
					print '</div>';
				}?>
			  </div>
<?php		}
		}
		writeshippingflags(3);
		if($shipType!=0||$willpickup_){ ?>
			  <div class="cart3row">
				<div class="cobhl cobhl3 cart3shippingt"><?php print (@$GLOBALS['combineshippinghandling'] ? $GLOBALS['xxShipHa'] : $GLOBALS['xxShippg'])?></div>
				<div class="cobll cobll3 cart3shipping"><?php
			if(! $success){
				print '<span class="ectwarning">' . $errormsg . '</span>';
			}else
				print FormatEuroCurrency(((float)$shipping+(@$GLOBALS['combineshippinghandling'] ? $handling : 0))-$freeshipamnt) . ($shipMethod!='' ? ' - ' . $shipMethod : '');
				?></div>
			  </div>
<?php	}
		if($success && $handling!=0 && @$GLOBALS['combineshippinghandling']!=TRUE){ ?>
			  <div class="cart3row">
				<div class="cobhl cobhl3 cart3handlingt"><?php print $GLOBALS['xxHndlg']?></div>
				<div class="cobll cobll3 cart3handling"><?php print FormatEuroCurrency($handling)?></div>
			  </div>
<?php	}
		if($totaldiscounts!=0&&(($totalgoods+$shipping+$handling)-($totaldiscounts+$freeshipamnt))>=0 && @$GLOBALS['showtaxinclusive']!=3){ ?>
			  <div class="cart3row">
				<div class="cobhl cobhl3 ectdscntt"><?php print $GLOBALS['xxTotDs']?></div>
				<div class="cobll cobll3 ectdscnt"><?php print FormatEuroCurrency($totaldiscounts)?></div>
			  </div>
			  <div class="cart3row">
				<div class="cobhl cobhl3"><?php print $GLOBALS['xxSubTot']?></div>
				<div class="cobll cobll3 cart3sustot"><?php print FormatEuroCurrency(($totalgoods+$shipping+$handling)-($totaldiscounts+$freeshipamnt))?></div>
			  </div>
<?php	}
		if($usehst){ ?>
			  <div class="cart3row">
				<div class="cobhl cobhl3"><?php print $GLOBALS['xxHST']?></div>
				<div class="cobll cobll3"><?php print FormatEuroCurrency($stateTax+$countryTax)?></div>
			  </div>
<?php	}else{
			if($stateTax!=0.0){ ?>
			  <div class="cart3row">
				<div class="cobhl cobhl3"><?php print $GLOBALS['xxStaTax']?></div>
				<div class="cobll cobll3"><?php print FormatEuroCurrency($stateTax)?></div>
			  </div>
<?php		}
			if($countryTax!=0.0||@$GLOBALS['alwaysdisplaycountrytax']){ ?>
			  <div class="cart3row">
				<div class="cobhl cobhl3"><?php print $GLOBALS['xxCntTax']?></div>
				<div class="cobll cobll3"><?php print FormatEuroCurrency($countryTax)?></div>
			  </div>
<?php		}
		}
		if($totaldiscounts!=0&&((($totalgoods+$shipping+$handling)-($totaldiscounts+$freeshipamnt))<0 || @$GLOBALS['showtaxinclusive']==3)){ ?>
			  <div class="cart3row">
				<div class="cobhl cobhl3 ectdscntt"><?php print $GLOBALS['xxTotDs']?></div>
				<div class="cobll cobll3 ectdscnt"><?php print FormatEuroCurrency($totaldiscounts)?></div>
			  </div>
<?php	}?>
			  <div class="cart3row cart3gndtotcntnr">
				<div class="cobhl cobhl3 cart3gndtot<?php print ($success?'':' ectwarning')?>"><?php print ($success?$GLOBALS['xxGndTot']:(@$errormsg!=$GLOBALS['xxPlShOp']?'Error':''))?></div>
				<div class="cobll cobll3 cart3gndtott<?php print ($success?'':' ectwarning')?>"><?php
					if(! $success)
						print trim(@$errormsg)!=''?$errormsg:'-';
					else{
						print FormatEuroCurrency($grandtotal);
						if(getpost('payprovider')=='27'&&($GLOBALS['adminPayLater'] & 64)==64){
							print '<div data-pp-message data-pp-amount="' . $grandtotal . '" class="paylaterquote cartpaylaterquote"></div>'."\n";
						}
					} ?></div>
			  </div>
<?php	if(! ($ordPayProvider=='7' || $ordPayProvider=='13' || $ordPayProvider=='18')) $cardinalprocessor='';
		$checkcarddetails=FALSE;
		if($success && $grandtotal>0 && ($ordPayProvider=='7' || $ordPayProvider=='10' || $ordPayProvider=='12' || $ordPayProvider=='13' || ($ordPayProvider=='14' && @$customppacceptcc) || ($ordPayProvider=='16' && $data2=='1') || $ordPayProvider=='18' || $ordPayProvider=='29' || $ordPayProvider=='30')){ // Payflow Pro || PSiGate || Auth.NET AIM || PayPal Pro || NMI || eWay
			$checkcarddetails=TRUE;
			if($ordPayProvider!='10'&&!(@$customppdefinecardtypes&&$ordPayProvider=='14')) $data1='XXXXXXX0XXXXXXXXXXXXXXXXX';
			if($ordPayProvider!='10'&&($origCountryCode=='GB'||$origCountryCode=='IE')&&!(@$customppdefinecardtypes&&$ordPayProvider=='14')) $data1='XXXXXXXXXXXXXXXXXXXXXXXXX';
			$isPSiGate=($ordPayProvider=='12');
			$isLinkpoint=($ordPayProvider=='16');
			$isnmi=$ordPayProvider=='29';
			$iseway=$ordPayProvider=='30';
			if($isPSiGate){
				$sscardname='Bname';
				$sscardnum='CardNumber';
				$ssexmon='CardExpMonth';
				$ssexyear='CardExpYear';
				$sscvv2='CardIDNumber';
			}elseif($isLinkpoint){
				$sscardname='bname';
				$sscardnum='cardnumber';
				$ssexmon='expmonth';
				$ssexyear='expyear';
				$sscvv2='cvm';
			}elseif($isnmi){
				$sscardname='nminame';
				$sscardnum='billing-cc-number';
				$ssexmon='nmimon';
				$ssexyear='nmiyear';
				$sscvv2='cvv';
				if($data2!=''){
					$sscardnum='ccnumber';
					$ssexmon='ccexp';
				}else
					writehiddenidvar('billing-cc-exp','');
			}elseif($iseway){
				// EWAY_CARDSTARTMONTH EWAY_CARDSTARTYEAR EWAY_CARDISSUENUMBER
				$sscardname='EWAY_CARDNAME';
				$sscardnum='EWAY_CARDNUMBER';
				$ssexmon='EWAY_CARDEXPIRYMONTH';
				$ssexyear='EWAY_CARDEXPIRYYEAR';
				$sscvv2='EWAY_CARDCVN';
			}else{
				$sscardname='cardname';
				$sscardnum='ACCT';
				$ssexmon='EXMON';
				$ssexyear='EXYEAR';
				$sscvv2='CVV2';
			}
			$acceptecheck=(($ppbits&1)==1 && $ordPayProvider=='13') || (@$customppacceptecheck && $ordPayProvider=='14');
?>
<input type="hidden" name="sessionid" value="<?php print $thesessionid?>" />
<script><?php print $GLOBALS['wpjavascriptcomments']?>/* <![CDATA[ */
function setnmidate(){
	document.getElementById('billing-cc-exp').value=document.getElementById('nmimon').value+document.getElementById('nmiyear').value;
}
var isswitchcard=false;
function clearcc(){
	document.getElementById("<?php print $sscardnum?>").value="";
	document.getElementById("<?php print $sscvv2?>").value="";
<?php if(!($isnmi&&$data2!='')){ ?>
	document.getElementById("<?php print $ssexmon?>").selectedIndex=0;
	document.getElementById("<?php print $ssexyear?>").selectedIndex=0;
<?php } ?>
}
function donecc(){
	return true;
}
if(window.addEventListener){
	window.addEventListener("load", clearcc, false);
	window.addEventListener("unload",donecc,false);
}else if(window.attachEvent){
	window.attachEvent("onload", clearcc);
}
function isCreditCard(st){
  if(st.length>19)return(false);
  sum=0; mul=1; l=st.length;
  for(i=0; i < l; i++){
	digit=st.substring(l-i-1,l-i);
	tproduct=parseInt(digit ,10)*mul;
	if(tproduct>=10)
		sum+=(tproduct % 10) + 1;
	else
		sum+=tproduct;
	if(mul==1)mul++;else mul--;
  }
  return((sum % 10)==0);
}
function isVisa(cc){
  if(((cc.length==16) || (cc.length==13)) && (cc.substr(0,1)==4))
	return isCreditCard(cc);
  return false;
}
function isMasterCard(cc){
  firstdig=cc.substr(0,1);
  seconddig=cc.substr(1,1);
  first4digs=parseInt(cc.substr(0,4));
  if((cc.length==16) && ((firstdig==5 && seconddig>=1 && seconddig<=5) || (first4digs>=2221 && first4digs<=2729)))
	return isCreditCard(cc);
  return false;
}
function isAmericanExpress(cc){
  firstdig=cc.substr(0,1);
  seconddig=cc.substr(1,1);
  if(cc.length==15 && firstdig==3 && (seconddig==4 || seconddig==7))
	return isCreditCard(cc);
  return false;
}
function isDinersClub(cc){
  firstdig=cc.substr(0,1);
  seconddig=cc.substr(1,1);
  if(cc.length==14 && firstdig==3 && (seconddig==0 || seconddig==6 || seconddig==8))
	return isCreditCard(cc);
  return false;
}
function isDiscover(cc){
  first4digs=cc.substr(0,4);
  if(cc.length==16 && (first4digs=="6011" || cc.substr(0,3)=="622" || cc.substr(0,2)=="64" || cc.substr(0,2)=="65"))
	return isCreditCard(cc);
  return false;
}
function isAusBankcard(cc){
  first4digs=cc.substr(0,4);
  if(cc.length==16 && (first4digs=="5610"||first4digs=="5602"))
	return isCreditCard(cc);
  return false;
}
function isEnRoute(cc){
  first4digs=cc.substr(0,4);
  if(cc.length==15 && (first4digs=="2014" || first4digs=="2149"))
	return isCreditCard(cc);
  return false;
}
function isJCB(cc){
  first4digs=cc.substr(0,4);
  if(cc.length==16 && (first4digs=="3088" || first4digs=="3096" || first4digs=="3112" || first4digs=="3158" || first4digs=="3337" || first4digs=="3528" || first4digs=="3589"))
	return isCreditCard(cc);
  return false;
}
function isSwitch(cc){
  first4digs=cc.substr(0,4);
  if((cc.length>=16 && cc.length<=19) && (first4digs=="4903" || first4digs=="4911" || first4digs=="4936" || first4digs=="5018" || first4digs=="5020" || first4digs=="5038" || first4digs=="5641" || first4digs=="6304" || first4digs=="6333" || first4digs=="6334" || first4digs=="6759" || first4digs=="6761" || first4digs=="6763" || first4digs=="6767")){
	isswitchcard=true;
	return(isCreditCard(cc));
  }
  return false;
}
function isLaser(cc){
  first4digs=cc.substr(0,4);
  if((cc.length>=16 && cc.length<=19) && (first4digs=="6304" || first4digs=="6706" || first4digs=="6771" || first4digs=="6709"))
	return(isCreditCard(cc));
  return false;
}
function isvalidcard(theForm){
	if(document.getElementById('ppcoverdiv'))document.getElementById('ppcoverdiv').style.display='';
	var retval=doisvalidcard(theForm);
	if(document.getElementById('ppcoverdiv'))document.getElementById('ppcoverdiv').style.display=(retval?'':'none');
	return retval;
}
function doisvalidcard(theForm){
  cc=theForm.elements['<?php print $sscardnum?>'].value;
  newcode="";
  var l=cc.length;
  for(i=0;i<l;i++){
	digit=cc.substring(i,i+1);
	digit=parseInt(digit ,10);
	if(!isNaN(digit)) newcode+=digit;
  }
  cc=newcode;
  if(theForm.<?php print $sscardname?>.value==""){
	alert("<?php print jscheck($GLOBALS['xxPlsEntr']) . ' \"' . jscheck($GLOBALS['xxCCName']) . '\"' ?>");
	theForm.<?php print $sscardname?>.focus();
	return false;
  }
<?php if($acceptecheck){ ?>
if(cc!="" && theForm.accountnum.value!=""){
alert("Please enter either Credit Card OR ECheck details");
return(false);
}else if(theForm.accountnum.value!=""){
  if(theForm.accountname.value==""){
	alert("<?php print jscheck($GLOBALS['xxPlsEntr'])?> \"Account Name\".");
	theForm.accountname.focus();
	return false;
  }
  if(theForm.bankname.value==""){
	alert("<?php print jscheck($GLOBALS['xxPlsEntr'])?> \"Bank Name\".");
	theForm.bankname.focus();
	return false;
  }
  if(theForm.routenumber.value==""){
	alert("<?php print jscheck($GLOBALS['xxPlsEntr'])?> \"Routing Number\".");
	theForm.routenumber.focus();
	return false;
  }
  if(theForm.accounttype.selectedIndex==0){
	alert("Please select your account type: (Checking / Savings).");
	theForm.accounttype.focus();
	return false;
  }
<?php	if(@$wellsfargo==TRUE){ ?>
  if(theForm.orgtype.selectedIndex==0){
	alert("Please select your account type: (Personal / Business).");
	theForm.orgtype.focus();
	return false;
  }
  if(theForm.taxid.value=="" && theForm.licensenumber.value==""){
	alert("Please enter either a Tax ID number or Drivers License Details.");
	theForm.taxid.focus();
	return false;
  }
  if(theForm.taxid.value==""){
	if(theForm.licensestate.selectedIndex==0){
		alert("Please select your Drivers License State.");
		theForm.licensestate.focus();
		return false;
	}
	if(theForm.dldobmon.selectedIndex==0){
		alert("Please select your Drivers License D.O.B. Month.");
		theForm.dldobmon.focus();
		return false;
	}
	if(theForm.dldobday.selectedIndex==0){
		alert("Please select your Drivers License D.O.B. Day.");
		theForm.dldobday.focus();
		return false;
	}
	if(theForm.dldobyear.selectedIndex==0){
		alert("Please select your Drivers License D.O.B. year.");
		theForm.dldobyear.focus();
		return false;
	}
  }
<?php	} ?>
}else{
<?php } ?>
  if(true <?php
		if(substr($data1,7,1)=='X') print '&& !isSwitch(cc) ';
		if(substr($data1,0,1)=='X') print '&& !isVisa(cc) ';
		if(substr($data1,1,1)=='X') print '&& !isMasterCard(cc) ';
		if(substr($data1,2,1)=='X') print '&& !isAmericanExpress(cc) ';
		if(substr($data1,3,1)=='X') print '&& !isDinersClub(cc) ';
		if(substr($data1,4,1)=='X') print '&& !isDiscover(cc) ';
		if(substr($data1,5,1)=='X') print '&& !isEnRoute(cc) ';
		if(substr($data1,6,1)=='X') print '&& !isJCB(cc) ';
		if(substr($data1,8,1)=='X') print '&& !isAusBankcard(cc) ';
		if(substr($data1,9,1)=='X') print '&& !isLaser(cc) '; ?>){
	<?php if($acceptecheck) $GLOBALS['xxValCC']='Please enter a valid credit card number or bank account details if paying by ECheck.'; ?>
	alert("<?php print jscheck($GLOBALS['xxValCC'])?>");
	theForm.elements['<?php print $sscardnum?>'].focus();
	return false;
  }
  if(theForm.<?php print $ssexmon?>.selectedIndex==0){
	alert("<?php print jscheck($GLOBALS['xxCCMon'])?>");
	theForm.<?php print $ssexmon?>.focus();
	return false;
  }
  if(theForm.<?php print $ssexyear?>.selectedIndex==0){
	alert("<?php print jscheck($GLOBALS['xxCCYear'])?>");
	theForm.<?php print $ssexyear?>.focus();
	return false;
  }
<?php if(substr($data1,7,1)=="X"){ ?>
	theForm.IssNum.value=theForm.IssNum.value.replace(/[^0-9]/g, '');
  if(theForm.IssNum.value=="" && isswitchcard){
	alert("Please enter an issue number / start date for Maestro/Solo cards.");
	theForm.IssNum.focus();
	return false;
  }
<?php } ?>
  if(theForm.<?php print $sscvv2?>.value==""){
	alert("<?php print jscheck($GLOBALS['xxPlsEntr']) . ' \"' . jscheck($GLOBALS['xx34code']) . '\"'?>");
	theForm.<?php print $sscvv2?>.focus();
	return false;
  }
<?php if($acceptecheck) print '}';
	if(recaptchaenabled(1)) print 'if(!cardentrycaptchaok){ alert("' . jscheck($GLOBALS['xxRecapt']) . '");return(false); }' ?>
	theForm.elements['<?php print $sscardnum?>'].value=cc;
	return true;
}
<?php if(@$cardinalprocessor!='' && @$cardinalmerchant!='' && @$cardinalpwd!=''){ ?>
vbvtext='<html><head><title>Verified by Visa</title><style type="text/css">body {font-family: verdana,sans-serif;font-size:10pt;}</style></head><body><p><h3><?php print str_replace("'","\'",$GLOBALS['xxVBV1'])?></h3></p><p><?php print str_replace("'","\'",$GLOBALS['xxVBV2'])?><img src="images/vbv_logo.gif" border="0" style="float:<?php print $tright?>;margin:4px;" /></p><p><?php print str_replace("'","\'",$GLOBALS['xxVBV3'])?></p><p><?php print str_replace("'","\'",$GLOBALS['xxVBV4'])?></p><p><?php print str_replace("'","\'",$GLOBALS['xxVBV5'])?></p><p align="center"><input type="button" class="ectbutton" value="<?php print str_replace("'","\'",$GLOBALS['xxClsWin'])?>" onclick="window.close()"></p></body></'+'html>';
<?php } ?>
/* ]]> */<?php print $GLOBALS['wpjavascriptendcomments']?></script>
<?php		if(@$_SERVER['HTTPS']!='on' && (@$_SERVER['SERVER_PORT']!='443') && @$nochecksslserver!=TRUE){ ?>
			  <div>
				<div class="cobhl cart2column ectwarning">This site may not be secure. Do not enter real Credit Card numbers.</div>
			  </div>
<?php		} ?>
			  <div><div class="cobhl cart4header cartheader"><?php print $GLOBALS['xxCCDets']?></div></div>
<?php				if($isnmi&&$data2!=''){
						splitname(trim($ordName.' '.$ordLastName), $firstname, $lastname); ?>
			  <div id="nmicarddetails">
				<div class="cart4row">
					<div class="cobhl cobhl4"><?php print labeltxt($GLOBALS['xxCrdNum'],$sscardnum)?></div>
					<div class="cobll cobll4"><div class="cdform3fixw" id="ccnumber"></div></div>
				</div>
				<div class="cart4row">
					<div class="cobhl cobhl4"><?php print $GLOBALS['xxExpEnd']?></div>
					<div class="cobll cobll4"><div class="cdform3fixw" id="ccexp"></div></div>
				</div>
				<div class="cart4row">
					<div class="cobhl cobhl4"><?php print labeltxt($GLOBALS['xx34code'],$sscvv2)?></div>
					<div class="cobll cobll4"><div class="cdformsmfixw" id="cvv"></div></div>
				</div>
			  </div>
<div id="nmicover" class="ectopaque" style="display:none;text-align:center;padding-top:250px"><img id="nmipreloader" src="images/preloader.gif" alt="" class="ectpreloader"><div id="threeDSMountPoint" style="display:none;max-width:800px;background-color:white;margin:0 auto;"></div></div>
<script src="https://secure.nmi.com/js/v1/Gateway.js"></script> 
<script src="https://secure.nmi.com/token/Collect.js" data-tokenization-key="<?php print $data2?>" data-field-ccnumber-placeholder='0000 0000 0000 0000' data-field-cvv-placeholder='***' data-field-ccexp-placeholder='00 / 00'></script>
<script>
	const gateway = Gateway.create('<?php print $data3?>');
	const threeDS = gateway.get3DSecure();
	window.addEventListener('DOMContentLoaded', () => {
		CollectJS.configure({
			variant:'inline',
			'validationCallback':function(field, status, message){if(!status){alert(field+' '+message);}},
			callback:(e) => {
			const options = {
				paymentToken:e.token,
				currency:'<?php print $countryCurrency?>',
				amount:'<?php print round($grandtotal*100)?>',
				email:'<?php print jsescape($ordEmail)?>',
				phone:'<?php print jsescape($ordPhone)?>',
				city:'New <?php print jsescape($ordCity)?>',
				state:'<?php print jsescape($ordState)?>',
				address1:'<?php print jsescape($ordAddress)?>',
				country:'<?php print $countryCode?>',
				firstName:'<?php print jsescape($firstname)?>',
				lastName:'<?php print jsescape($lastname)?>',
				postalCode:'<?php print jsescape($ordZip)?>'
			};
			document.getElementById('nmicover').style.display='';
			document.getElementById('nmicarddetails').style.display='none';
			document.getElementById('payButton').style.display='none';
			const threeDSecureInterface = threeDS.createUI(options);
			const payment_token=e.token
			threeDSecureInterface.start('#threeDSMountPoint');
			threeDSecureInterface.on('challenge', function(e) {
				document.getElementById('nmipreloader').style.display='none';
				document.getElementById('threeDSMountPoint').style.display='';
			});
			threeDSecureInterface.on('complete', function(e){
				fetch('<?php print $storeurlssl?>vsadmin/stripewebhook.php?pprov=29&ordid=<?php print $orderid?>', {
					method:'POST',
					body:JSON.stringify({
						...options,cavv:e.cavv,xid:e.xid,eci:e.eci,
						cardHolderAuth:e.cardHolderAuth,
						threeDsVersion:e.threeDsVersion,
						directoryServerId:e.directoryServerId,
					})
				}).then(value => {console.log(value);document.location='thanks<?php print $GLOBALS['extension']?>?mode=authorize&method=29&ordernumber=<?php print $orderid?>&payment_token='+payment_token});
			});
			threeDSecureInterface.on('failure', function(e){
				console.log(e);
				alert(e.message);
				document.location.reload();
			});
			}
		})
		gateway.on('error', function (e) {
			console.error(e);
			document.getElementById('nmicover').style.display='none';
			document.getElementById('nmicarddetails').style.display='none';
			document.getElementById('payButton').style.display='none';
			alert(e.message);
		})
	})
</script>
<?php		}else{ ?>
			  <div class="cart4row">
				<div class="cobhl cobhl4"><?php print labeltxt($GLOBALS['xxCCName'],$sscardname)?></div>
				<div class="cobll cobll4"><input type="text" class="cdform3fixw" name="<?php print $sscardname?>" id="<?php print $sscardname?>" size="21" value="<?php print trim($ordName.' '.$ordLastName)?>" AUTOCOMPLETE="off" /></div>
			  </div>
			  <div class="cart4row">
				<div class="cobhl cobhl4"><?php print labeltxt($GLOBALS['xxCrdNum'],$sscardnum)?></div>
				<div class="cobll cobll4"><input type="text" class="cdform3fixw" name="<?php print $sscardnum?>" id="<?php print $sscardnum?>" size="21" AUTOCOMPLETE="off" /></div>
			  </div>
			  <div class="cart4row">
				<div class="cobhl cobhl4"><?php print $GLOBALS['xxExpEnd']?></div>
				<div class="cobll cobll4">
				  <select class="ectselectinput nofixw" name="<?php print $ssexmon?>" id="<?php print $ssexmon?>" size="1"<?php if($isnmi) print ' onchange="setnmidate()"'?>>
					<option value=""><?php print $GLOBALS['xxMonth']?></option>
					<?php	for($index=1; $index<=12; $index++){
								if($index < 10) $themonth="0" . $index; else $themonth=$index;
								print "<option value='" . $themonth . "'>" . $themonth . "</option>\n";
							} ?>
				  </select> / <select class="ectselectinput nofixw" name="<?php print $ssexyear?>" id="<?php print $ssexyear?>" size="1"<?php if($isnmi) print ' onchange="setnmidate()"'?>>
					<option value=""><?php print $GLOBALS['xxYear']?></option>
					<?php	$thisyear=date("Y", time());
							for($index=$thisyear; $index<=$thisyear+10; $index++){
								print "<option value='" . ($isPSiGate||$isnmi?substr($index,-2):$index) . "'>" . $index . "</option>\n";
							} ?></select>
				</div>
			  </div>
			  <div class="cart4row">
				<div class="cobhl cobhl4"><?php print labeltxt($GLOBALS['xx34code'],$sscvv2)?></div>
				<div class="cobll cobll4"><input class="ecttextinput nofixw" type="text" name="<?php print $sscvv2?>" id="<?php print $sscvv2?>" style="width:100px" AUTOCOMPLETE="off"></div>
			  </div>
<?php			if(substr($data1,7,1)=="X"){ ?>
			  <div class="cart4row">
				<div class="cobhl cobhl4"><?php print labeltxt('Issue Number / Start Date (mmyy)','IssNum')?></div>
				<div class="cobll cobll4"><input class="ecttextinput nofixw" type="text" name="IssNum" id="IssNum" style="width:100px" AUTOCOMPLETE="off"> (Maestro/Solo Only)</div>
			  </div>
<?php			}
			}
			if($acceptecheck){ // Auth.net ?>
			  <div class="cart4row">
				<div class="cobhl cart2column"><div class="cartecheck cart4header">ECheck Details</div><div class="echeckeither ectwarning">Please enter either Credit Card OR ECheck details</div></div>
			  </div>
			  <div class="cart4row">
				<div class="cobhl cobhl4"><?php print labeltxt('Account Name','accountname')?></div>
				<div class="cobll cobll4"><input type="text" name="accountname" id="accountname" size="21" AUTOCOMPLETE="off" value="<?php print trim($ordName.' '.$ordLastName)?>" /></div>
			  </div>
			  <div class="cart4row">
				<div class="cobhl cobhl4"><?php print labeltxt('Account Number','accountnum')?></div>
				<div class="cobll cobll4"><input type="text" name="accountnum" id="accountnum" size="21" AUTOCOMPLETE="off" /></div>
			  </div>
			  <div class="cart4row">
				<div class="cobhl cobhl4"><?php print labeltxt('Bank Name','bankname')?></div>
				<div class="cobll cobll4"><input type="text" name="bankname" id="bankname" size="21" AUTOCOMPLETE="off" /></div>
			  </div>
			  <div class="cart4row">
				<div class="cobhl cobhl4"><?php print labeltxt('Routing Number','routenumber')?></div>
				<div class="cobll cobll4"><input type="text" name="routenumber" id="routenumber" size="10" AUTOCOMPLETE="off" /></div>
			  </div>
			  <div class="cart4row">
				<div class="cobhl cobhl4"><?php print labeltxt('Account Type','accounttype')?></div>
				<div class="cobll cobll4"><select name="accounttype" id="accounttype" size="1"><option value=""><?php print $GLOBALS['xxPlsSel']?></option><option value="checking">Checking</option><option value="savings">Savings</option><option value="businessChecking">Business Checking</option></select></div>
			  </div>
<?php			if(@$wellsfargo==TRUE){ ?>
			  <div class="cart4row">
				<div class="cobhl cobhl4"><?php print labeltxt('Personal or Business Acct.','orgtype')?></div>
				<div class="cobll cobll4"><select name="orgtype" id="orgtype" size="1"><option value=""><?php print $GLOBALS['xxPlsSel']?></option><option value="I">Personal</option><option value="B">Business</option></select></div>
			  </div>
			  <div class="cart4row">
				<div class="cobhl cobhl4"><?php print labeltxt('Tax ID','taxid')?></div>
				<div class="cobll cobll4"><input type="text" name="taxid" id="taxid" size="21" AUTOCOMPLETE="off" /></div>
			  </div>
			  <div class="cart4row">
				<div class="cobhl cobhl4 cart2column carttaxidnot">If you have provided a Tax ID then the following information is not necessary</div>
			  </div>
			  <div class="cart4row">
				<div class="cobhl cobhl4"><?php print labeltxt('Drivers License Number','licensenumber')?></div>
				<div class="cobll cobll4"><input type="text" name="licensenumber" id="licensenumber" size="21" AUTOCOMPLETE="off" /></div>
			  </div>
			  <div class="cart4row">
				<div class="cobhl cobhl4"><?php print labeltxt('Drivers License State','licensestate')?></div>
				<div class="cobll cobll4"><select size="1" name="licensestate" id="licensestate"><option value=""><?php print $GLOBALS['xxPlsSel']?></option><?php
					$sSQL='SELECT stateName,stateAbbrev FROM states WHERE stateCountryID=1 ORDER BY stateName';
					$result=ect_query($sSQL) or ect_error();
					while($rs=ect_fetch_assoc($result))
						print '<option value="' . str_replace('"','&quot;',$rs['stateAbbrev']) . '">' . $rs['stateName'] . '</option>';
					ect_free_result($result); ?></select></div>
			  </div>
			  <div class="cart4row">
				<div class="cobhl cobhl4"><?php print labeltxt('Date Of Birth On License','dldobmon')?></div>
				<div class="cobll cobll4"><select name="dldobmon" id="dldobmon" size="1"><option value=""><?php print $GLOBALS['xxMonth']?></option>
<?php				for($index=1; $index<=12; $index++) print '<option value="' . $index . '">' . date("M", mktime(1,0,0,$index,1,1990)) . '</option>'; ?>
				</select> <select name="dldobday" size="1"><option value="">Day</option>
<?php				for($index=1; $index<=31; $index++) print '<option value="' . $index . '">' . $index . '</option>'; ?>
				</select> <select name="dldobyear" size="1"><option value=""><?php print $GLOBALS['xxYear']?></option>
<?php				$thisyear=date("Y");
					for($index=$thisyear-100; $index<=$thisyear; $index++) print '<option value="' . $index . '">' . $index . '</option>'; ?>
				</select></div>
			  </div>
<?php			}
			}
		}elseif($success && $grandtotal>0 && $ordPayProvider=='25'){ // Braintree
			$url='https://api.' . ($demomode?'sandbox.':'') . 'braintreegateway.com:443/merchants/'.$data1.'/client_token';
			$sXML='<?xml version="1.0" encoding="UTF-8"?><client_token><version type="integer">2</version>' . ($data5!=''?'<merchant_account_id>' . $data5 . '</merchant_account_id>':'') . '</client_token>';
			$GLOBALS['xmlfnheaders']=array("Accept: application/xml","Content-Type: application/xml");
			$GLOBALS['xmlfnuser']=$data2;
			$GLOBALS['xmlfnpassword']=$data3;
			if(callcurlfunction($url,$sXML,$res,'',$errormsg,FALSE)){
				if($res!=''){
					$resxml=new SimpleXMLElement($res);
					if(($clientToken=$resxml->value)!=''){
?>
<script src="https://js.braintreegateway.com/web/dropin/1.46.0/js/dropin.min.js"></script>
<script>
braintree.dropin.create({
authorization:'<?php print $clientToken?>',
<?php if(($ppbits&1)==1) print "threeDSecure:{amount:'" . number_format($grandtotal,2,'.','') . "'},"?>
container:'#dropin-container',
<?php if(($ppbits&4)==4) print "paypal:{flow:'checkout',amount:" . number_format($grandtotal,2,'.','') . ",currency:'" . $countryCurrency . "'},";
if(($ppbits&2)==2) print "applePay:{displayName:'".jsescape($data4)."',paymentRequest:{total:{label: '".jsescape($data4)."',amount:'" . number_format($grandtotal,2,'.','') . "'}}},";
if(($ppbits&8)==8) print "paypalCredit:{flow:'checkout',amount:" . number_format($grandtotal,2,'.','') . ",currency:'" . $countryCurrency . "'},";
if(($ppbits&16)==16) print "venmo:{},";
if($data6!='') print "googlePay:{googlePayVersion:2,merchantId:'" . $data6 . "',transactionInfo:{totalPriceStatus:'FINAL',totalPrice:'" . number_format($grandtotal,2,'.','') . "',currencyCode:'" . $countryCurrency . "'},cardRequirements:{billingAddressRequired:true}},"?>
card:{cardholderName:{required:true},overrides:{fields:{postalCode:{prefill:'<?php print $ordZip?>'}}}}
},function(createErr,instance){
	document.getElementById('preloader').style.display='none';
	if(createErr)console.log(createErr);
	function sendNonceToServer(event){
		//if(typeof event.preventDefault==="function") event.preventDefault(); // else return;
		instance.requestPaymentMethod(function(err,payload){
			if(err){
				console.log('sendNonceToServer:', err.message);
			}else{
				if(<?php if(($ppbits&1)!=1) print "true||"?>payload.liabilityShifted||payload.type!=='CreditCard'){
					document.getElementById('payment_method_nonce').value=payload.nonce;
					document.getElementById('checkoutbutton3').style.display='none';
					var alltags=document.getElementById('dropin-container').getElementsByTagName('div');
					for(var i=0;i<alltags.length;i++){
						if(alltags[i].getAttribute('data-braintree-id')=='toggle'){ alltags[i].style.display='none'; break; }
					}
					document.getElementById('ectcheckoutform').submit();
				}else{
					alert("Authentication failure. Please choose another payment method.");
					instance.clearSelectedPaymentMethod();
				}
			}
		});
	}
	document.getElementById('checkoutbutton3').addEventListener('click',sendNonceToServer);
	document.getElementById('checkoutbutton3').disabled=false;
	instance.on('paymentMethodRequestable',function(event){if(event.paymentMethodIsSelected&&event.type!=='CreditCard') sendNonceToServer(event);});
});
</script>
<div id="preloader" style="margin:10px;text-align:center"><img src="images/preloader.gif" alt="" class="ectpreloader"></div>
<div id="dropin-container"></div>
<?php				}else{
						print '<div style="color:#FF0000">' . ($resxml->message?$resxml->message:$res) . '</div>';
						$success=FALSE;
					}
				}else{
					print '<div style="color:#FF0000">Invalid response from Braintree.</div>';
					$success=FALSE;
				}
			}else{
				print '<div style="color:#FF0000">' . $errormsg . '</div>';
				$success=FALSE;
			}
		}elseif($success && $grandtotal>0 && $ordPayProvider=='28'){ // SquareUp
?>
<script src="https://<?php print ($demomode?'sandbox.':'')?>web.squarecdn.com/v1/square.js"></script>
<div id="squarecover" class="ectopaque" style="display:none;text-align:center"><img src="images/preloader.gif" alt="" style="margin-top:250px" class="ectpreloader"></div>
<div class="sq-payment-form">
	<div id="preloader" style="margin:10px;text-align:center"><img src="images/preloader.gif" alt="" class="ectpreloader"></div>
	<div id="sq-walletbox" style="display:none">
		<button type="button" id="sq-google-pay" class="button-google-pay"></button>
		<button type="button" id="sq-apple-pay" class="apple-pay-button"></button>
		<button type="button" id="sq-masterpass" class="sq-masterpass"></button>
		<div class="sq-wallet-divider"><span class="sq-wallet-divider__text">Or</span></div>
	</div>
	<div id="sq-ccbox">
		<div class="sq-field"><div id="sq-card-number"></div></div>
		<div class="sq-field"><button type="button" id="sq-creditcard" class="ectbutton sq-button" disabled>Pay <?php print FormatEuroCurrency($grandtotal)?> Now</button></div>
	</div>
</div>
<script>
const locationId="<?php print $data3?>";
async function initializeCard(payments) {
	const card = await payments.card();
	await card.attach('#sq-card-number');
	return card;
}
function buildPaymentRequest(payments) {
	return payments.paymentRequest({
		countryCode:'<?php print jscheck($countryCode)?>',
		currencyCode:'<?php print $countryCurrency?>',
		total:{
			amount:'<?php print number_format($grandtotal,2,'.','')?>',
			label:'Total',
		},
	});
}
async function initializeGooglePay(payments) {
	const paymentRequest = buildPaymentRequest(payments);
	const googlePay = await payments.googlePay(paymentRequest);
	await googlePay.attach('#sq-google-pay');
	return googlePay;
}
async function initializeApplePay(payments) {
	const paymentRequest = buildPaymentRequest(payments);
	const applePay = await payments.applePay(paymentRequest);
	return applePay;
}
async function createPayment(token,verificationToken){
	const bodyjson = JSON.stringify({locationId,sourceId:token});
	const paymentResponse = await fetch('vsadmin/ajaxservice.php?action=squareup', {
		method: 'POST',
		headers: {'Content-Type': 'application/x-www-form-urlencoded'},
		body:'ordernumber=<?php print $orderid?>&nonce='+encodeURIComponent(token)<?php if($data3!='') print '+\'&verification=\'+verificationToken'?>,
	});
	if (paymentResponse.ok) return paymentResponse.json();
	const errorBody = await paymentResponse.text();
	alert(errorBody);
	throw new Error(errorBody);
}
async function tokenize(paymentMethod){
	const tokenResult=await paymentMethod.tokenize();
	if(tokenResult.status==='OK'){
		return tokenResult.token;
	}else{
		let errorMessage='';
		if(tokenResult.status=='Cancel'||tokenResult.status=='Invalid'){
			return false;
		}else{
			errorMessage=`Tokenization failed with status: ${tokenResult.status}`;
			if(tokenResult.errors) errorMessage+=` and errors: ${JSON.stringify(tokenResult.errors)}`;
		}
		throw new Error(errorMessage);
	}
}
<?php	if($data3!=''){
			splitname(trim($ordName.' '.$ordLastName), $firstname, $lastname);
?>
async function verifyBuyer(payments,token){
	const verificationDetails={
		intent:'CHARGE',
		amount:'<?php print number_format($grandtotal,2,'.','')?>',
		currencyCode:'<?php print $countryCurrency?>',
		billingContact:{
			givenName:"<?php print jscheck($firstname)?>",
			familyName:"<?php print jscheck($lastname)?>",
			email:"<?php print jscheck($ordEmail)?>",
			country:"<?php print jscheck($countryCode)?>",
			postalCode:"<?php print jscheck($ordZip)?>",
			region:"<?php print jscheck($ordState)?>",
			city:"<?php print jscheck($ordCity)?>",
			addressLines:["<?php print jscheck($ordAddress)?>"<?php if($ordAddress2!='') print ',"' . jscheck($ordAddress2) . '"'?>]
		}
	};
	const verificationResults = await payments.verifyBuyer(token,verificationDetails);
	return verificationResults.token;
}
<?php	} ?>
document.addEventListener('DOMContentLoaded', async function () {
	if(!window.Square){throw new Error('Square.js failed to load properly');}
	let payments,card,googlePay,applePay;
	try{
		payments = window.Square.payments("<?php print $data1?>", locationId);
	}catch{
		alert("Invalid Square credentials");
		return;
	}
	try{
		card = await initializeCard(payments);
	}catch(e){
		console.error('Initializing Card failed', e);
		return;
	}
	document.getElementById('preloader').style.display='none';
	try{
		googlePay = await initializeGooglePay(payments);
	}catch(e){}
	try{
		applePay = await initializeApplePay(payments);
	}catch(e){}
	async function handlePaymentMethodSubmission(event,paymentMethod,shouldVerify=false) {
		event.preventDefault();
		document.getElementById('squarecover').style.display='';
		try {
			cardButton.disabled = true;
			const token = await tokenize(paymentMethod);
			if(token!=false){
				let verificationToken;
				if(shouldVerify) verificationToken=await verifyBuyer(payments,token);
				const paymentResults = await createPayment(token,verificationToken);
				if(paymentResults.status=='SUCCESS'){
					document.getElementById('payment_method_nonce').value=token;
					document.getElementById('txnid').value=paymentResults.txn_id;
					document.getElementById('ectcheckoutform').submit();
				}else{
					alert(paymentResults.reason);
					cardButton.disabled=false;
				}
			}else
				cardButton.disabled=false;
		} catch (e) {
			cardButton.disabled=false;
			alert(e.message);
			console.error(e.message);
		}
		document.getElementById('squarecover').style.display='none';
	}
	const cardButton = document.getElementById('sq-creditcard');
	cardButton.disabled=false;
	cardButton.addEventListener('click', async function (event) {
		await handlePaymentMethodSubmission(event,card,<?php print ($data3!=''?'true':'false') ?>);
	});
	if(googlePay){
		const googlePayButton = document.getElementById('sq-google-pay');
		document.getElementById('sq-walletbox').style.display='block';
		document.getElementById('sq-google-pay').style.display='block';
		googlePayButton.addEventListener('click', async function (event) {
			await handlePaymentMethodSubmission(event, googlePay,<?php print ($data3!=''?'true':'false') ?>);
		});
	}
	if(applePay){
		const applePayButton = document.getElementById('sq-apple-pay');
		document.getElementById('sq-walletbox').style.display='block';
		document.getElementById('sq-apple-pay').style.display='block';
		applePayButton.addEventListener('click', async function (event) {
			await handlePaymentMethodSubmission(event, applePay,<?php print ($data3!=''?'true':'false') ?>);
		});
	}
});
</script>
<?php
		}
		if($success&&$ordPayProvider!='28'){
			if(@$cardinalprocessor!='' && @$cardinalmerchant!='' && @$cardinalpwd!=''){ ?>
				<div class="cart4row"><div class="cobhl cart2column"><?php print $GLOBALS['xxCentl']?></div></div>
<?php		}
			if(($checkcarddetails && recaptchaenabled(1)) || (($grandtotal==0 || $ordPayProvider=='4' || $ordPayProvider=='17') && recaptchaenabled(256))){
				displayrecaptchajs("cardentrycaptcha",TRUE,FALSE);
				print '<div style="text-align:center"><div id="cardentrycaptcha" class="g-recaptcha reCAPTCHAcheckout" style="margin-bottom:10px;display:inline-block"></div></div>';
			} ?>
				<div class="cobll cart2column checkoutbutton3"><?php
			if($orderid!=0){
				if($ordPayProvider=='23' && $grandtotal>0 && $ppflag1==0){
					print '<script src="https://checkout.stripe.com/checkout.js" class="stripe-button" data-key="'.$data2.'" data-amount="'.round($grandtotal*100).'" data-currency="'.$countryCurrency.'" data-email="'.$ordEmail.'" ' . ($data3!=''?'data-name="'.$data3.'" ':'') . 'data-description="' . substr(htmlspecials($descstr),0,255) . '" data-zip-code="true" data-billing-address="true"></script>';
				}elseif($ordPayProvider=='23' && $grandtotal>0 && $ppflag1==2){
					print '<div id="payment-element" style="margin-bottom:10px"></div><button id="stripesubmit" class="ectbutton checkoutbutton checkoutbutton3 widecheckout3" disabled>' . (@$GLOBALS['xxCOTxt3']!=''?$GLOBALS['xxCOTxt3']:$GLOBALS['xxCOTxt']) . '</button>';
?>
<script>
<?php
$stripelocale='';
if($origCountryID==65) $stripelocale='fr';
if($origCountryID==71) $stripelocale='de';
if($origCountryID==133) $stripelocale='nl';
if($origCountryID==175) $stripelocale='es';
if($origCountryID==201) $stripelocale='en-GB';
?>
	const stripe=Stripe('<?php print $data2?>'<?php print ($stripelocale!='' ? ",{locale:'" . $stripelocale . "'}" : '')?>);
	const options={
		clientSecret:'<?php print $paymentintent?>',
		appearance:{},
		loader:'always'
	};
	const elements=stripe.elements(options);
	const paymentElement=elements.create('payment',{defaultValues:{billingDetails:{address:{country:'<?php print jsescape($countryCode)?>',postal_code:'<?php print jsescape($ordZip)?>'}}}});
	paymentElement.on('ready',function(event){document.getElementById('stripesubmit').disabled=false;});
	paymentElement.mount('#payment-element');
	const form=document.getElementById('payment-form');
	form.addEventListener('submit',async(event)=>{
		event.preventDefault();
		document.getElementById('stripesubmit').disabled=true;
		const {error}=await stripe.confirmPayment({
			elements,
			confirmParams:{
				return_url:'<?php print $storeurlssl.'thanks'.$GLOBALS['extension'].'?soid=' . $orderid?>',
			},
		});
		if(error){
			alert('<?php print jsescape($GLOBALS['xxGenPEr'])?>');
			document.getElementById('stripesubmit').disabled=false;
		}
	});
</script>
<?php
				}elseif($grandtotal>0 && $ordPayProvider=='24' && $ppflag1==1){ // Opayo Server
					print '<iframe scrolling="no" style="margin-top:10px;width:100%;max-width:600px;height:580px;border:none" src="' . $NextURL . '"></iframe>';
				}elseif($ordPayProvider=='25')
					print imageorbuttontag(@$imgcheckoutbutton3,(@$GLOBALS['xxCOTxt3']!=''?$GLOBALS['xxCOTxt3']:$GLOBALS['xxCOTxt']),'checkoutbutton checkoutbutton3 widecheckout3'," false",TRUE,FALSE,'disabled id="checkoutbutton3"');
				elseif($ordPayProvider=='27'&&getget('action')!='termpp')
					paypalcheckoutjs(FALSE,$ppflag2==1,($GLOBALS['adminPayLater']&192)!=0);
				elseif($ordPayProvider=='31'||$ordPayProvider=='32')
					print imageorbuttontag(@$imgcheckoutbutton3,(@$GLOBALS['xxCOTxt3']!=''?$GLOBALS['xxCOTxt3']:$GLOBALS['xxCOTxt']),'widecheckout3','payprovscript()',TRUE);
				elseif($ordPayProvider=='29'&&$data2!='')
					print imageorbuttontag('',(@$GLOBALS['xxCOTxt3']!=''?$GLOBALS['xxCOTxt3']:$GLOBALS['xxCOTxt']),'checkoutbutton checkoutbutton3 widecheckout3','',TRUE,FALSE,'id="payButton"');
				elseif($ordPayProvider=='34'&&$data1!=''){
?>
					<script src="https://gateway<?php print ($demomode?'t':'')?>.moneris.com/chktv2/js/chkt_v2.00.js"></script>
					<div id="monerisopaque" class="ectopaque" style="display:none"><div id="monerisCheckout" class="monerisCheckout"></div></div>
<script>
var myCheckout = new monerisCheckout();
myCheckout.setMode("<?php print ($demomode?"qa":"prod")?>");
myCheckout.setCheckoutDiv("monerisCheckout");

var myCheckout = new monerisCheckout();
function monerisStartCheckout(){
	ectById('monerisCheckout').style.position='fixed';
	ectById('monerisCheckout').style.top='0';
	ectById('monerisCheckout').style.left='0';
	ectById('monerisCheckout').style.padding='20px';
	ectById('monerisopaque').style.display='';
	myCheckout.startCheckout('<?php print $ticketno ?>');
}
function monerisPageLoad(msg){
}
function monerisCancelTxn(){
	myCheckout.closeCheckout();
	ectById('monerisopaque').style.display='none';
}
function monerisErrorEvent(){
	myCheckout.closeCheckout();
	alert('We apologize but there seems to have been an error. Please try checking out again and if that doesn\'t work then please contact us.');
}
function monerisPaymentReceipt(){
}
function monerisPaymentComplete(msg){
	var response=JSON.parse(msg);
	//alert('payment complete:'+msg);
	if(response.response_code=='001'){
		myCheckout.closeCheckout();
		document.location='thanks<?php print $GLOBALS['extension']?>?action=moneris&ordid=<?php print $orderid?>&check='+response.ticket;
	}
}
myCheckout.setCallback("page_loaded", monerisPageLoad);
myCheckout.setCallback("cancel_transaction", monerisCancelTxn);
myCheckout.setCallback("error_event", monerisErrorEvent);
myCheckout.setCallback("payment_receipt", monerisPaymentReceipt);
myCheckout.setCallback("payment_complete", monerisPaymentComplete);
</script>
<?php
					print imageorbuttontag('',(@$GLOBALS['xxCOTxt3']!=''?$GLOBALS['xxCOTxt3']:$GLOBALS['xxCOTxt']),'checkoutbutton checkoutbutton3 widecheckout3','monerisStartCheckout()',TRUE,FALSE,'id="payButton"');
				}else
					print imageorsubmittag(@$imgcheckoutbutton3,(@$GLOBALS['xxCOTxt3']!=''?$GLOBALS['xxCOTxt3']:$GLOBALS['xxCOTxt']),'widecheckout3',@$GLOBALS['closeorderimmediately']?'onclick="docloseorder()"':'');
			} ?>
			  </div>
<?php	} ?>
			</div>
		</div>
<?php	if($shipType==4 || $shipType==11){ ?>
			<div class="carriertm" style="text-align:center;font-size:10px;padding:6px"><?php print $GLOBALS['xxUPStm']?></div>
<?php	}elseif($shipType==7 || $shipType==8){ ?>
			<div class="carriertm" style="text-align:center;font-size:10px;padding:6px"><?php print $GLOBALS['fedexcopyright']?></div>
<?php	}
		print '</form>' . "\r\n" . '<form method="post" name="shipform" id="shipform" action="cart'.$GLOBALS['extension'] . (getget('action')=='termpp'&&preg_match('/[\w]+/',getget('paymentID'))?'?action=termpp&paymentID='.getget('paymentID'):'') . '">';
		print whv('mode','go') . whv('sessionid',$thesessionid) . whv('orderid',$orderid) . whv('cpncode',$rgcpncode) . whv('token',$token) . whv('payerid',$payerid);
		writehiddenidvar('altrates',$shipType);
		writehiddenidvar('shipselectoridx','');
		writehiddenidvar('shipselectoraction','');
		writehiddenidvar('numshiprate',$numshiprate);
		writehiddenidvar('changeaction','');
		writehiddenidvar('willpickup','');
		writehiddenidvar('shipformaddinfo','');
		writehiddenidvar('sftermsandconds',getpost('sftermsandconds'));
		if($amazonpayment) writehiddenidvar('amzrefid',$amzrefid_);
		if($warncheckspamfolder) print whv('warncheckspamfolder','true');
		print '</form>';
		$_SESSION['shipselectoridx']=(is_numeric(getpost('shipselectoridx')) ? getpost('shipselectoridx') : '');
		$_SESSION['shipselectoraction']=(getpost('shipselectoraction')=='selector' || getpost('shipselectoraction')=='altrates' ? getpost('shipselectoraction') : '');
		if(! $fromshipselector && $adminAltRates==2) print '<script>getalternatecarriers();</script>';
	}
	if(@$GLOBALS['nopriceanywhere']&&$success){
		if(recaptchaenabled(256)){
			print '<script>function docheckform(){if(!cardentrycaptchaok){ alert("' . jscheck($GLOBALS['xxRecapt']) . '");return(false); }return(true);}</script>';
			displayrecaptchajs('cardentrycaptcha',TRUE,FALSE);
			print '<div class="cart3header">' . $GLOBALS['xxRecapt'] . '</div>';
			print '<div class="cart2column"><div id="cardentrycaptcha" class="g-recaptcha reCAPTCHAcheckout"></div></div>';
			print '<div class="cart2column">'.imageorsubmit(@$imgcheckoutbutton3,(@$GLOBALS['xxCOTxt3']!=''?$GLOBALS['xxCOTxt3']:$GLOBALS['xxCOTxt']),'checkoutbutton checkoutbutton3').'</div>';
		}
		print '</form>';
		if(!recaptchaenabled(256)) print '<script>document.checkoutform.submit();</script>';
	}
	if(@$GLOBALS['googletagid']!=''){
		print '<script>gtag("event","add_payment_info",{ currency:"' . $countryCurrency . '",value:' . $totalgoods . ',items:[' . getcartforganalytics('') . ']});</script>'."\n";
	}
	if(@$GLOBALS['closeemailordersautomatically']){
		print '<script>if(document.getElementById("ectemailform"))setTimeout("document.getElementById(\'ectemailform\').submit()",' . (is_numeric($GLOBALS['closeemailordersautomatically'])&&$GLOBALS['closeemailordersautomatically']>1?(($GLOBALS['closeemailordersautomatically']-2)*1000):500) . ');';
		if(is_numeric($GLOBALS['closeemailordersautomatically'])&&$GLOBALS['closeemailordersautomatically']>1) print 'var checkoutstart=Date.now()+(' . $GLOBALS['closeemailordersautomatically'] . '*1000);
		document.getElementsByClassName("widecheckout3")[0].innerHTML+=\' - \' + Math.trunc((checkoutstart-Date.now())/1000);
		setInterval(function(){document.getElementsByClassName("widecheckout3")[0].innerHTML=document.getElementsByClassName("widecheckout3")[0].innerHTML.replace(/[0-9]+/g,Math.trunc((checkoutstart-Date.now())/1000));},1000);'."\n";
		print '</script>'."\n";
	}
}elseif(getget('amazon')=='logout'){
	$_SESSION['AmazonLogin']='';
	$_SESSION['AmazonLoginTimeout']='';
}
if($checkoutmode=='checkout'){
	$sSQL="SELECT ordID FROM orders WHERE ordStatus>1 AND ordAuthNumber='' AND " . getordersessionsql();
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		release_stock($rs['ordID']);
		ect_query("UPDATE cart SET cartSessionID='".escape_string($thesessionid)."',cartClientID='" . (@$_SESSION['clientID']!='' ? escape_string($_SESSION['clientID']) : 0) . "' WHERE cartCompleted=0 AND cartOrderID=" . $rs['ordID']) or ect_error();
		ect_query("UPDATE orders SET ordAuthStatus='MODWARNOPEN',ordShipType='MODWARNOPEN' WHERE ordID=" . $rs['ordID']) or ect_error();
	}
	ect_free_result($result);
	$havestate=FALSE;
	if(getpost('checktmplogin')=='x'){
		$_SESSION['clientID']=NULL; unset($_SESSION['clientID']); $_SESSION['clientUser']=NULL; unset($_SESSION['clientUser']); $_SESSION['clientActions']=NULL; unset($_SESSION['clientActions']); $_SESSION['clientLoginLevel']=NULL; unset($_SESSION['clientLoginLevel']); $_SESSION['clientPercentDiscount']=NULL; unset($_SESSION['clientPercentDiscount']);
	}elseif(getpost('checktmplogin')!=''){
		$sSQL="SELECT tmploginname FROM tmplogin WHERE tmploginid='" . escape_string(getpost('sessionid')) . "' AND tmploginchk='" . escape_string(getpost('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,clActions,clLoginLevel,clPercentDiscount,clEmail,clPW FROM customerlogin WHERE clID='" . escape_string($_SESSION['clientID']) . "'";
			$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;
				get_wholesaleprice_sql();
				if($rs['clEmail']!=@$_COOKIE['WRITECLL'] || $rs['clPW']!=@$_COOKIE['WRITECLP']){
					setacookie('WRITECLL',$rs['clEmail'],0);
					setacookie('WRITECLP',$rs['clPW'],0);
				}
			}
		}
		ect_free_result($result);
	}
	if(@$_SESSION['clientID']==''&&@$_COOKIE['ectsessid']!=''&&@$_COOKIE['ecthash']!=''&&is_numeric(@$_COOKIE['ectordid'])&&!$returntocustomerdetails){
		if($_COOKIE['ecthash']==hash('sha256',$_COOKIE['ectordid'].$_COOKIE['ectsessid'].$adminSecret))
			retrieveorderdetails($_COOKIE['ectordid'],$_COOKIE['ectsessid']);
	}
	if($success){
		if(@$ordZip=='') $ordZip=@$_SESSION['zip'];
		if(@$ordState=='') $ordState=@$_SESSION['state'];
		if(@$ordCountry=='') $ordCountry=@$_SESSION['country'];
	}
	$sSQL='SELECT stateID FROM states INNER JOIN countries ON states.stateCountryID=countries.countryID WHERE countryEnabled<>0 AND stateEnabled<>0 AND loadStates=2 ORDER BY stateCountryID,stateName';
	$result=ect_query($sSQL) or ect_error();
	$hasstates=(ect_num_rows($result)>0);
	ect_free_result($result);
	$sSQL="SELECT countryName,countryOrder,".getlangid('countryName',8)." AS countryName,countryID,loadStates FROM countries WHERE countryEnabled=1 ORDER BY countryOrder DESC," . getlangid("countryName",8);
	$result=ect_query($sSQL) or ect_error();
	while($rs=ect_fetch_assoc($result)){
		$allcountries[$numallcountries++]=$rs;
	}
	ect_free_result($result);
	$addresses=[];
	$numaddresses=0;
	if(@$GLOBALS['enableclientlogin'] && @$_SESSION['clientID']!=''){
		$sSQL="SELECT addID,addIsDefault,addName,addLastName,addAddress,addAddress2,addState,addCity,addZip,addPhone,addCountry,addExtra1,addExtra2 FROM address INNER JOIN countries ON address.addCountry=countries.countryName WHERE countries.countryEnabled<>0 AND addCustID='" . escape_string($_SESSION['clientID']) . "' ORDER BY addName,addLastName,addAddress";
		$result=ect_query($sSQL) or ect_error();
		while($rs=ect_fetch_assoc($result))
			$addresses[$numaddresses++]=$rs;
		ect_free_result($result);
	} ?>
			<form method="post" name="mainform" action="cart<?php print $GLOBALS['extension']?>" onsubmit="return checkform(this)">
<?php
	if($numaddresses>0){ ?>
<script><?php print $GLOBALS['wpjavascriptcomments']?>/* <![CDATA[ */
var addrs=new Array();
addrs[0]={'name':'','lastname':'','address':'','address2':'','city':'','state':'','zip':'','phone':'','country':'','extra1':'','extra2':''};
function checkeditbutton(isshipping){
	adidobj=document.getElementById(isshipping + 'addressid');
	theaddy=adidobj[adidobj.selectedIndex].value;
	if(theaddy=='') document.getElementById(isshipping + 'editbutton').disabled=true; else document.getElementById(isshipping + 'editbutton').disabled=false;
}
function editaddress(isshipping,isaddnew){
	eval(isshipping+'checkaddress=true;');
	adidobj=document.getElementById(isshipping + 'addressid');
	theaddy=adidobj[adidobj.selectedIndex].value;
	if(isaddnew)theaddy=0;
	document.getElementById(isshipping + 'ordname').value=addrs[theaddy]['name'];
<?php	if(@$GLOBALS['usefirstlastname']==TRUE) print "document.getElementById(isshipping + 'lastname').value=addrs[theaddy]['lastname'];" ?>
	document.getElementById(isshipping + 'address').value=addrs[theaddy]['address'];
<?php	if(@$GLOBALS['useaddressline2']==TRUE) print "document.getElementById(isshipping + 'address2').value=addrs[theaddy]['address2'];" ?>
	document.getElementById(isshipping + 'city').value=addrs[theaddy]['city'];
	document.getElementById(isshipping + 'zip').value=addrs[theaddy]['zip'];
	document.getElementById(isshipping + 'phone').value=addrs[theaddy]['phone'];
<?php	if(trim_(@$GLOBALS['extraorderfield1'])!='') print "setdefs(document.getElementById('ord'+isshipping+'extra1'),addrs[theaddy]['extra1']);";
		if(trim_(@$GLOBALS['extraorderfield2'])!='') print "setdefs(document.getElementById('ord'+isshipping+'extra2'),addrs[theaddy]['extra2']);"; ?>
	thecntry=document.getElementById(isshipping + 'country')
	foundcntry=9999;
	for(var ind=0; ind < thecntry.length; ind++){
		if(thecntry[ind].value==addrs[theaddy]['countryid']){
			thecntry.selectedIndex=ind;
			foundcntry=ind;
		}
	}
	if(foundcntry==9999)thecntry.selectedIndex=0;
	dynamiccountries(document.getElementById(isshipping+'country'),isshipping);
	foundstate=0;
	checkoutspan(isshipping);
<?php	if($hasstates){ ?>
	thestate=document.getElementById(isshipping + 'state');
	if(countryhasstates[addrs[theaddy]['countryid']]){
		for(var ind=0; ind < thestate.length; ind++){
			if(thestate[ind].value==addrs[theaddy]['stateid'])
				foundstate=ind;
		}
	}else
		document.getElementById(isshipping+'state2').value=addrs[theaddy]['state'];
	thestate.selectedIndex=foundstate;
<?php	} ?>
	showshipform(1,thecntry);
}
<?php	for($ii=0; $ii<$numaddresses; $ii++){
			$countryid=getidfromcountry($addresses[$ii]['addCountry']);
			$stateid=getidfromstate($addresses[$ii]['addState'],$countryid);
			$addresses[$ii]['addPhone']=str_replace('xxx-xxx-xxxx','',$addresses[$ii]['addPhone']);
			print 'addrs[' . $addresses[$ii]['addID'] . "]={'name':'" . jschk($addresses[$ii]['addName']) . "','lastname':'" . jschk($addresses[$ii]['addLastName']) . "','address':'" . jschk($addresses[$ii]['addAddress']) . "','address2':'" . jschk($addresses[$ii]['addAddress2']) . "','state':'" . jschk($addresses[$ii]['addState']) . "','stateid':'" . $stateid . "','city':'" . jschk($addresses[$ii]['addCity']) . "','zip':'" . jschk($addresses[$ii]['addZip']) . "','phone':'" . jschk($addresses[$ii]['addPhone']) . "','country':'" . jschk($addresses[$ii]['addCountry']) . "','countryid':'" . $countryid . "','extra1':'" . jschk($addresses[$ii]['addExtra1']) . "','extra2':'" . jschk($addresses[$ii]['addExtra2']) . "'}\n";
		} ?>
/* ]]> */<?php print $GLOBALS['wpjavascriptendcomments']?></script>
<?php
	}
	print whv('mode','go');
	print whv('sessionid',strip_tags(trim($thesessionid)));
	print whv('PARTNER',strip_tags(getpost('PARTNER')));
	print whv('altrates',strip_tags(getpost('altrates')));
	$colspan2='';
	$colspan3=''; ?>
	<input type="hidden" name="addaddress" id="addaddress" value="<?php print ($numaddresses>0 ? '' : 'add')?>" />
	<input type="hidden" name="saddaddress" id="saddaddress" value="<?php print ($numaddresses>0 ? '' : 'add')?>" />
<?php	if(@$GLOBALS['xxCoStp2']!='') print '<div class="checkoutsteps">' . $GLOBALS['xxCoStp2'] . '</div>'?>
		<div class="cart2details">
<?php
	showcartresumeheader(2);
	if($returntocustomerdetails && $errormsg!='') print '<div class="cobhl cart2column ectwarning">' . $errormsg . "</div>\r\n";
	if($returntocustomerdetails&&getpost('nonce')!='') print whv('nonce',getpost('nonce'));
	if($numaddresses>0){
		print whv('addressarray',1); ?>
				<div class="cartcheckoutsavedaddr">
				  <div class="cartheader cdformtitle"><?php print $GLOBALS['xxBilAdd']?></div>
				  <div class="cdformtitlell">
<?php	function writeaddressspans($isshp){
			global $numaddresses,$addresses,$redstar,$tleft,$tright,$hasstates,$colspan2,$errordname,$errordaddress,$errordcity,$errordstate,$errordcountry,$errordzip,$errordphone;
?>		<span id="<?php print $isshp?>addressspan1" style="display:block"><select class="ectselectinput cdform2fixw" name="<?php print $isshp?>addressid" id="<?php print $isshp?>addressid" size="1" onchange="checkeditbutton('<?php print $isshp?>')"><?php
		if($isshp=='s') print '<option value="">' . $GLOBALS['xxSamAs'] . '</option>';
		for($index=0; $index < $numaddresses; $index++){
			print '<option value="' . $addresses[$index]['addID'] . '"' . ($addresses[$index]['addIsDefault']==($isshp=='s'?2:1) ? ' selected="selected"' : '') . '>' . htmlspecials(trim($addresses[$index]['addName'] . (@$GLOBALS['usefirstlastname']?' '.$addresses[$index]['addLastName']:''))) . ', ' . htmlspecials($addresses[$index]['addAddress']) . (trim($addresses[$index]['addAddress2'])!='' ? ', ' . htmlspecials($addresses[$index]['addAddress2']) : '') . ', ' . htmldisplay($addresses[$index]['addState']) . '</option>';
		} ?></select> <div class="editaddressbuttons"><input type="button" class="ectbutton" value="<?php print $GLOBALS['xxEdit']?>" id="<?php print $isshp?>editbutton" onclick="editaddress('<?php print $isshp?>',false);document.getElementById('<?php print $isshp?>addressspan1').style.display='none';document.getElementById('<?php print $isshp?>addressspan2').style.display='block';document.getElementById('<?php print $isshp?>addaddress').value='edit'"> <input type="button" class="ectbutton" value="<?php print $GLOBALS['xxNew']?>" onclick="editaddress('<?php print $isshp?>',true);document.getElementById('<?php print $isshp?>addressspan1').style.display='none';document.getElementById('<?php print $isshp?>addressspan2').style.display='block';document.getElementById('<?php print $isshp?>addaddress').value='add'"></div>
		</span><div id="<?php print $isshp?>addressspan2" style="display:none">
			<?php	if(trim_(@$GLOBALS['extraorderfield1'])!=''){ ?>
			<div class="billformrow"><div class="cobhl cobhl2 cdformtextra1<?php print @$GLOBALS['extraorderfield1required']?' redstar':''?>"><?php print labeltxt($GLOBALS['extraorderfield1'],'ord'.$isshp.'extra1') ?>:</div><div class="cobll cobll2 cdformextra1"><?php if(@$GLOBALS['extraorderfield1html']!='') print str_replace(array('ectfield','ordextra1'),'ord'.$isshp.'extra1',$GLOBALS['extraorderfield1html']); else print '<input type="text" name="ord'.$isshp.'extra1" id="ord'.$isshp.'extra1" class="ecttextinput cdform1fixw" placeholder="'.placeholder($GLOBALS['extraorderfield1']).'" autocomplete="false"' . (@$GLOBALS['extraorderfield1required']?' aria-required="true"':'') . '>'?></div></div>
			<?php	} ?>
			<div class="billformrow"><div class="cobhl cobhl2 cdformtname redstar<?php print $isshp=='' && $errordname?' ectwarning':''?>"><?php print labeltxt($GLOBALS['xxName'],$isshp.'ordname')?>:</div><div class="cobll cobll2 cdformname"><?php
			if(@$GLOBALS['usefirstlastname'])
				print '<input type="text" name="'.$isshp.'ordname" id="'.$isshp.'ordname" class="ecttextinput cdformsmfixw" placeholder="'.placeholder($GLOBALS['xxFirNam']).'" autocomplete="given-name" aria-required="true"> <input type="text" name="'.$isshp.'lastname" id="'.$isshp.'lastname" class="ecttextinput cdformsmfixw" placeholder="'.placeholder($GLOBALS['xxLasNam']).'" aria-label="' . placeholder($GLOBALS['xxLasNam']) . '" aria-required="true" autocomplete="family-name">';
			else
				print '<input type="text" name="'.$isshp.'ordname" id="'.$isshp.'ordname" class="ecttextinput cdform1fixw" placeholder="'.placeholder($GLOBALS['xxName']).'" aria-required="true">';
			?></div></div>
			<div class="billformrow"><div class="cobhl cobhl2 cdformtaddress redstar<?php print $isshp=='' && $errordaddress?' ectwarning':''?>"><?php print labeltxt($GLOBALS['xxAddress'],$isshp.'address')?>:</div><div class="cobll cobll2 cdformaddress"><input type="text" name="<?php print $isshp?>address" id="<?php print $isshp?>address" class="ecttextinput cdform1fixw" placeholder="<?php print placeholder($GLOBALS['xxAddress'])?>" aria-required="true"></div></div>
			<?php	if(@$GLOBALS['useaddressline2']){ ?>
			<div class="billformrow"><div class="cobhl cobhl2 cdformtaddress2"><?php print labeltxt($GLOBALS['xxAddress2'],$isshp.'address2')?>:</div><div class="cobll cobll2 cdformaddress2"><input type="text" name="<?php print $isshp?>address2" id="<?php print $isshp?>address2" class="ecttextinput cdform1fixw" placeholder="<?php print placeholder($GLOBALS['xxAddress2'])?>"></div></div>
			<?php	} ?>
			<div class="billformrow"><div class="cobhl cobhl2 cdformtcity redstar<?php print $isshp=='' && $errordcity?' ectwarning':''?>"><?php print labeltxt($GLOBALS['xxCity'],$isshp.'city')?>:</div><div class="cobll cobll2 cdformcity"><input type="text" name="<?php print $isshp?>city" id="<?php print $isshp?>city" class="ecttextinput cdform1fixw" placeholder="<?php print placeholder($GLOBALS['xxCity'])?>" aria-required="true"></div></div>
			<div class="billformrow"><div id="<?php print $isshp?>statestar" class="cobhl cobhl2 cdformtstate redstar<?php print $isshp=='' && $errordstate?' ectwarning':''?>"><label class="ectlabel" for="<?php print $isshp?>state" id="<?php print $isshp?>statetxt"><?php print $GLOBALS['xxState']?></label>:</div><div class="cobll cobll2 cdformstate"><?php if($hasstates){ ?><select name="<?php print $isshp?>state" id="<?php print $isshp?>state" size="1" onchange="remwarning(this);dosavestate('')" class="ectselectinput cdform1fixw"><?php $havestate=show_states(-1) ?></select><?php } ?><input type="text" name="<?php print $isshp?>state2" id="<?php print $isshp?>state2" class="ecttextinput cdform1fixw"></div></div>
			<div class="nohidebillrow"><div class="cobhl cobhl2 cdformtcountry redstar<?php print $isshp=='' && $errordcountry?' ectwarning':''?>"><?php print labeltxt($GLOBALS['xxCountry'],$isshp.'country')?>:</div><div class="cobll cobll2 cdformcountry"><select name="<?php print $isshp?>country" id="<?php print $isshp?>country" size="1" onchange="remwarning(this);checkoutspan('<?php print $isshp?>');showshipform(1,this)" class="ectselectinput cdform1fixw"><?php show_countries(-1,TRUE) ?></select></div></div>
			<div class="billformrow"><div id="<?php print $isshp?>zipstar" class="cobhl cobhl2 cdformtzip redstar<?php print $isshp=='' && $errordzip?' ectwarning':''?>"><?php print '<label class="ectlabel" for="'.$isshp.'zip" id="'.$isshp.'ziptxt">' . $GLOBALS['xxZip'] . '</label>'?>:</div><div class="cobll cobll2 cdformzip"><input type="text" name="<?php print $isshp?>zip" id="<?php print $isshp?>zip" class="ecttextinput cdform1fixw" placeholder="<?php print placeholder($GLOBALS['xxZip'])?>" autocapitalize="characters" aria-required="true"></div></div>
			<div class="billformrow"><div class="cobhl cobhl2 cdformtphone redstar<?php print ($isshp=='' && $errordphone?' ectwarning':'')?>"><?php print labeltxt($GLOBALS['xxPhone'],$isshp.'phone')?>:</div><div class="cobll cobll2 cdformphone"><input type="tel" name="<?php print $isshp?>phone" id="<?php print $isshp?>phone" class="ecttextinput cdform1fixw" placeholder="<?php print placeholder($GLOBALS['xxPhone'])?>"<?php print $isshp?' aria-required="true"':''?>></div></div>
			<?php	if(trim_(@$GLOBALS['extraorderfield2'])!=''){ ?>
			<div class="billformrow"><div class="cobhl cobhl2 cdformtextra2<?php print (@$GLOBALS['extraorderfield2required']?' redstar':'')?>"><?php print labeltxt($GLOBALS['extraorderfield2'],'ord'.$isshp.'extra2')?>:</div><div class="cobll cobll2 cdformextra2"><?php if(@$GLOBALS['extraorderfield2html']!='') print str_replace(array('ectfield','ordextra2'),'ord'.$isshp.'extra2',$GLOBALS['extraorderfield2html']); else print '<input type="text" name="ord'.$isshp.'extra2" id="ord'.$isshp.'extra2" class="ecttextinput cdform1fixw" placeholder="'.placeholder($GLOBALS['extraorderfield2']).'" autocomplete="false"' . (@$GLOBALS['extraorderfield2required']?' aria-required="true"':'') . '>'?></div></div>
			<?php	} ?>
			<div class="billformrow"><div class="cobhl cobhl2 cdformtextra2">&nbsp;</div><div class="cobll cobll2 cdformextra2"><input type="button" class="ectbutton cdform2fixw" value="<?php print $GLOBALS['xxCancel']?>" onclick="document.getElementById('<?php print $isshp?>addressspan2').style.display='none';document.getElementById('<?php print $isshp?>addressspan1').style.display='block';document.getElementById('<?php print $isshp?>addaddress').value='';<?php print $isshp?>checkaddress=false;"></div></div>
		</div>
<?php	}
		writeaddressspans(''); ?>
				  </div>
				</div>
<?php	if(!@$GLOBALS['noshipaddress']){ ?>
				<div  class="cartcheckoutsavedaddr cartshipsavedaddr">
				  <div class="cartheader cdformtitle"><?php print $GLOBALS['xxShpAdd']?></div>
				  <div class="cdformtitlell"><?php writeaddressspans('s'); ?></div>
				</div>
<?php	}
		writeshippingflags(2);
	}else{
		if(@$_SESSION['clientID']!=''){
			$result=ect_query("SELECT clUserName,clEmail FROM customerlogin WHERE clID='" . escape_string($_SESSION['clientID']) . "'") or ect_error();
			if($rs=ect_fetch_assoc($result)){
				$ordName=trim($rs['clUserName']);
				if(@$GLOBALS['usefirstlastname']){
					if(strpos(trim($ordName), ' ')!==FALSE){
						$namearr=explode(' ',$ordName,2);
						$ordName=$namearr[0];
						$ordLastName=@$namearr[1];
					}else
						$ordName='';
				}
				$ordEmail=$rs['clEmail'];
			}
			ect_free_result($result);
		}
		function displayzip($isship){
			global $tright,$redstar,$ordShipZip,$ordZip,$errordzip,$errordshipaddress;?>
				<div class="<?php print $isship?'ship':'bill'?>formrow">
				  <div id="<?php print $isship?>zipstar" class="cobhl cobhl2 cdformtzip redstar<?php print ($isship=='' && $errordzip) || ($isship=="s" && $errordshipaddress && $ordShipZip=='')?' ectwarning':''?>"><label class="ectlabel" for="<?php print $isship.'zip'?>" id="<?php print $isship?>ziptxt"><?php print $GLOBALS['xxZip']?></label></div>
				  <div class="cobll cobll2 cdformzip"><input type="text" name="<?php print $isship?>zip" class="cdform2fixw ecttextinput cdformzip" id="<?php print $isship?>zip" value="<?php print htmlspecials($isship?@$ordShipZip:@$ordZip)?>" placeholder="<?php print placeholder($GLOBALS['xxZip'])?>" autocapitalize="characters" aria-required="true"></div>
				</div>
<?php	}
		if(trim_(@$GLOBALS['extraorderfield1'])!=''){ ?>
				<div class="billformrow" style="display:none">
				  <div class="cobhl cobhl2 cdformtextra1"><?php if(@$GLOBALS['extraorderfield1required']) print $redstar;
									print labeltxt($GLOBALS['extraorderfield1'],'ordextra1')?></div>
				  <div class="cobll cobll2 cdformextra1"><?php if(@$GLOBALS['extraorderfield1html']!='') print str_replace('ectfield','ordextra1',$GLOBALS['extraorderfield1html']); else print '<input type="text" name="ordextra1" class="cdform2fixw ecttextinput cdformextra1" id="ordextra1" placeholder="' . placeholder($GLOBALS['extraorderfield1']) . '" value="' . htmlspecials(@$ordExtra1) . '" autocomplete="false" aria-required="' . (@$GLOBALS['extraorderfield1required']?'true':'false') . '">'?></div>
				</div>
<?php	} ?>
				<div class="billformrow" style="display:none">
				  <div class="cobhl cobhl2 cdformtname<?php print $errordname?' ectwarning':''?>"><?php print $redstar . labeltxt($GLOBALS['xxName'],'ordname')?></div>
				  <div class="cobll cobll2 cdformname" style="white-space:nowrap"><?php
		if(@$GLOBALS['usefirstlastname']){
			print '<input type="text" name="ordname" class="cdformsmfixw ecttextinput cdformname" id="ordname" value="' . htmlspecials(@$ordName) . '" placeholder="' . placeholder($GLOBALS['xxFirNam']) . '" autocomplete="given-name" aria-required="true"> <input type="text" name="lastname" id="lastname" class="cdformsmfixw ecttextinput cdformlastname" value="' . htmlspecials(@$ordLastName) . '" placeholder="' . placeholder($GLOBALS['xxLasNam']) . '" autocomplete="family-name" aria-label="' . placeholder($GLOBALS['xxLasNam']) . '" aria-required="true">';
		}else
			print '<input type="text" name="ordname" class="cdform2fixw ecttextinput cdformname" id="ordname" value="' . htmlspecials(@$ordName) . '" placeholder="' . placeholder($GLOBALS['xxName']) . '" aria-required="true">'; ?></div>
				</div>
				<div class="billformrow" style="display:none">
				  <div class="cobhl cobhl2 cdformtemail<?php print $errordemail?' ectwarning':''?>"><?php print $redstar . labeltxt($GLOBALS['xxEmail'],'email')?></div>
				  <div class="cobll cobll2 cdformemail"><input type="email" name="email" class="cdform2fixw ecttextinput cdformemail" id="email" placeholder="<?php print placeholder($GLOBALS['xxEmail'])?>" value="<?php print htmlspecials(@$ordEmail)?>" aria-required="true"></div>
				</div>
<?php	if(@$GLOBALS['verifyemail']){ ?>
				<div class="billformrow" style="display:none">
				  <div class="cobhl cobhl2 cdformtemail<?php print $errordemailv?' ectwarning':''?>"><?php print $redstar . labeltxt($GLOBALS['xxEmVerf'],'email2')?></div>
				  <div class="cobll cobll2 cdformemail"><input type="email" name="email2" class="cdform2fixw ecttextinput cdformemail" id="email2" placeholder="<?php print placeholder($GLOBALS['xxEmVerf'])?>" value="<?php print htmlspecials(@$ordEmail2)?>" aria-required="true"></div>
				</div>
<?php	} ?>
				<div class="billformrow" style="display:none">
				  <div class="cobhl cobhl2 cdformtaddress<?php print $errordaddress?' ectwarning':''?>"><?php print $redstar . labeltxt($GLOBALS['xxAddress'],'address')?></div>
				  <div class="cobll cobll2 cdformaddress"><input type="text" name="address" id="address" class="cdform2fixw ecttextinput cdformaddress" placeholder="<?php print placeholder($GLOBALS['xxAddress'])?>" value="<?php print htmlspecials(@$ordAddress)?>" aria-required="true"></div>
				</div>
<?php	if(@$GLOBALS['useaddressline2']){ ?>
				<div class="billformrow" style="display:none">
				  <div class="cobhl cobhl2 cdformtaddress2"><?php print labeltxt($GLOBALS['xxAddress2'],'address2')?></div>
				  <div class="cobll cobll2 cdformaddress2"><input type="text" name="address2" class="cdform2fixw ecttextinput cdformaddress2" id="address2" placeholder="<?php print placeholder($GLOBALS['xxAddress2'])?>" value="<?php print htmlspecials(@$ordAddress2)?>"></div>
				</div>
<?php	}
		if($GLOBALS['zipposition']==4) displayzip('') ?>
				<div class="billformrow" style="display:none">
				  <div class="cobhl cobhl2 cdformtcity<?php print $errordcity?' ectwarning':''?>"><?php print $redstar . labeltxt($GLOBALS['xxCity'],'city')?></div>
				  <div class="cobll cobll2 cdformcity"><input type="text" name="city" class="cdform2fixw ecttextinput cdformcity" id="city" placeholder="<?php print placeholder($GLOBALS['xxCity'])?>" value="<?php print htmlspecials(@$ordCity)?>" aria-required="true"></div>
				</div>
<?php	if($GLOBALS['zipposition']==3) displayzip('') ?>
				<div class="billformrow" style="display:none">
				  <div id="statestar" class="cobhl cobhl2 cdformtstate redstar<?php print $errordstate?' ectwarning':''?>"><label class="ectlabel" for="state" id="statetxt"><?php print $GLOBALS['xxState']?></label></div>
				  <div class="cobll cobll2 cdformstate"><?php if($hasstates){ ?><select name="state" class="cdform2fixw ectselectinput cdformstate" id="state" size="1" onchange="remwarning(this);dosavestate('')" aria-required="true"><?php $havestate=show_states($ordState) ?></select><?php } ?><input type="text" name="state2" class="cdform2fixw ecttextinput cdformstate" id="state2" style="display:none" placeholder="<?php print placeholder($GLOBALS['xxState'])?>" value="<?php if(! $havestate) print htmlspecials($ordState)?>" aria-required="false"></div>
				</div>
<?php	if($GLOBALS['zipposition']==2) displayzip('') ?>
				<div class="nohidebillrow">
				  <div class="cobhl cobhl2 cdformtcountry<?php print $errordcountry?' ectwarning':''?>"><?php print $redstar . labeltxt($GLOBALS['xxCountry'],'country')?></div>
				  <div class="cobll cobll2 cdformcountry"><select name="country" class="cdform2fixw ectselectinput cdformcountry" id="country" size="1" onchange="remwarning(this);checkoutspan('');showshipform(1,this)" aria-required="true"><?php show_countries(@$ordCountry,TRUE) ?></select></div>
				</div>
<?php	if($GLOBALS['zipposition']==1) displayzip('') ?>
				<div class="billformrow" style="display:none">
				  <div class="cobhl cobhl2 cdformtphone<?php print $errordphone?' ectwarning':''?>"><?php print $redstar . labeltxt($GLOBALS['xxPhone'],'phone')?></div>
				  <div class="cobll cobll2 cdformphone"><input type="tel" name="phone" class="cdform2fixw ecttextinput cdformphone" id="phone" placeholder="<?php print placeholder($GLOBALS['xxPhone'])?>" value="<?php print htmlspecials(@$ordPhone)?>" aria-required="true"></div>
				</div>
<?php	if(trim_(@$GLOBALS['extraorderfield2'])!=''){ ?>
				<div class="billformrow" style="display:none">
				  <div class="cobhl cobhl2 cdformtextra2"><?php if(@$GLOBALS['extraorderfield2required']) print $redstar;
									print labeltxt($GLOBALS['extraorderfield2'],'ordextra2')?></div>
				  <div class="cobll cobll2 cdformextra2"><?php if(@$GLOBALS['extraorderfield2html']!='') print str_replace('ectfield','ordextra2',$GLOBALS['extraorderfield2html']); else print '<input type="text" name="ordextra2" class="cdform2fixw ecttextinput cdformextra2" id="ordextra2" placeholder="' . placeholder($GLOBALS['extraorderfield2']) . '" value="' . htmlspecials(@$ordExtra2) . '" autocomplete="false" aria-required="' . (@$GLOBALS['extraorderfield2required']?'true':'false') . '">'?></div>
				</div>
<?php	}
		writeshippingflags(2);
		if(!@$GLOBALS['noshipaddress']){ ?>
				<div>
				  <div class="cdformshipdiff">
					<input type="hidden" name="shipdiff" id="shipdiff" value="<?php print getpost('shipdiff')=='1' || (trim($ordShipName.$ordShipLastName)!='' && trim($ordShipAddress)!='')?'1':'' ?>">
					<input type="button" class="ectbutton widecheckout2 shipdiff" value="<?php print $GLOBALS['xxShpDff']?>" onclick="document.getElementById('shipdiff').value=document.getElementById('shipdiff').value=='1'?'':'1';checkoutspan('s');showshipform(2,document.getElementById('scountry'))">
				  </div>
				</div>
<?php		if(trim_(@$GLOBALS['extraorderfield1'])!=''){ ?>
				<div class="shipformrow" style="display:none">
				  <div class="cobhl cobhl2 cdformtextra1"><?php if(@$GLOBALS['extraorderfield1required']) print $redstar;
									print labeltxt($GLOBALS['extraorderfield1'],'ordsextra1')?></div>
				  <div class="cobll cobll2 cdformextra1"><?php if(@$GLOBALS['extraorderfield1html']!='') print str_replace(array('ordextra1','ectfield'),'ordsextra1',$GLOBALS['extraorderfield1html']); else print '<input type="text" name="ordsextra1" class="cdform2fixw ecttextinput cdformextra1" id="ordsextra1" placeholder="' . placeholder($GLOBALS['extraorderfield1']) . '" value="' . htmlspecials(@$ordShipExtra1) . '" autocomplete="false" aria-required="' . (@$GLOBALS['extraorderfield1required']?'true':'false') . '">'?></div>
				</div>
<?php		} ?>
				<div class="shipformrow" style="display:none">
				  <div class="cobhl cobhl2 cdformtname<?php print $errordshipaddress && $ordShipName==''?' ectwarning':''?>"><?php print $redstar . labeltxt($GLOBALS['xxName'],'sordname')?></div>
				  <div class="cobll cobll2 cdformname"><?php
		if(@$GLOBALS['usefirstlastname']){
			print '<input type="text" name="sordname" class="cdformsmfixw ecttextinput cdformname" id="sordname" value="' . htmlspecials(@$ordShipName) . '" placeholder="' . placeholder($GLOBALS['xxFirNam']) . '" aria-required="true"> <input type="text" name="slastname" class="cdformsmfixw ecttextinput cdformlastname" id="slastname" value="' . htmlspecials($ordShipLastName) . '" placeholder="' . stripnspecials($GLOBALS['xxLasNam']) . '" aria-label="' . placeholder($GLOBALS['xxLasNam']) . '" aria-required="true">';
		}else
			print '<input type="text" name="sordname" class="cdform2fixw ecttextinput cdformname" id="sordname" value="' . htmlspecials(@$ordShipName) . '" placeholder="' . placeholder($GLOBALS['xxName']) . '" aria-required="true">'; ?></div>
				</div>
				<div class="shipformrow" style="display:none">
				  <div class="cobhl cobhl2 cdformtaddress<?php print $errordshipaddress && $ordShipAddress==''?' ectwarning':''?>"><?php print $redstar . labeltxt($GLOBALS['xxAddress'],'saddress')?></div>
				  <div class="cobll cobll2 cdformaddress"><input type="text" name="saddress" class="cdform2fixw ecttextinput cdformaddress" id="saddress" placeholder="<?php print placeholder($GLOBALS['xxAddress'])?>" value="<?php print htmlspecials(@$ordShipAddress)?>" aria-required="true"></div>
				</div>
<?php		if(@$GLOBALS['useaddressline2']){ ?>
				<div class="shipformrow" style="display:none">
				  <div class="cobhl cobhl2 cdformtaddress2"><?php print labeltxt($GLOBALS['xxAddress2'],'saddress2')?></div>
				  <div class="cobll cobll2 cdformaddress2"><input type="text" name="saddress2" class="cdform2fixw ecttextinput cdformaddress2" id="saddress2" placeholder="<?php print placeholder($GLOBALS['xxAddress2'])?>" value="<?php print htmlspecials(@$ordShipAddress2)?>"></div>
				</div>
<?php		}
			if($GLOBALS['zipposition']==4) displayzip('s') ?>
				<div class="shipformrow" style="display:none">
				  <div class="cobhl cobhl2 cdformtcity<?php print $errordshipaddress && $ordShipCity==''?' ectwarning':''?>"><?php print $redstar . labeltxt($GLOBALS['xxCity'],'scity')?></div>
				  <div class="cobll cobll2 cdformcity"><input type="text" name="scity" class="cdform2fixw ecttextinput cdformcity" id="scity" placeholder="<?php print placeholder($GLOBALS['xxCity'])?>" value="<?php print htmlspecials(@$ordShipCity)?>" aria-required="true"></div>
				</div>
<?php		if($GLOBALS['zipposition']==2) displayzip('s') ?>
				<div class="shipformrow" style="display:none">
				  <div class="cobhl cobhl2 cdformtcountry<?php print $errordshipaddress && $ordShipCountry==''?' ectwarning':''?>"><?php print $redstar . labeltxt($GLOBALS['xxCountry'],'scountry')?></div>
				  <div class="cobll cobll2 cdformcountry"><select name="scountry" class="cdform2fixw ectselectinput cdformcountry" id="scountry" size="1" onchange="remwarning(this);checkoutspan('s')"><option value=""><?php print $GLOBALS['xxPlsSel']?>...</option><?php show_countries(@$ordShipCountry,FALSE) ?></select></div>
				</div>
<?php		if($GLOBALS['zipposition']==3) displayzip('s') ?>
				<div class="shipformrow" style="display:none">
				  <div id="sstatestar" class="cobhl cobhl2 cdformtstate redstar<?php print $errordshipaddress && $ordShipState==''?' ectwarning':''?>"><label class="ectlabel" for="sstate" id="sstatetxt"><?php print $GLOBALS['xxState']?></label></div>
				  <div class="cobll cobll2 cdformstate"><?php if($hasstates){ ?><select name="sstate" class="cdform2fixw ectselectinput cdformstate" id="sstate" size="1" onchange="remwarning(this);dosavestate('s')"><?php $havestate=show_states($ordShipState) ?></select><?php } ?><input type="text" name="sstate2" class="cdform2fixw ecttextinput cdformstate" id="sstate2" style="display:none" placeholder="<?php print placeholder($GLOBALS['xxState'])?>" value="<?php if(! $havestate) print htmlspecials($ordShipState)?>" aria-required="false"></div>
				</div>
<?php		if($GLOBALS['zipposition']==1) displayzip('s') ?>
				<div class="shipformrow" style="display:none">
				  <div class="cobhl cobhl2 cdformtphone redstar<?php print $errordshipaddress && $ordShipPhone==''?' ectwarning':''?>"><?php print labeltxt($GLOBALS['xxPhone'],'sphone')?></div>
				  <div class="cobll cobll2 cdformphone"><input type="tel" name="sphone" class="cdform2fixw ecttextinput cdformphone" id="sphone" placeholder="<?php print placeholder($GLOBALS['xxPhone'])?>" value="<?php print htmlspecials(@$ordShipPhone)?>"></div>
				</div>
<?php		if(trim_(@$GLOBALS['extraorderfield2'])!=''){ ?>
				<div class="shipformrow" style="display:none">
				  <div class="cobhl cobhl2 cdformtextra2"><?php if(@$GLOBALS['extraorderfield2required']) print $redstar;
									print labeltxt($GLOBALS['extraorderfield2'],'ordsextra2')?></div>
				  <div class="cobll cobll2 cdformextra2"><?php if(@$GLOBALS['extraorderfield2html']!='') print str_replace(array('ordextra2','ectfield'),'ordsextra2',$GLOBALS['extraorderfield2html']); else print '<input type="text" name="ordsextra2" class="cdform2fixw ecttextinput cdformextra2" id="ordsextra2" placeholder="' . placeholder($GLOBALS['extraorderfield2']) . '" value="' . htmlspecials(@$ordShipExtra2) . '" autocomplete="false" aria-required="' . (@$GLOBALS['extraorderfield2required']?'true':'false') . '">'?></div>
				</div>
<?php		}
		} // noshipaddress
	} // ($numaddresses>0)
?>				<div class="cobhl cartheader cart2subheader cart2column"><?php print $GLOBALS['xxMisc']?></div>
<?php
	if(@$GLOBALS['noadditionalinfo']!=TRUE){ ?>
				<div class="checkoutadditionals checkoutadds2col">
				  <div class="cobhl cobhl2 cdformtaddinfo"><?php print labeltxt($GLOBALS['xxAddInf'],'ordAddInfo')?></div>
				  <div class="cobll cobll2 cdformaddinfo"><textarea name="ordAddInfo" id="ordAddInfo" class="addinfo"<?php if(@$GLOBALS['addinfplaceholder']!='') print ' placeholder="' . $GLOBALS['addinfplaceholder'] . '"'?>><?php print htmlspecials(@$ordAddInfo)?></textarea></div>
				</div>
<?php
	}
	if(trim_(@$GLOBALS['extracheckoutfield1'])!=''){
		$checkoutfield1=(@$GLOBALS['extracheckoutfield1required'] ? $redstar : '') . labeltxt($GLOBALS['extracheckoutfield1'],'ordcheckoutextra1');
		$checkoutfield2=(@$GLOBALS['extracheckoutfield1html']!='' ? str_replace('ectfield','ordcheckoutextra1',$GLOBALS['extracheckoutfield1html']) : '<input type="text" name="ordcheckoutextra1" class="cdform2fixw ecttextinput cdformextraco1" id="ordcheckoutextra1" size="20" value="' . htmlspecials(@$ordCheckoutExtra1) . '" placeholder="' . placeholder($GLOBALS['extracheckoutfield1']) . '" autocomplete="false" aria-required="' . (@$GLOBALS['extracheckoutfield1required']?'true':'false') . '">');
?>				<div class="checkoutadditionals checkoutadds2col">
				  <div class="cobhl cobhl2 cdformtextraco1"><?php if(@$GLOBALS['extracheckoutfield1reverse']) print $checkoutfield2; else print $checkoutfield1 ?></div>
				  <div class="cobll cobll2 cdformextraco1"><?php if(@$GLOBALS['extracheckoutfield1reverse']) print $checkoutfield1; else print $checkoutfield2 ?></div>
				</div>
<?php
	}
	if(trim_(@$GLOBALS['extracheckoutfield2'])!=''){
		$checkoutfield1=(@$GLOBALS['extracheckoutfield2required'] ? $redstar : '') . labeltxt($GLOBALS['extracheckoutfield2'],'ordcheckoutextra2');
		$checkoutfield2=(@$GLOBALS['extracheckoutfield2html']!='' ? str_replace('ectfield','ordcheckoutextra2',$GLOBALS['extracheckoutfield2html']) : '<input type="text" name="ordcheckoutextra2" class="cdform2fixw ecttextinput cdformextraco1" id="ordcheckoutextra2" size="20" value="' . htmlspecials(@$ordCheckoutExtra2) . '" placeholder="' . placeholder($GLOBALS['extracheckoutfield2']) . '" autocomplete="false" aria-required="' . (@$GLOBALS['extracheckoutfield2required']?'true':'false') . '">');
?>				<div class="checkoutadditionals checkoutadds2col">
				  <div class="cobhl cobhl2 cdformtextraco2"><?php if(@$GLOBALS['extracheckoutfield2reverse']) print $checkoutfield2; else print $checkoutfield1 ?></div>
				  <div class="cobll cobll2 cdformextraco2"><?php if(@$GLOBALS['extracheckoutfield2reverse']) print $checkoutfield1; else print $checkoutfield2 ?></div>
				</div>
<?php
	}
	if(@$_SESSION['clientID']==''){
		if(@$GLOBALS['enableclientlogin'] && @$GLOBALS['allowclientregistration'] && ! @$GLOBALS['nocreateaccountoncheckout']){ ?>
				<div class="checkoutadditionals checkoutadds2col">
				  <div id="co2newacctbutton" class="cobhl cobhl2 cdformtnewaccount"><?php
			if(@$GLOBALS['enableclientlogin']) displaysoftlogin();
			print imageorbuttontag(@$GLOBALS['imgcreateaccount'],$GLOBALS['xxCreAcc'],'createaccount','co2displaynewaccount()',TRUE);
?>				  </div>
				  <div id="co2newaccttxt" class="cobll cobll2 cdformnewaccount"><?php print $GLOBALS['xxClkCrA']?><br><span class="ectsmallnote"><?php print $GLOBALS['xxCrASvD']?></span>
				  </div>
				</div>
<?php	}
	}
	if(!@$GLOBALS['nomailinglist']){
		$labelfor=' for="coallowemail"'; ?>
				<div class="billformrowflags">
				  <div class="cdaddtflag cdformtmailing<?php print (@$GLOBALS['mailinglistdropdown']?'d':'')?>"<?php print (!@$GLOBALS['mailinglistdropdown']&&@$GLOBALS['mailinglistradios']?' role="radiogroup" aria-labelledby="coallowemaillabel"':'')?>><?php
		if(@$GLOBALS['mailinglistdropdown']){ ?>
					<select name="allowemail" id="coallowemail" class="ectselectinput" size="1">
						<option value=""><?php print $GLOBALS['xxPlsSel']?></option>
						<option value="ON"><?php print $GLOBALS['xxYes']?></option>
						<option value=""><?php print $GLOBALS['xxNo']?></option>
					</select>
<?php	}elseif(@$GLOBALS['mailinglistradios']){
			$labelfor=' id="coallowemaillabel"'; ?>
					<div><?php print labeltxt($GLOBALS['xxYes'],'allowemailradioy')?>&nbsp;<input type="radio" class="ectradio" id="allowemailradioy" name="allowemail" value="ON"></div>
					<div><?php print labeltxt($GLOBALS['xxNo'],'allowemailradion')?>&nbsp;<input type="radio" class="ectradio" id="allowemailradion" name="allowemail" value=""></div>
<?php	}else{ ?>
					<input type="checkbox" name="allowemail" id="coallowemail" class="ectcheckbox cdformcb cdformmailing" value="ON" <?php if(@$allowemaildefaulton) print 'checked="checked"'?>>
<?php	} ?>
				  </div>
				  <div class="cdaddflag cdformmailing<?php print (@$GLOBALS['mailinglistdropdown']?'d':'')?>"><label class="ectlabel"<?php print $labelfor?>><?php print $GLOBALS['xxAlPrEm']?></label><br><span class="ectsmallnote"><?php print $GLOBALS['xxNevDiv']?></span></div>
				</div>
<?php
	}
	if(@$GLOBALS['termsandconditions']){ ?>
				<div class="billformrowflags">
				  <div class="cdaddtflag cdformtterms<?php print $errtermsandconditions?' ectwarning':'' ?>"><input type="checkbox" id="ecttnccheckbox" name="license" class="ectcheckbox cdformcb cdformterms" onchange="ectremoveclass(this,'ectwarning')" value="1" aria-required="true"></div>
				  <div class="cdaddflag cdformterms"><?php print labeltxt($GLOBALS['xxTermsCo'],'ecttnccheckbox')?></div>
				</div>
<?php
	}
	if(!@$GLOBALS['nogiftcertificate']){ ?>
				<div class="checkoutadditionals checkoutadds2col"><div class="cobhl cobhl2 cdformtcoupon"><?php print labeltxt($GLOBALS['xxGifNum'],'cpncode')?></div><div class="cobll cobll2 cdformcoupon">
			<div><input type="text" name="cpncode" class="cdform2fixw ecttextinput cdformcoupon" id="cpncode" placeholder="<?php print placeholder($GLOBALS['xxGifNum'])?>" size="<?php print $mobilebrowser?14:20?>" autocomplete="off" /> <?php print imageorbuttontag(@$imgapplycoupon,$GLOBALS['xxApply'],'applycoupon applycoupon2','applycert()',TRUE) ?></div>
		<div id="cpncodespan"><?php
		if(@$_SESSION['giftcerts']!='' || @$_SESSION['cpncode']!=''){
			print '<div style="display:table">';
			if(trim_(@$_SESSION['giftcerts'])!=''){
				$gcarr=explode(' ', trim_(@$_SESSION['giftcerts']));
				foreach($gcarr as $key=>$value){
					print '<div style="display:table-row"><div style="display:table-cell">' . $GLOBALS['xxAppGC'] . '</div><div style="display:table-cell">' . $value . '</div><div style="display:table-cell">(<a href="#" onclick="return removecert(\''.$value.'\')">'.$GLOBALS['xxRemove'].'</a>)</div></div>';
				}
			}
			if(trim_(@$_SESSION['cpncode'])!=''){
				$cpnarr=explode(' ', trim_(@$_SESSION['cpncode']));
				foreach($cpnarr as $key=>$value){
					print '<div style="display:table-row"><div style="display:table-cell">' . $GLOBALS['xxApdCpn'] . '</div><div style="display:table-cell">' . $value . '</div><div style="display:table-cell">(<a href="#" onclick="return removecert(\''.$value.'\')">'.$GLOBALS['xxRemove'].'</a>)</div></div>';
				}
			}
			print '</div>';
		} ?>
		</div>
		</div></div>
<?php
	}
	print whv('token', $token) . whv('payerid', $payerid) . whv('checktmplogin',getpost('checktmplogin'));
	if(! @isset($noemailgiftcertorders)) $noemailgiftcertorders='4';
	$sSQL="SELECT cartID FROM cart WHERE cartCompleted=0 AND (cartProdID='".$giftcertificateid."' OR cartProdID='".$donationid."') AND " . getsessionsql();
	$result=ect_query($sSQL) or ect_error();
	if(ect_num_rows($result)!=0 && $noemailgiftcertorders!='') $exclemail=$noemailgiftcertorders.','; else $exclemail='';
	ect_free_result($result);
	$ppsql=' AND NOT (payProvID IN ('.$exclemail.'19,20,21,26' . (@$paypalhostedsolution?',18':'') . '))';
	if($ordPayProvider=='19' && getget('token')!='')$ppsql=' AND payProvID=19';
	if($ordPayProvider=='26' && getpost('nonce')!='')$ppsql=' AND payProvID=26';
	$sSQL='SELECT payProvID,'.getlangid('payProvShow',128).' FROM payprovider WHERE payProvEnabled=1 AND payProvLevel<=' . $minloglevel . $ppsql . ' ORDER BY payProvOrder';
	$result=ect_query($sSQL) or ect_error();
	if(($ppsuccess=ect_num_rows($result))==0){ ?>
				<div class="cobhl cart2column ectwarning"><?php print @$errormsg!=''?$errormsg:$GLOBALS['xxNoPay']?></div>
<?php
	}elseif(ect_num_rows($result)==1){
		$rs=ect_fetch_assoc($result);
		print whv('payprovider',$rs['payProvID']);
		$nodefaultpayprovider=FALSE;
		$GLOBALS['payproviderradios']='';
	}else{
		if(@$GLOBALS['payproviderradios']==1){
			$showtitle=TRUE;
			while($rs=ect_fetch_assoc($result)){
				print '<div class="checkoutadditionals copayradio1"><div class="cobhl cdformpayradio1">';
				print $showtitle ? '<div class="cdformtpayradio1">' . $GLOBALS['xxPlsChz'] . '</div>' : '';
				print '<input type="radio" name="payprovider" id="pprovid' . $rs['payProvID'] . '" class="ectradio cdformradio cdformpayment" value="' . $rs['payProvID'] . '"';
				if(@$ordPayProvider==$rs['payProvID'] || ($ordPayProvider=='' && @$nodefaultpayprovider!=TRUE)){ print ' checked="checked"'; $ordPayProvider='-1'; }
				print ' /></div><div class="cobll cobll2 cdformpayment"><label class="ectlabel cdformradio" for="pprovid' . $rs['payProvID'] . '">' . $rs[getlangid('payProvShow',128)] . ($rs['payProvID']==1?'<img src="images/paypalacceptmark.gif" style="vertical-align:middle;padding-left:15px" alt="PayPal Payments" />':'') . '</label></div>';
				print "</div>\n";
				$showtitle=FALSE;
			}
		}else{ ?>
				<div class="checkoutadditionals checkoutadds2col"><div class="cobhl cobhl2 cdformtpayment"><?php print $GLOBALS['xxPlsChz']?></div>
				  <div class="cobll cobll2 cdformpayment"><?php
			if(@$GLOBALS['payproviderradios']==2){
				print '<div class="payprovider">';
				while($rs=ect_fetch_assoc($result)){
					print '<label class="ectlabel cdformradio"><input type="radio" name="payprovider" class="ectradio cdformradio cdformpayment" value="' . $rs['payProvID'] . '"';
					if(@$ordPayProvider==$rs['payProvID'] || ($ordPayProvider=='' && @$nodefaultpayprovider!=TRUE)){ print ' checked="checked"'; $ordPayProvider='-1'; }
					print ' />' . $rs[getlangid('payProvShow',128)] . ($rs['payProvID']==1?'<img src="images/paypalacceptmark.gif" alt="PayPal Payments" style="vertical-align:bottom;margin-left:3px" />':'') . '</label>';
				}
				print '</div>';
			}else{
				print '<select name="payprovider" class="cdform2fixw ectselectinput cdformpayment" size="1" onchange="remwarning(this)">';
				if(@$nodefaultpayprovider==TRUE) print '<option value="">'.$GLOBALS['xxPlsSel'].'</option>';
				while($rs=ect_fetch_assoc($result)){
					print '<option value="' . $rs['payProvID'] . '"' . (@$ordPayProvider==$rs['payProvID'] ? ' selected="selected"' : '') . '>' . $rs[getlangid('payProvShow',128)] . '</option>';
				}
				print '</select>';
			}	?></div>
				</div>
<?php	}
	}
	ect_free_result($result);
	if($ppsuccess){ ?>
				<div>
				  <div class="cobll cart2column checkoutbutton2"><?php print imageorsubmit(@$imgcheckoutbutton2,(@$GLOBALS['xxCOTxt2']!=''?$GLOBALS['xxCOTxt2']:$GLOBALS['xxCOTxt']),'widecheckout2')?></div>
				</div><?php
	} ?>	  </div>
			</div>
		</form>
<script><?php print $GLOBALS['wpjavascriptcomments']?>/* <![CDATA[ */
var allinputs=document.forms.mainform.getElementsByTagName('input');
for(var i=0; i<allinputs.length; i++){
	fieldtype=(allinputs[i].type?allinputs[i].type:'radio');
	if(fieldtype=='text'||fieldtype=='textarea'||fieldtype=='email'||fieldtype=='tel'){allinputs[i].onchange=function(){if(this.value!='')remwarning(this);};allinputs[i].onkeyup=function(){if(this.value!='')remwarning(this);}};
}
var globcurobj=[];
function doshowshipform(itm){
	var elem=document.getElementsByTagName('div');
	for(var i=0; i<elem.length; i++){
		var classes=elem[i].className;
		var issel=((itm==2?document.getElementById('shipdiff').value=='1':globcurobj[itm].selectedIndex!=0||globcurobj[itm].options.length<=1)?'':'none');
		if(classes.indexOf((itm==1?'bill':'ship')+'formrow')!=-1){
			if(elem[i].style.display!=issel){
				elem[i].style.display=issel;
				setTimeout("doshowshipform("+itm+");", 30);
				return;
			}
		}
	}
}
function showshipform(itm,curobj){
	globcurobj[itm]=curobj;
	doshowshipform(itm);
}
var checkedfullname=false,isshipcheckouterr=false;
var checkaddress=true,scheckaddress=true;
var checkouterrtxt='';
function chkextra(isship,ob,fldtxt){
	var hasselected=false,fieldtype='';
	if(ob){
		fieldtype=(ob.type?ob.type:'radio');
		if(fieldtype=='text'||fieldtype=='textarea'||fieldtype=='password'){
			hasselected=ob.value!='';
		}else if(fieldtype=='select-one'){
			hasselected=ob.selectedIndex!=0;
		}else if(fieldtype=='radio'){
			for(var ii=0;ii<ob.length;ii++)if(ob[ii].checked)hasselected=true;
		}else if(fieldtype=='checkbox')
			hasselected=ob.checked;
		if(!hasselected){
			if(checkouterrtxt==''){
				if(ob.focus)ob.focus();else if(ob[0].focus) ob[0].focus();
				if(isship){
					chkconfship(true,ob,"<?php print jscheck($GLOBALS['xxPlsEntr'].' "'.$GLOBALS['xxShpDet'].' / ')?>"+fldtxt+"\".\n\n<?php print jscheck($GLOBALS['xxNoShip'])?>");
				}else
					chkfocus(true,ob,"<?php print jscheck($GLOBALS['xxPlsEntr'])?> \""+fldtxt+"\".");
			}
			if(ob.classList)ectaddclass(ob,'ectwarning');
			return(false);
		}else
			if(ob.classList)ectremoveclass(ob,'ectwarning');
	}else{
		alert("Invalid: " + fldtxt);
		return(false);
	}
	return(true);
}
function setdefs(ob,deftxt){
	var fieldtype='';
	if(ob)fieldtype=(ob.type?ob.type:'radio');<?php if(@$debugmode) print 'else alert("Extra order field id not found");'?>
	if(fieldtype=='text'||fieldtype=='textarea'||fieldtype=='password'){
		ob.value=deftxt;
	}else if(fieldtype=='select-one'){
		for(var ii=0;ii<ob.length;ii++)if(ob[ii].value==deftxt)ob[ii].selected=true;
	}else if(fieldtype=='radio'){
		for(var ii=0;ii<ob.length;ii++)if(ob[ii].value==deftxt)ob[ii].checked=true;
	}else if(fieldtype=='checkbox'){
		if(ob.value==deftxt)ob.checked=true;
	}
}
function zipoptional(cntobj){
var cntid=cntobj[cntobj.selectedIndex].value;
if(cntid==0<?php foreach($zipoptional as $zipval)print '||cntid=='.$zipval;?>)return true; else return false;
}
function stateoptional(cntobj){
var cntid=cntobj[cntobj.selectedIndex].value;
if(false<?php
$result=ect_query('SELECT countryID FROM countries WHERE countryEnabled<>0 AND loadStates<0') or ect_error();
while($rs=ect_fetch_assoc($result)) print '||cntid==' . $rs['countryID'];
ect_free_result($result);
?>)return true; else return false;
}
<?php	if($numaddresses==0){
			if(trim_(@$GLOBALS['extraorderfield1'])!='' && trim(@$ordExtra1)!='') print "setdefs(document.forms.mainform.ordextra1,'".jsspecials($ordExtra1)."');\r\n";
			if(trim_(@$GLOBALS['extraorderfield2'])!='' && trim(@$ordExtra2)!='') print "setdefs(document.forms.mainform.ordextra2,'".jsspecials($ordExtra2)."');\r\n";
			if(!@$GLOBALS['noshipaddress']){
				if(trim_(@$GLOBALS['extraorderfield1'])!='' && trim(@$ordShipExtra1)!='') print "setdefs(document.forms.mainform.ordsextra1,'".jsspecials($ordShipExtra1)."');\r\n";
				if(trim_(@$GLOBALS['extraorderfield2'])!='' && trim(@$ordShipExtra2)!='') print "setdefs(document.forms.mainform.ordsextra2,'".jsspecials($ordShipExtra2)."');\r\n";
			}
		}
		if(trim_(@$GLOBALS['extracheckoutfield1'])!='' && trim(@$ordCheckoutExtra1)!='') print "setdefs(document.forms.mainform.ordcheckoutextra1,'".jsspecials($ordCheckoutExtra1)."');\r\n";
		if(trim_(@$GLOBALS['extracheckoutfield2'])!='' && trim(@$ordCheckoutExtra2)!='') print "setdefs(document.forms.mainform.ordcheckoutextra2,'".jsspecials($ordCheckoutExtra2)."');\r\n"; ?>
function chkfocus(ttest,tobj,ttxt){
	if(ttest){
		if(checkouterrtxt==''){
			if(tobj.focus)tobj.focus();
			checkouterrtxt=ttxt;
		}
		ectaddclass(tobj,'ectwarning');
	}else
		ectremoveclass(tobj,'ectwarning');
	return false;
}
function chkconfship(ttest,tobj,ttxt){
	if(ttest) isshipcheckouterr=true;
	return chkfocus(ttest,tobj,ttxt);
}
function remwarning(tobj){
	ectremoveclass(tobj,'ectwarning');
}
function checkform(frm){
	var cntelem=document.getElementById('country');
	var scntelem=document.getElementById('scountry');
	checkouterrtxt='';
if(checkaddress){
if(frm.country[frm.country.selectedIndex].value=='') return(chkfocus(true,frm.country,"<?php print jscheck($GLOBALS['xxPlsSlct'] . ' ' . $GLOBALS['xxCountry'])?>"));
<?php	if(trim_(@$GLOBALS['extraorderfield1'])!='' && @$GLOBALS['extraorderfield1required']) print 'chkextra(false,frm.ordextra1,"'.jsspecials(strip_tags($GLOBALS['extraorderfield1'])).'");'."\n";?>
chkfocus(frm.ordname.value=="",frm.ordname,"<?php print jscheck($GLOBALS['xxPlsEntr'] . ' "' . (@$GLOBALS['usefirstlastname'] ? $GLOBALS['xxFirNam'] : $GLOBALS['xxName']))?>\".");
<?php	if(@$GLOBALS['usefirstlastname']){ ?>
chkfocus(frm.lastname.value=="",frm.lastname,"<?php print jscheck($GLOBALS['xxPlsEntr'] . ' "' . $GLOBALS['xxLasNam'])?>\".");
<?php	}
		if($numaddresses==0){ ?>
var regex=/[^@]+@[^@]+\.[a-z]{2,}$/i;
chkfocus(!regex.test(frm.email.value),frm.email,"<?php print jscheck($GLOBALS['xxValEm'])?>");
<?php		if(@$GLOBALS['verifyemail']){ ?>
chkfocus(!regex.test(frm.email2.value),frm.email2,"<?php print jscheck($GLOBALS['xxEmVerf'].'\n\n'.$GLOBALS['xxValEm'])?>");
chkfocus(frm.email.value!=frm.email2.value,frm.email2,"<?php print jscheck($GLOBALS['xxEmNoMa'])?>");
<?php		}
		} ?>
chkfocus(frm.address.value=="",frm.address,"<?php print jscheck($GLOBALS['xxPlsEntr'] . ' "' . $GLOBALS['xxAddress'])?>\".");
chkfocus(frm.city.value=="",frm.city,"<?php print jscheck($GLOBALS['xxPlsEntr'] . ' "' . $GLOBALS['xxCity'])?>\".");
	if(stateoptional(cntelem)){
	}else if(stateselectordisabled[0]==false){
<?php	if($hasstates){ ?>
		chkfocus(frm.state.selectedIndex==0,frm.state,"<?php print jscheck($GLOBALS['xxPlsSlct']) . ' '?>"+document.getElementById('statetxt').innerHTML);
<?php	} ?>
	}else
		chkfocus(frm.state2.value=="",frm.state2,"<?php print jscheck($GLOBALS['xxPlsEntr'])?> \""+document.getElementById('statetxt').innerHTML+"\".");
chkfocus(frm.zip.value==""&&!zipoptional(cntelem),frm.zip,"<?php print jscheck($GLOBALS['xxPlsEntr'])?> \""+getziptext(cntelem[cntelem.selectedIndex].value)+"\".");
chkfocus(frm.phone.value=="",frm.phone,"<?php print jscheck($GLOBALS['xxPlsEntr'] . ' "' . $GLOBALS['xxPhone'])?>\".");
<?php if(trim_(@$GLOBALS['extraorderfield2'])!='' && @$GLOBALS['extraorderfield2required']) print 'chkextra(false,frm.ordextra2,"'.jsspecials(strip_tags($GLOBALS['extraorderfield2'])).'");'."\n";?>
}
<?php
if(abs(@$addshippinginsurance)==2 && @$GLOBALS['forceinsuranceselection']){ ?>
chkfocus(frm.wantinsurance.selectedIndex==0,frm.wantinsurance,"<?php print jscheck(strip_tags(str_replace('<br>',"\n",$GLOBALS['xxChoIns'])))?>");
<?php
}
if(!@$GLOBALS['noshipaddress']){ ?>
var xxnoship="\n\n<?php print jscheck($GLOBALS['xxNoShip'])?>";
if(scheckaddress<?php if($numaddresses==0) print "&&document.getElementById('shipdiff').value=='1'"?>){
	chkconfship(frm.scountry[frm.scountry.selectedIndex].value=='',frm.scountry,"<?php print jscheck($GLOBALS['xxPlsSlct'].' "'.$GLOBALS['xxShpDet'].' / '.$GLOBALS['xxCountry'])?>\"."+xxnoship);
<?php	if(trim_(@$GLOBALS['extraorderfield1'])!='' && @$GLOBALS['extraorderfield1required']) print 'chkextra(true,frm.ordsextra1,"'.jsspecials(strip_tags($GLOBALS['extraorderfield1'])).'");'."\n";?>
	chkconfship(frm.sordname.value=="",frm.sordname,"<?php print jscheck($GLOBALS['xxPlsEntr'].' "'.$GLOBALS['xxShpDet'].' / '.$GLOBALS['xxName'])?>\"."+xxnoship);
<?php	if(@$GLOBALS['usefirstlastname']){ ?>
	chkconfship(frm.slastname.value=="",frm.slastname,"<?php print jscheck($GLOBALS['xxPlsEntr'] . ' "' . $GLOBALS['xxLasNam'])?>\"."+xxnoship);
<?php	} ?>
	chkconfship(frm.saddress.value=="",frm.saddress,"<?php print jscheck($GLOBALS['xxPlsEntr'].' "'.$GLOBALS['xxShpDet'].' / '.$GLOBALS['xxAddress'])?>\"."+xxnoship);
	chkconfship(frm.scity.value=="",frm.scity,"<?php print jscheck($GLOBALS['xxPlsEntr'].' "'.$GLOBALS['xxShpDet'].' / '.$GLOBALS['xxCity'])?>\"."+xxnoship);
	if(stateoptional(scntelem)){
	}else if(stateselectordisabled[1]==false){
<?php	if($hasstates){ ?>
		chkconfship(frm.sstate.selectedIndex==0,frm.sstate,"<?php print jscheck($GLOBALS['xxPlsSlct'].' "'.$GLOBALS['xxShpDet'].' / ')?>"+document.getElementById('sstatetxt').innerHTML+"\"."+xxnoship);
<?php	} ?>
	}else
		chkconfship(frm.sstate2.value=="",frm.sstate2,"<?php print jscheck($GLOBALS['xxPlsEntr'].' "'.$GLOBALS['xxShpDet'].' / ')?>"+document.getElementById('sstatetxt').innerHTML+"\"."+xxnoship);
	chkconfship(frm.szip.value==""&&!zipoptional(scntelem),frm.szip,"<?php print jscheck($GLOBALS['xxPlsEntr'].' "'.$GLOBALS['xxShpDet'].' / ')?> \""+getziptext(scntelem[scntelem.selectedIndex].value)+"\"."+xxnoship);
	chkconfship(frm.sphone.value=="",frm.sphone,"<?php print jscheck($GLOBALS['xxPlsEntr'] . ' "' . $GLOBALS['xxShpDet'].' / '.$GLOBALS['xxPhone'])?>\"."+xxnoship);
<?php	if(trim_(@$GLOBALS['extraorderfield2'])!='' && @$GLOBALS['extraorderfield2required']) print 'chkextra(true,frm.ordsextra2,"'.jsspecials(strip_tags($GLOBALS['extraorderfield2'])).'");'."\n";?>
}
<?php }
		if(trim_(@$GLOBALS['extracheckoutfield1'])!='' && @$GLOBALS['extracheckoutfield1required']) print 'chkextra(false,frm.ordcheckoutextra1,"'.jsspecials(strip_tags($GLOBALS['extracheckoutfield1'])).'");'."\n";
		if(trim_(@$GLOBALS['extracheckoutfield2'])!='' && @$GLOBALS['extracheckoutfield2required']) print 'chkextra(false,frm.ordcheckoutextra2,"'.jsspecials(strip_tags($GLOBALS['extracheckoutfield2'])).'");'."\n";
		if(@$GLOBALS['nomailinglist']){
		}elseif(@$GLOBALS['mailinglistdropdown']){ ?>
chkfocus(frm.allowemail.selectedIndex==0,frm.allowemail,"<?php print jscheck($GLOBALS['xxPlSePE'])?>");
<?php	}elseif(@$GLOBALS['mailinglistradios']){ ?>
chkfocus(!(document.getElementById('allowemailradioy').checked||document.getElementById('allowemailradion').checked),document.getElementById('allowemailradioy'),"<?php print jscheck($GLOBALS['xxPlSePE'])?>");
<?php	}
		if(@$GLOBALS['termsandconditions']){ ?>
chkfocus(frm.license.checked==false,frm.license,"<?php print jscheck($GLOBALS['xxPlsProc'])?>");
<?php	}
		if(@$GLOBALS['payproviderradios']!=''&&@$GLOBALS['payproviderradios']!=0){ ?>
hasselected=false;
for(var ii=0;ii<frm.payprovider.length;ii++)if(frm.payprovider[ii].checked)hasselected=true;
chkfocus(!hasselected,frm.payprovider[0],"<?php print jscheck($GLOBALS['xxPlsEntr'] . ' "' . $GLOBALS['xxPlsChz'])?>\".");
<?php	}elseif(@$nodefaultpayprovider){ ?>
chkfocus(frm.payprovider.selectedIndex==0,frm.payprovider,"<?php print jscheck($GLOBALS['xxPlsEntr'] . ' "' . $GLOBALS['xxPlsChz'])?>\".");
<?php	} ?>
if(checkouterrtxt!=''){
	if(isshipcheckouterr){
		if(!confirm(checkouterrtxt)){
			document.getElementById('shipdiff').value='';
			showshipform(2,document.getElementById('scountry'));
			return true;
		}
	}else
		alert(checkouterrtxt);
	return false;
}
<?php	if(!@$GLOBALS['usefirstlastname']){ ?>
var regex=/ /;
if(checkaddress&&!checkedfullname&&!regex.test(frm.ordname.value)){
	alert("<?php print jscheck($GLOBALS['xxFulNam'] . ' "' . $GLOBALS['xxName'])?>\".");
	frm.ordname.focus();
	checkedfullname=true;
	return(false);
}
<?php	} ?>
return true;
}
<?php	if(@$GLOBALS['termsandconditions']) gettermsjsfunction() ?>
var savestate=0;
var ssavestate=0;
function applycertcallback(){
	if(ajaxobj.readyState==4){
		document.getElementById("cpncodespan").innerHTML=ajaxobj.responseText;
	}
}
function applycert(){
	cpncode=document.getElementById("cpncode").value;
	if(cpncode!=""){
		ajaxobj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
		ajaxobj.onreadystatechange=applycertcallback;
		document.getElementById("cpncodespan").innerHTML="<?php print $GLOBALS['xxAplyng']?>...";
		ajaxobj.open("GET", "vsadmin/ajaxservice.php?action=applycert&cpncode="+cpncode, true);
		ajaxobj.send(null);
	}
}
function removecert(cpncode){
	if(cpncode!=""){
		ajaxobj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
		ajaxobj.onreadystatechange=applycertcallback;
		document.getElementById("cpncodespan").innerHTML="<?php print $GLOBALS['xxDeltng']?>...";
		ajaxobj.open("GET", "vsadmin/ajaxservice.php?action=applycert&act=delete&cpncode="+cpncode, true);
		ajaxobj.send(null);
		document.getElementById("cpncode").value="";
	}
	return false;
}
function dosavestate(shp){
	thestate=eval('document.forms.mainform.'+shp+'state');
	eval(shp+'savestate=thestate.selectedIndex');
}
function checkoutspan(shp){
	var stateopt=stateoptional(ectById(shp+'country'));
	ectById(shp+'zip').setAttribute('aria-required',zipoptional(ectById(shp+'country'))?'false':'true');
	if(zipoptional(ectById(shp+'country'))) ectremoveclass(ectById(shp+'zipstar'),'redstar'); else ectaddclass(ectById(shp+'zipstar'),'redstar');
	if(stateopt) ectremoveclass(ectById(shp+'statestar'),'redstar'); else ectaddclass(ectById(shp+'statestar'),'redstar');
	if(ectById(shp+'state'))thestate=ectById(shp+'state');
	dynamiccountries(ectById(shp+'country'),shp);
	if(!stateselectordisabled[shp=='s'?1:0]&&!stateopt){
		if(ectById(shp+'state2')){
			ectById(shp+'state2').setAttribute('aria-required','false');
			ectById(shp+'state2').style.display='none';
		}
		if(ectById(shp+'state')){
			ectById(shp+'state').setAttribute('aria-required',stateopt?'false':'true');
			thestate.disabled=false;
			eval('thestate.selectedIndex='+shp+'savestate');
			ectById(shp+'state').style.display='';
			ectById(shp+'statetxt').htmlFor=shp+'state';
		}
	}else{
		if(ectById(shp+'state2')){
			ectById(shp+'state2').setAttribute('aria-required',stateopt?'false':'true');
			ectById(shp+'state2').style.display='';
			ectById(shp+'statetxt').htmlFor=shp+'state2';
		}
		if(ectById(shp+'state')){
			ectById(shp+'state').setAttribute('aria-required','false');
			ectById(shp+'state').style.display='none';
			if(!thestate.disabled){
				thestate.disabled=true;
				eval(shp+'savestate=thestate.selectedIndex');
				thestate.selectedIndex=0;
			}
		}
	}
}
<?php
	createdynamicstates('SELECT stateID,stateAbbrev,stateName,stateName2,stateName3,stateCountryID,countryName FROM states INNER JOIN countries ON states.stateCountryID=countries.countryID WHERE countryEnabled<>0 AND stateEnabled<>0 AND loadStates=2 ORDER BY stateCountryID,' . getlangid('stateName',1048576));
	if($numaddresses>0) print "checkaddress=false;scheckaddress=false;\r\n";
	if($numaddresses>0 && !@$GLOBALS['noshipaddress']) print "checkeditbutton('s');";
	print "checkoutspan('');\r\n";
	if(!@$GLOBALS['noshipaddress']) print "checkoutspan('s');\r\n";
	print "setinitialstate('');setinitialstate('s');\r\n";
	if($numaddresses==0){
		print "showshipform(1,ectById('country'));\r\n";
		if(!@$GLOBALS['noshipaddress']) print "showshipform(2,ectById('scountry'));\r\n";
	}
	if(@$_SESSION['clientID']=='' && @$GLOBALS['enableclientlogin'] && @$GLOBALS['allowclientregistration']){ ?>
function co2newacctcallback(){
	if(liajaxobj.readyState==4){
		postdata="email=" + encodeURIComponent(document.getElementById('naemail').value) + "&pw=" + encodeURIComponent(document.getElementById('pass').value);
		document.getElementById('ectsoftpreload').style.display='none';
		document.getElementById('newacctdiv').style.display='';
		if(liajaxobj.responseText.substr(0,7)=='SUCCESS'){
			document.getElementById('softopaquediv').style.display='none';
<?php	if(@$GLOBALS['storeurlssl']!=$GLOBALS['storeurl']){ ?>
			liajaxobj2=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
			liajaxobj2.open('POST','<?php print $GLOBALS['storeurl']?>vsadmin/ajaxservice.php?action=loginaccount',true);
			liajaxobj2.setRequestHeader('Content-type','application/x-www-form-urlencoded');
			liajaxobj2.send(postdata);
<?php	} ?>
			document.getElementById('co2newacctbutton').innerHTML='';
			document.getElementById('co2newaccttxt').innerHTML='<?php print jscheck($GLOBALS['xxAccSuc'])?>';
		}else{
			document.getElementById('accounterrordiv').innerHTML=liajaxobj.responseText.substr(6);
			var className=document.getElementById('accounterrordiv').className;
			if(className.indexOf('ectwarning')==-1)document.getElementById('accounterrordiv').className+=' ectwarning cartnewaccloginerror';
<?php	if(recaptchaenabled(8)) print 'nacaptchaok=false;grecaptcha.reset(nacaptchawidgetid);' ?>
		}
	}
}
function ecttrim(x) {
	return x.replace(/^\s+|\s+$/gm,'');
}
function co2displaynewaccount(){
	displaynewaccount();
	document.getElementById('naname').value=ecttrim(document.getElementById('ordname').value+(document.getElementById('lastname')?' '+document.getElementById('lastname').value:''));
	document.getElementById('naemail').value=document.getElementById('email').value;
}
<?php
	}
	if(@$GLOBALS['googletagid']!=''){
		$sSQL='SELECT SUM(cartProdPrice*cartQuantity) AS thePrice FROM cart WHERE cartCompleted=0 AND ' . getsessionsql();
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)) $totalgoods=$rs['thePrice']; else $totalgoods=0;
		$sSQL='SELECT SUM(coPriceDiff*cartQuantity) AS thePrice FROM cart INNER JOIN cartoptions ON cart.cartID=cartoptions.coCartID WHERE cartCompleted=0 AND ' . getsessionsql();
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)) $totalgoods+=$rs['thePrice'];
		print 'gtag("event","add_shipping_info",{ currency:"' . $countryCurrency . '",value:' . $totalgoods . ',items:[' . getcartforganalytics('') . ']});'."\n";
	}
?>
/* ]]> */<?php print $GLOBALS['wpjavascriptendcomments']?></script><?php
}elseif(getpost('mode')=='authorize'){
	$iframe=$ordauthstatus='';
	$blockuser=checkuserblock('');
	$ordID=escape_string(str_replace("'",'',getpost('ordernumber')));
	$vsRESULT='x';
	$vsRESPMSG=$vsAVSADDR=$vsAVSZIP=$vsTRANSID='';
	$centinelenrolled='N';
	$recaptchasuccess=TRUE;
	if($ordID!=0 && $ordauthstatus!='MODWARNOPEN' && @$cardinalprocessor!='' && @$cardinalmerchant!='' && @$cardinalpwd!=''){
		$sSQL="SELECT ordPrivateStatus FROM orders WHERE ordID='" . escape_string($ordID) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)) $cardinalstring=$rs['ordPrivateStatus']; else $cardinalstring='';
		ect_free_result($result);
		$cardinalMDvars=explode('&',$cardinalstring);
		if(@$cardinalMDvars[0]=='centinelresult'){
			$centinelok=@$cardinalMDvars[1];
			$PAResStatus=@$cardinalMDvars[2];
			$ErrorDesc=@$cardinalMDvars[3];
			$Cavv=@$cardinalMDvars[4];
			$EciFlag=@$cardinalMDvars[5];
			$Xid=@$cardinalMDvars[6];
			$sSQL="UPDATE orders SET ordPrivateStatus='' WHERE ordID='" . escape_string($ordID) . "'";
			ect_query($sSQL) or ect_error();
		}
	}
	if(is_numeric($ordID) && is_numeric(getpost('method'))){
		if(getpayprovdetx(getpost('method'),$data1,$data2,$data3,$ppdata4,$data5,$data6,$ppflag1,$ppflag2,$ppflag3,$ppbits,$demomode,$ppmethod)){
			$sSQL="SELECT ordID,ordAuthStatus FROM orders WHERE ordID='" . escape_string($ordID) . "' AND " . getordersessionsql();
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)) $ordauthstatus=$rs['ordAuthStatus']; else $ordID=0;
			ect_free_result($result);
			$centinelerror=@$ErrorDesc;
			eval('$authorizeextraparams=@$authorizeextraparams' . (int)getpost('method') . ';');
			if(getpost('method')=='14' && @$custompp3ds!=TRUE) $cardinalprocessor='';
		}else
			$ordID=0;
	}else
		$ordID=0;
	if(recaptchaenabled(1) && ! (getpost('method')=='8'||getpost('method')=='22')){
		$recaptchasuccess=checkrecaptcha($errormsg);
		if(! $recaptchasuccess){ $ordID=0; $vsRESPMSG='reCAPTCHA failure. If you inadvertently refreshed this page, please contact customer support.<br>' . $errormsg; }
	}
	if($ordID!=0 && $ordauthstatus!='MODWARNOPEN' && @$cardinalprocessor!='' && @$cardinalmerchant!='' && @$cardinalpwd!='' && $centinelok==''){
		$cardnum=str_replace(' ', '', getpost('ACCT'));
		$exmon=getpost('EXMON');
		$exyear=getpost('EXYEAR');
		$cardname=getpost('cardname');
		$cvv2=getpost('CVV2');
		$issuenum=getpost('IssNum');
		$sSQL="SELECT ordID,ordName,ordLastName,ordCity,ordState,ordCountry,ordPhone,ordHandling,ordZip,ordEmail,ordShipping,ordStateTax,ordCountryTax,ordHSTTax,ordTotal,ordDiscount,ordAddress,ordAddress2,ordIP,ordAuthNumber,ordShipName,ordShipLastName,ordShipAddress,ordShipAddress2,ordShipCity,ordShipState,ordShipCountry,ordShipZip FROM orders WHERE ordID='" . escape_string($ordID) . "'";
		$result=ect_query($sSQL) or ect_error();
		$rs=ect_fetch_assoc($result);
		$sXML='<CardinalMPI>' .
			addtag('Version','1.7') . addtag('MsgType','cmpi_lookup') . addtag('ProcessorId',$cardinalprocessor) . addtag('MerchantId',$cardinalmerchant) . addtag('TransactionPwd',$cardinalpwd) . addtag('TransactionType','C') .
			addtag('Amount',(int)((($rs['ordShipping']+$rs['ordStateTax']+$rs['ordCountryTax']+$rs['ordHSTTax']+$rs['ordTotal']+$rs['ordHandling']+0.001)-$rs['ordDiscount'])*100)) .
			addtag('CurrencyCode',$countryNumCurrency) . addtag('OrderNumber',$ordID) . addtag('OrderDescription','Order id ' . $ordID) . addtag('EMail',$rs['ordEmail']) .
			addtag('UserAgent',@$_SERVER['HTTP_USER_AGENT']) . addtag('BrowserHeader',@$_SERVER['HTTP_ACCEPT']) . addtag('IPAddress',$GLOBALS['REMOTE_ADDR']) .
			addtag('CardNumber',$cardnum) . addtag('CardExpMonth',$exmon) . addtag('CardExpYear',(strlen($exyear)==2?'20':'').$exyear) .
			'</CardinalMPI>';
		ect_free_result($result);
		$theurl='https://'.(getpost('method')=='7'||getpost('method')=='18'?'paypal':'centinel400').'.cardinalcommerce.com/maps/txns.asp';
		if(@$cardinaltestmode) $theurl='https://centineltest.cardinalcommerce.com/maps/txns.asp';
		if(@$cardinalurl!='') $theurl=$cardinalurl;
		if(callcurlfunction($theurl, 'cmpi_msg=' . urlencode($sXML), $res, '', $errormsg, 12)){
			$xmlDoc=new vrXMLDoc($res);
			$nodeList=$xmlDoc->nodeList->childNodes[0];
			$cardinal_orderid=$cardinal_transaction=$cardinal_method='';
			for($i=0; $i < $nodeList->length; $i++){
				if($nodeList->nodeName[$i]=='ACSUrl') $acsurl=$nodeList->nodeValue[$i];
				if($nodeList->nodeName[$i]=='Payload') $_SESSION['cardinal_pareq']=$nodeList->nodeValue[$i];
				if($nodeList->nodeName[$i]=='Enrolled'){ $centinelenrolled=$nodeList->nodeValue[$i]; $_SESSION['centinel_enrolled']=$centinelenrolled; }
				if($nodeList->nodeName[$i]=='OrderId') $_SESSION['cardinal_orderid']=$cardinal_orderid=$nodeList->nodeValue[$i];
				if($nodeList->nodeName[$i]=='TransactionId') $cardinal_transaction=$nodeList->nodeValue[$i];
				if($nodeList->nodeName[$i]=='EciFlag') $_SESSION['EciFlag']=$EciFlag=$nodeList->nodeValue[$i];
				if($nodeList->nodeName[$i]=='ErrorDesc') $centinelerror=$nodeList->nodeValue[$i];
				if($nodeList->nodeName[$i]=='ErrorNo' && $nodeList->nodeValue[$i]=='1360'){ $centinelerror=''; break; }
			}
			if($centinelenrolled=='Y'){
				$_SESSION['cardinal_method']=getpost('method');
				$_SESSION['cardinal_ordernum']=$ordID;
				$_SESSION['cardinal_sessionid']=$thesessionid;
				$_SESSION['cardinal_cardnum']=$cardnum;
				$_SESSION['cardinal_exmon']=getpost('EXMON');
				$_SESSION['cardinal_exyear']=getpost('EXYEAR');
				$_SESSION['cardinal_cardname']=getpost('cardname');
				$_SESSION['cardinal_cvv2']=getpost('CVV2');
				$_SESSION['cardinal_issnum']=getpost('IssNum');
				$sSQL="UPDATE orders SET ordPrivateStatus='" . escape_string(urlencode($cardinal_transaction).'&'.urlencode($cardinal_orderid).'&'.urlencode(getpost('method')).'&'.urlencode($ordID).'&'.urlencode($thesessionid)) . "' WHERE ordID='" . escape_string($ordID) . "'";
				ect_query($sSQL) or ect_error();
				print '<div style="font-weight:bold;padding:5px;margin:5px;text-align:center;">' . $GLOBALS['xxComOrd'] . '<br><br>' . $GLOBALS['xxNoBack'] . '<br><br><iframe id="centinelwin" src="vsadmin/ajaxservice.php?action=centinel&url='.urlencode($acsurl).'" width="440" height="400">Browser error.</iframe></div>';
			}
		}
	}elseif($ordID!=0 && $centinelok=='Y'){
		$cardnum=$_SESSION['cardinal_cardnum'];
		$exmon=$_SESSION['cardinal_exmon'];
		$exyear=$_SESSION['cardinal_exyear'];
		$cardname=$_SESSION['cardinal_cardname'];
		$cvv2=$_SESSION['cardinal_cvv2'];
		$issuenum=$_SESSION['cardinal_issnum'];
		$_SESSION['cardinal_cardnum']=NULL; unset($_SESSION['cardinal_cardnum']);
		$_SESSION['cardinal_exmon']=NULL; unset($_SESSION['cardinal_exmon']);
		$_SESSION['cardinal_exyear']=NULL; unset($_SESSION['cardinal_exyear']);
		$_SESSION['cardinal_cardname']=NULL; unset($_SESSION['cardinal_cardname']);
		$_SESSION['cardinal_cvv2']=NULL; unset($_SESSION['cardinal_cvv2']);
		$_SESSION['cardinal_issnum']=NULL; unset($_SESSION['cardinal_issnum']);
	}elseif($ordID!=0){
		$cardnum=str_replace(' ', '', getpost('ACCT'));
		$exmon=getpost('EXMON');
		$exyear=getpost('EXYEAR');
		$cardname=getpost('cardname');
		$cvv2=getpost('CVV2');
		$issuenum=getpost('IssNum');
	}
	if($ordID==0||$ordauthstatus=='MODWARNOPEN'){
		if($recaptchasuccess){
			if($ordauthstatus=='MODWARNOPEN') $vsRESPMSG=$GLOBALS['xxMoWnRC']; else $vsRESPMSG='Error';
		}
	}elseif($centinelenrolled=='Y'){
		// Do Nothing
	}elseif($centinelok=='N'||$centinelerror!=''){
		$vsRESPMSG=($centinelerror!=''?$centinelerror.'<br>':'').$GLOBALS['xx3DSFai'];
	}elseif(getpost('method')=='33'){
			$grandtotal=0;
			$countryCode='';
			$sSQL="SELECT ordName,ordLastName,ordZip,ordShipping,ordStateTax,ordCountryTax,ordHSTTax,ordHandling,ordTotal,ordDiscount,ordAddress,ordAddress2,ordCity,ordState,ordCountry,ordShipName,ordShipLastName,ordShipAddress,ordShipAddress2,ordShipCity,ordShipState,ordShipCountry,ordShipZip,ordAuthNumber,ordEmail FROM orders WHERE ordPayProvider=33 AND ordStatus<=2 AND ordID='" . $ordID . "'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				$grandtotal=($rs['ordShipping']+$rs['ordStateTax']+$rs['ordCountryTax']+$rs['ordHSTTax']+$rs['ordTotal']+$rs['ordHandling'])-$rs['ordDiscount'];
				$sSQL="SELECT countryID,countryCode FROM countries WHERE countryName='" . escape_string($rs['ordCountry']) . "'";
				$result2=ect_query($sSQL) or ect_error();
				if($rs2=ect_fetch_assoc($result2)){
					$countryid=$rs2['countryID'];
					$countryCode=$rs2['countryCode'];
					$homecountry=($countryid==$origCountryID);
				}
				ect_free_result($result2);
				$ptypes='';
				if(($ppbits&1)==1 || $ppbits==0) $ptypes.='"card"';
				if(($ppbits&2)==2) $ptypes.=',"paypal"';
				//if(($ppbits&4)==4) $ptypes.=',"sofort"';
				if(($ppbits&8)==8) $ptypes.=',"klarna"';
				if(($ppbits&16)==16) $ptypes.=',"ideal"';
				if(($ppbits&32)==32) $ptypes.=',"sepa"';
				if(($ppbits&64)==64) $ptypes.=',"knet"';
				if(($ppbits&128)==128) $ptypes.=',"giropay"';
				if(($ppbits&256)==256) $ptypes.=',"bancontact"';
				if(($ppbits&512)==512) $ptypes.=',"eps"';
				if(($ppbits&1024)==1024) $ptypes.=',"p24"';
				if(($ppbits&2048)==2048) $ptypes.=',"multibanco"';
				$sXML='{"amount":' . round($grandtotal*100) . ',"currency":' . json_encode($countryCurrency) . ',
					"reference":"' . $ordID . '",
					"billing":{"address":{"zip":' . json_encode($rs['ordZip']) . ',"country":' . json_encode($countryCode) . '}},
					"customer":{"name":' . json_encode($ordName) . ',"email":' . json_encode($rs['ordEmail']) . '},
					"allow_payment_methods":[' . trim($ptypes,',') . '],
					"success_url":' . json_encode($storeurlssl.'thanks'.$GLOBALS['extension'].'?ordid='.$ordID) . ',
					"failure_url":' . json_encode($storeurlssl.'thanks'.$GLOBALS['extension'].'?ordid='.$ordID) . ',
					"cancel_url":' . json_encode($storeurlssl.'cart'.$GLOBALS['extension']) . ',
					"capture":' . ($ppmethod==1?'false':'true') . '}';
				$GLOBALS['callcurlfunctionhttperrors']=TRUE;
				$GLOBALS['xmlfnheaders']=array("Authorization: ".$data2,'Content-Type: application/json');
				callcurlfunction('https://api.' . ($demomode?'sandbox.':'') . 'checkout.com/hosted-payments',$sXML,$jres,'',$vsRESPMSG,FALSE);
				if($jres!=''){
					$jsarray=json_decode((string)$jres);
					if(property_exists(@$jsarray,'_links')){
						$redirect_url=$jsarray->{'_links'}->{'redirect'}->{'href'};
						if(ob_get_length()!==FALSE)
							header('Location: ' . $redirect_url);
						else
							print '<meta http-equiv="Refresh" content="'.$cartrefreshseconds.'; URL=' . $redirect_url . '">';
					}else{
						$success=FALSE;
						if(property_exists(@$jsarray,'error_codes'))
							$vsRESPMSG=$jsarray->{'error_codes'}[0];
					}
				}else
					$success=FALSE;
			}else{
				$success=FALSE;
				$vsRESPMSG='Checkout.com order not found';
			}
	}elseif(getpost('method')=='7'||getpost('method')=='8'||getpost('method')=='22'){ // Payflow Pro / Payflow Link / PayPal Advanced
		$vsdetails=explode('&', $data1);
		$vs1=@$vsdetails[0];
		$vs2=@$vsdetails[1];
		$vs3=@$vsdetails[2];
		$vs4=@$vsdetails[3];
		$sSQL="SELECT ordName,ordLastName,ordZip,ordShipping,ordStateTax,ordCountryTax,ordHSTTax,ordHandling,ordTotal,ordDiscount,ordAddress,ordAddress2,ordCity,ordState,ordCountry,ordShipName,ordShipLastName,ordShipAddress,ordShipAddress2,ordShipCity,ordShipState,ordShipCountry,ordShipZip,ordAuthNumber,ordEmail FROM orders WHERE ordID='" . $ordID . "'";
		$result=ect_query($sSQL) or ect_error();
		$rs=ect_fetch_assoc($result);
		$vsAUTHCODE=$rs['ordAuthNumber'];
		$sSQL="SELECT countryID,countryCode FROM countries WHERE countryName='" . escape_string($rs['ordCountry']) . "'";
		$result2=ect_query($sSQL) or ect_error();
		if($rs2=ect_fetch_assoc($result2)){
			$countryid=$rs2['countryID'];
			$countryCode=$rs2['countryCode'];
			$homecountry=($countryid==$origCountryID);
		}
		ect_free_result($result2);
		$sSQL="SELECT countryCode FROM countries WHERE countryName='" . (trim($rs['ordShipAddress'])!='' ? escape_string($rs['ordShipCountry']) : escape_string($rs['ordCountry'])) . "'";
		$result2=ect_query($sSQL) or ect_error();
		if($rs2=ect_fetch_assoc($result2))
			$shipCountryCode=$rs2['countryCode'];
		ect_free_result($result2);
		if(trim($rs['ordShipAddress'])!='') $isshp='Ship'; else $isshp='';
		$ordState=$rs['ordState'];
		$ordShipState=$rs['ord'.$isshp.'State'];
		if(($countryid==1 || $countryid==2) && $homecountry && @$usestateabbrev!=TRUE){
			$ordState=getstateabbrev($ordState);
			$ordShipState=getstateabbrev($ordShipState);
		}
		splitname(getpost('method')=='8'||getpost('method')=='22'?trim($rs['ordName'].' '.$rs['ordLastName']):$cardname, $firstname, $lastname);
		splitname(trim($rs['ord'.$isshp.'Name'].' '.$rs['ord'.$isshp.'LastName']), $shipfirstname, $shiplastname);
		$sXML='PARTNER='.$vs3.'&VENDOR='.$vs2.'&TRXTYPE='.($ppmethod==1?'A':'S').'&TENDER=C&ZIP['.strlen($rs['ordZip']).']='.$rs['ordZip'].'&STREET['.strlen($rs['ordAddress']).']='.$rs['ordAddress']. ($rs['ordAddress2']!='' ? '&STREET2['.strlen($rs['ordAddress2']).']='.$rs['ordAddress2'] : '') . '&CITY['.strlen($rs['ordCity']).']='.$rs['ordCity'].'&STATE['.strlen($ordState).']='.$ordState.'&BILLTOCOUNTRY['.strlen($countryCode).']='.$countryCode.'&FIRSTNAME['.strlen($firstname).']='.$firstname.'&LASTNAME['.strlen($lastname).']='.$lastname.'&EMAIL='.$rs['ordEmail'];
		$sXML.='&SHIPTOZIP['.strlen($rs['ord'.$isshp.'Zip']).']='.$rs['ord'.$isshp.'Zip'].'&SHIPTOSTREET['.strlen($rs['ord'.$isshp.'Address']).']='.$rs['ord'.$isshp.'Address']. ($rs['ord'.$isshp.'Address2']!='' ? '&SHIPTOSTREET2['.strlen($rs['ord'.$isshp.'Address2']).']='.$rs['ord'.$isshp.'Address2'] : '') . '&SHIPTOCITY['.strlen($rs['ord'.$isshp.'City']).']='.$rs['ord'.$isshp.'City'].'&SHIPTOSTATE['.strlen($ordShipState).']='.$ordShipState.'&SHIPTOCOUNTRYCODE['.strlen($shipCountryCode).']='.$shipCountryCode.'&SHIPTOCOUNTRY['.strlen($shipCountryCode).']='.$shipCountryCode.'&SHIPTOFIRSTNAME['.strlen($shipfirstname).']='.$shipfirstname.'&SHIPTOLASTNAME['.strlen($shiplastname).']='.$shiplastname;
		if($issuenum!=''){
			if(strlen($issuenum)==2) $sXML.='&CARDISSUE=' . $issuenum; else $sXML.='&CARDSTART=' . $issuenum;
		}
		$sXML.='&CUSTIP=' . ipv6to4($GLOBALS['REMOTE_ADDR']) . '&PWD=' . $vs4 . '&USER=' . $vs1 . '&CURRENCY=' . $countryCurrency . '&AMT=' . number_format(($rs['ordShipping']+$rs['ordStateTax']+$rs['ordCountryTax']+$rs['ordHSTTax']+$rs['ordTotal']+$rs['ordHandling'])-$rs['ordDiscount'],2,'.','') . '&BUTTONSOURCE=EcommerceTemplatesUS_Cart_PPA' . $authorizeextraparams;
		ect_free_result($result);
		if(getpost('method')=='8'||getpost('method')=='22'){
			$securetokenid='ECTP' . md5($ordID . time() . $adminSecret . $vs4 . $lastname . $firstname);
			$sXML.='&INVNUM=' . $ordID . '&RETURNURL='.$storeurlssl.'thanks'.$GLOBALS['extension'].'&ERRORURL='.$storeurlssl.'thanks'.$GLOBALS['extension'].'&NOTIFYURL='.$storeurlssl.'vsadmin/ppconfirm.php&CREATESECURETOKEN=Y&TEMPLATE=MINLAYOUT&DISABLERECEIPT=TRUE&SECURETOKENID=' . $securetokenid;
			$success=callcurlfunction('https://' . ($demomode?'pilot-':'') . 'payflowpro.paypal.com', $sXML, $curString, '', $errormsg, TRUE);
			$resparr=explode('&',$curString);
			foreach($resparr as $val){
				$itemarr=explode('=',$val);
				if($itemarr[0]=='SECURETOKEN') $SECURETOKEN=$itemarr[1];
				if($itemarr[0]=='RESPMSG') $RESPMSG=$itemarr[1];
			}
			if($RESPMSG=='Approved'){
				$iframe='<iframe style="border:none" src="https://payflowlink.paypal.com/?SECURETOKEN=' . $SECURETOKEN . '&SECURETOKENID=' . $securetokenid . ($demomode?'&MODE=test':'') . ($GLOBALS['mobilebrowser']?'&TEMPLATE=MOBILE':'') . '" width="510" height="610"></iframe>';
				print $iframe;
			}else
				$vsRESPMSG=$RESPMSG;
		}else{
			$sXML.='&COMMENT1=' . $ordID . '&ACCT=' . $cardnum . '&CVV2=' . $cvv2 . '&EXPDATE=' . $exmon . substr($exyear, -2);
			if(@$cardinalprocessor!='' && @$cardinalmerchant!='' && @$cardinalpwd!=''){
				$sXML.='&AUTHSTATUS3DS=' . @$PAResStatus . '&MPIVENDOR3DS=' . @$_SESSION['centinel_enrolled'] . '&CAVV=' . @$Cavv . '&ECI=' . @$EciFlag . '&XID=' . @$Xid;
			}
			if($vsAUTHCODE==''){
				$GLOBALS['xmlfnheaders']=array('X-VPS-REQUEST-ID: ' . $ordID.'.'.rand(1000000,9999999));
				if($success=callcurlfunction('https://' . ($demomode?'pilot-':'') . 'payflowpro.paypal.com', $sXML, $curString, '', $vsRESPMSG, TRUE)){
					if(!is_array($curString)){
						$curStringArr=array();
						while(strlen($curString)!=0){
							if(strpos($curString,'&')!==FALSE) $varString=substr($curString, 0, strpos($curString , "&" )); else $varString=$curString;
							$name=substr($varString, 0, strpos($varString,'='));
							$curStringArr[$name]=substr($varString, (strlen($name)+1) - strlen($varString));
							if(strlen($curString)!=strlen($varString)) $curString=substr($curString,  (strlen($varString)+1) - strlen($curString)); else $curString='';
						}
						$curString=$curStringArr;
					}
					$vsRESULT=$curString['RESULT'];
					$vsRESPMSG=@$curString['RESPMSG'];
					$vsAUTHCODE=@$curString['AUTHCODE'];
					if(array_key_exists('PNREF', $curString))$vsTRANSID=$curString['PNREF'];
					if(array_key_exists('PPREF', $curString))$vsTRANSID=$curString['PPREF'];
					$vsAVSADDR=@$curString['AVSADDR'];
					if(array_key_exists('AVSCODE', $curString))$vsAVSADDR=$curString['AVSCODE'];
					$vsAVSZIP=@$curString['AVSZIP'];
					$vsIAVS=@$curString['IAVS'];
					$vsCVV2=@$curString['CVV2MATCH'];
					if(array_key_exists('ACK', $curString)){
						if($curString['ACK']=='Success'){ $vsRESULT='0'; $vsRESPMSG=$GLOBALS['xxTranAp']; } else $vsRESULT='';
					}
					if(array_key_exists('L_LONGMESSAGE0', $curString))
						$vsRESPMSG=urldecode($curString['L_LONGMESSAGE0']);
					if(array_key_exists('L_ERRORCODE0', $curString))
						$vsERRCODE=$curString['L_ERRORCODE0'];
					if(array_key_exists('DUPLICATE', $curString)){
						if($curString['DUPLICATE']=='1'){ $vsRESULT=''; $vsRESPMSG='DUPLICATE'; $success=FALSE; }
					}
					if($vsRESULT=='0' || $vsRESULT=='126'){
						if($vsRESULT=='126'){ $underreview='Fraud Review:<br>';$vsRESPMSG='Approved'; }else $underreview='';
						ect_query("UPDATE cart SET cartDateAdded='" . date('Y-m-d',time()+($GLOBALS['dateadjust']*60*60)) . "',cartCompleted=1 WHERE cartCompleted<>1 AND cartOrderID='" . $ordID . "'") or ect_error();
						ect_query("UPDATE orders SET ordStatus=3,ordAuthStatus='',ordAVS='" . escape_string($vsAVSADDR . $vsAVSZIP) . "',ordCVV='" . escape_string($vsCVV2) . "',ordAuthNumber='" . escape_string($underreview . $vsAUTHCODE) . "',ordTransID='" . escape_string($vsTRANSID) . "',ordDate='" . date('Y-m-d H:i:s',time()+($GLOBALS['dateadjust']*60*60)) . "',ordPrivateStatus='' WHERE ordAuthNumber='' AND ordID='" . $ordID . "'") or ect_error();
						do_order_success($ordID,$emailAddr,$sendEmail,FALSE,TRUE,TRUE,TRUE);
						$vsRESULT='0';
					}else{
						$vsERRCODE=(int)$vsRESULT;
						ect_query("UPDATE orders SET ordPrivateStatus='".escape_string(strip_tags('(' . $vsERRCODE . ') ' . $vsRESPMSG))."' WHERE ordAuthNumber='' AND ordID='" . $ordID . "'") or ect_error();
						if($vsERRCODE==12||$vsERRCODE==24||$vsERRCODE==114) $vsRESPMSG=$GLOBALS['xxCCErro'];
					}
				}
			}else{
				$vsRESULT='0';
				$vsRESPMSG='Approved';
			}
		}
	}elseif(getpost('method')=='13'){ // Auth.net AIM
		$acceptecheck=($ppbits&1)==1;
		if(@$secretword!=''){
			$data1=upsdecode($data1, $secretword);
			$data2=upsdecode($data2, $secretword);
		}
		$sSQL="SELECT ordID,ordStatus,ordCity,ordState,ordCountry,ordPhone,ordHandling,ordZip,ordEmail,ordShipping,ordStateTax,ordCountryTax,ordHSTTax,ordTotal,ordDiscount,ordAddress,ordAddress2,ordIP,ordAuthNumber,ordShipName,ordShipLastName,ordShipAddress,ordShipAddress2,ordShipCity,ordShipState,ordShipCountry,ordShipZip FROM orders WHERE ordID='" . $ordID . "'";
		$result=ect_query($sSQL) or ect_error();
		$rs=ect_fetch_assoc($result);
		ect_free_result($result);
		$vsAUTHCODE=trim($rs['ordAuthNumber']);
		$ordstatus=trim($rs['ordStatus']);
		$gotvalidresult=FALSE;
		$vsRESULT=-1;
		$saveerrcode='';
		if($vsAUTHCODE==''||$ordstatus<3){
			if(@$authnetemulateurl!=''){
				$sXML='x_version=3.1&x_delim_data=TRUE&x_relay_response=FALSE&x_delim_char=|&x_duplicate_window=15&x_solution_id=AAA172582' .
					'&x_login=' . $data1 . '&x_tran_key=' . $data2 . (@$_SESSION['clientID']!='' ? '&x_cust_id=' . $_SESSION['clientID'] : '') . '&x_invoice_num=' . $rs['ordID'] .
					'&x_amount=' . number_format(($rs['ordShipping']+$rs['ordStateTax']+$rs['ordCountryTax']+$rs['ordHSTTax']+$rs['ordTotal']+$rs['ordHandling'])-$rs['ordDiscount'],2,'.','') .
					'&x_currency_code=' . $countryCurrency . '&x_description=' . substr(urlencode(str_replace('&quot;','"',getpost('description'))),0,255);
				if(getpost('accountnum')!=''){
					$sXML.='&x_method=ECHECK&x_echeck_type=WEB&x_recurring_billing=NO' .
						'&x_bank_acct_name=' . urlencode(getpost('accountname')) . '&x_bank_acct_num=' . urlencode(getpost('accountnum')) .
						'&x_bank_name=' . urlencode(getpost('bankname')) . '&x_bank_aba_code=' . urlencode(getpost('routenumber')) .
						'&x_bank_acct_type=' . urlencode(getpost('accounttype')) . '&x_type=AUTH_CAPTURE';
					if(@$wellsfargo==TRUE){
						$sXML.='&x_customer_organization_type=' . getpost('orgtype');
						if(getpost('taxid')!='')
							$sXML.='&x_customer_tax_id=' . urlencode(getpost('taxid'));
						else
							$sXML.='&x_drivers_license_num=' . urlencode(getpost('licensenumber')) . '&x_drivers_license_state=' . urlencode(getpost('licensestate')) . '&x_drivers_license_dob=' . urlencode(getpost('dldobyear') . '/' . getpost('dldobmon') . '/' . getpost('dldobday'));
					}
				}else{
					$sXML.='&x_method=CC&x_card_num=' . urlencode($cardnum) . '&x_exp_date=' . $exmon . $exyear;
					if($cvv2!='') $sXML.='&x_card_code=' . $cvv2;
					if($ppmethod==1) $sXML.='&x_type=AUTH_ONLY'; else $sXML.='&x_type=AUTH_CAPTURE';
				}
				if(@$cardinalprocessor!='' && @$cardinalmerchant!='' && @$cardinalpwd!=''){
					$sXML.='&x_cardholder_authentication_value=' . urldecode(@$Cavv) . '&x_authentication_indicator=' . (int)@$EciFlag;
				}
				if($cardname!=''){
					if(strstr($cardname,' ')){
						$namearr=explode(' ',$cardname,2);
						$sXML.='&x_first_name=' . urlencode($namearr[0]) . '&x_last_name=' . urlencode(@$namearr[1]);
					}else
						$sXML.='&x_last_name=' . urlencode($cardname);
				}
				$sXML.='&x_address=' . urlencode($rs['ordAddress']);
				if($rs['ordAddress2']!='') $sXML.=urlencode(', ' . $rs['ordAddress2']);
				$sXML.='&x_city=' . urlencode($rs['ordCity']) . '&x_state=' . urlencode($rs['ordState']) . '&x_zip=' . urlencode($rs['ordZip']) . '&x_country=' . urlencode($rs['ordCountry']) . '&x_phone=' . urlencode($rs['ordPhone']) . '&x_email=' . urlencode($rs['ordEmail']);
				if(trim($rs['ordShipName'])!='' || trim($rs['ordShipLastName'])!='' || $rs['ordShipAddress']!=''){
					if(@$GLOBALS['usefirstlastname'])
						$sXML.='&x_ship_to_first_name=' . urlencode(trim($rs['ordShipName'])) . '&x_ship_to_last_name=' . urlencode(trim($rs['ordShipLastName']));
					elseif(strpos(trim($rs['ordShipName']),' ')!==FALSE){
						$namearr=explode(' ',trim($rs['ordShipName']),2);
						$sXML.='&x_ship_to_first_name=' . urlencode($namearr[0]) . '&x_ship_to_last_name=' . urlencode(@$namearr[1]);
					}else
						$sXML.='&x_ship_to_last_name=' . urlencode(trim($rs['ordShipName']));
					$sXML.='&x_ship_to_address=' . urlencode($rs['ordShipAddress']);
					if($rs['ordShipAddress2']!='') $sXML.=urlencode(', ' . $rs['ordShipAddress2']);
					$sXML.='&x_ship_to_city=' . urlencode($rs['ordShipCity']) . '&x_ship_to_state=' . urlencode($rs['ordShipState']) . '&x_ship_to_zip=' . urlencode($rs['ordShipZip']) . '&x_ship_to_country=' . urlencode($rs['ordShipCountry']);
				}
				if(trim($rs['ordIP'])!='') $sXML.='&x_customer_ip=' . urlencode(trim($rs['ordIP']));
				if($demomode) $sXML.='&x_test_request=TRUE';
				if(@$authnetemulateurl=='') $authnetemulateurl='https://secure.authorize.net/gateway/transact.dll';
				$success=TRUE;
				if($blockuser){
					$success=FALSE;
					$vsRESPMSG=$multipurchaseblockmessage;
				}else
					$success=callcurlfunction($authnetemulateurl, $sXML . $authorizeextraparams, $res, '', $vsRESPMSG, TRUE);
				if($success){
					$varString=explode('|', $res);
					if(count($varString)<38){
						$vsRESPMSG='Invalid response: ' . $res;
					}else{
						$vsRESULT=$varString[0];
						$vsERRCODE=(int)$varString[2];
						$vsRESPMSG=$varString[3];
						$vsAUTHCODE=$varString[4];
						$vsAVSADDR=$varString[5];
						$vsTRANSID=$varString[6];
						$vsCVV2=$varString[38];
						$gotvalidresult=TRUE;
					}
				}
			}else{
				splitname($cardname,$firstname,$lastname);
				$sSQL="SELECT countryID,countryCode3,loadStates FROM countries WHERE countryName='" . escape_string($rs['ordCountry']) . "'";
				$result=ect_query($sSQL) or ect_error();
				if($rs2=ect_fetch_assoc($result)){
					$countryid=$rs2['countryID'];
					$countryCode3=$rs2['countryCode3'];
					$homecountry=($rs2['countryID']==$origCountryID);
				}
				$sjson='{"createTransactionRequest":{
					"merchantAuthentication":{"name":' . json_encode($data1) . ',"transactionKey":' . json_encode($data2) . '},
					"transactionRequest":{
						"transactionType":"auth' . ($ppmethod==1?'Only':'Capture') . 'Transaction",
						"amount":"' . number_format(($rs['ordShipping']+$rs['ordStateTax']+$rs['ordCountryTax']+$rs['ordHSTTax']+$rs['ordTotal']+$rs['ordHandling'])-$rs['ordDiscount'],2,'.','') . '",';
				if(getpost('accountnum')!=''&&$acceptecheck){	
					$sjson.='"payment":{"bankAccount":{"accountType":' . json_encode(getpost('accounttype')) . ',"routingNumber":' . json_encode(getpost('routenumber')) . ',"accountNumber":' . json_encode(getpost('accountnum')) . ',"nameOnAccount":' . json_encode(getpost('accountname')) . ',"echeckType":' . json_encode('WEB') . ',"bankName":' . json_encode(getpost('bankname')) . '}},';
				}else{
					$sjson.='"payment":{"creditCard":{"cardNumber":' . json_encode(preg_replace('/[^0-9]/','',$cardnum)) . ',"expirationDate":' . json_encode($exyear . '-' . $exmon) . ',"cardCode":' . json_encode($cvv2) . '}},';
				}
				$sjson.=($demomode?'':'"solution":{"id":"AAA172582"},') .
					'"order":{"invoiceNumber":' . json_encode($ordID) . ',"description":' . json_encode(substr(getpost('description'),0,255)) . '},
					"tax":{"amount":' . json_encode(number_format($rs['ordStateTax']+$rs['ordCountryTax']+$rs['ordHSTTax'],2,'.','')) . '},
					"shipping":{"amount":' . json_encode(number_format($rs['ordShipping'] + (@$GLOBALS['combineshippinghandling']?$rs['ordHandling']:0),2,'.','')) . '},
					"customer":{"email":' . json_encode($rs['ordEmail']) . '},
					"billTo":{
						"firstName":' . json_encode($firstname) . ',"lastName":' . json_encode($lastname) . ',
						"address":' . json_encode($rs['ordAddress']) . ',"city":' . json_encode($rs['ordCity']) . ',"state":' . json_encode($countryid==1&&$homecountry&&!@$GLOBALS['usestateabbrev']?getstateabbrev($rs['ordState']):$rs['ordState']) . ',"zip":' . json_encode($rs['ordZip']) . ',"country":' . json_encode($countryCode3) . ',"phoneNumber":' . json_encode($rs['ordPhone']) . '
					},';
				if(trim($rs['ordShipName'])!='' || trim($rs['ordShipLastName'])!='' || trim($rs['ordShipAddress'])!=''){
					$sSQL="SELECT countryID,countryCode3,loadStates FROM countries WHERE countryName='" . escape_string($rs['ordShipCountry']) . "'";
					$result=ect_query($sSQL) or ect_error();
					if($rs2=ect_fetch_assoc($result)){
						$shipcountryid=$rs2['countryID'];
						$shipCountryCode3=$rs2['countryCode3'];
						$shiphomecountry=($rs2['countryID']==$origCountryID);
					}
					$firstname=$rs['ordShipName']; $lastname=$rs['ordShipLastName'];
					if(! @$GLOBALS['usefirstlastname']) splitname($rs['ordShipName'],$firstname,$lastname);
					$sjson.='"shipTo":{
							"firstName":' . json_encode($firstname) . ',"lastName":' . json_encode($lastname) . ',
							"address":' . json_encode($rs['ordShipAddress']) . ',"city":' . json_encode($rs['ordShipCity']) . ',"state":' . json_encode($shipcountryid==1&&$shiphomecountry&&!@$GLOBALS['usestateabbrev']?getstateabbrev($rs['ordShipState']):$rs['ordShipState']) . ',"zip":' . json_encode($rs['ordShipZip']) . ',"country":' . json_encode($shipCountryCode3) . '
						},';
				}
				$sjson.='"customerIP":' . json_encode(ipv6to4($rs['ordIP'])) . ',
					"transactionSettings":{"setting":[{"settingName":"duplicateWindow","settingValue":"60"}]}}}}';
				if($success=callcurlfunction('https://api' . ($demomode?'test':'') . '.authorize.net/xml/v1/request.api',$sjson,$jres,'',$vsRESPMSG,FALSE)){
					$jres=trim($jres);
					$index=0;
					while($index<strlen($jres)&&ord($jres[$index])>127)
						$index++;
					if($index>0) $jres=substr($jres,$index);
					$jsarray=json_decode((string)$jres);
					if(property_exists(@$jsarray,'transactionResponse') && property_exists(@$jsarray->{'transactionResponse'},'responseCode')) (int)$vsRESULT=@$jsarray->{'transactionResponse'}->{'responseCode'};
					$vsERRCODE=0;
					if(@$jsarray->{'transactionResponse'}->{'errors'}){
						$vsERRCODE=(int)$jsarray->{'transactionResponse'}->{'errors'}[0]->{'errorCode'};
						$vsRESPMSG=$jsarray->{'transactionResponse'}->{'errors'}[0]->{'errorText'};
					}elseif($vsRESULT==4){
						$vsERRCODE=(int)$jsarray->{'transactionResponse'}->{'messages'}[0]->{'code'};
						$vsRESPMSG=$jsarray->{'transactionResponse'}->{'messages'}[0]->{'description'};
					}elseif($vsRESULT==-1){
						$vsERRCODE=(int)@$jsarray->{'messages'}->{'message'}[0]->{'code'};
						$vsRESPMSG=@$jsarray->{'messages'}->{'message'}[0]->{'text'};
					}else
						$vsRESPMSG=$jsarray->{'transactionResponse'}->{'messages'}[0]->{'description'};
					if(is_numeric($vsERRCODE)) $vsERRCODE=(int)$vsERRCODE; else{ $saveerrcode=$vsERRCODE; $vsERRCODE=0; }
					$vsAUTHCODE=@$jsarray->{'transactionResponse'}->{'authCode'};
					$vsAVSADDR=@$jsarray->{'transactionResponse'}->{'avsResultCode'};
					$vsTRANSID=@$jsarray->{'transactionResponse'}->{'transId'};
					$vsCVV2=@$jsarray->{'transactionResponse'}->{'cvvResultCode'};
					$gotvalidresult=TRUE;
				}
			}
			if($gotvalidresult){
				if((int)$vsRESULT==1||$vsERRCODE==253){
					if($vsERRCODE==253) $pendingreason='Pending: FDS'; else $pendingreason='';
					if(getpost('accountnum')!='') $vsAUTHCODE='eCheck';
					$vsRESULT='0'; // Keep in sync with Payflow Pro
					ect_query("UPDATE cart SET cartDateAdded='" . date('Y-m-d',time()+($GLOBALS['dateadjust']*60*60)) . "',cartCompleted=1 WHERE cartCompleted<>1 AND cartOrderID='" . $ordID . "'") or ect_error();
					ect_query("UPDATE orders SET ordStatus=3,ordAuthStatus='".$pendingreason."',ordAVS='".escape_string($vsAVSADDR)."',ordCVV='".escape_string($vsCVV2)."',ordAuthNumber='" . escape_string($vsAUTHCODE) . "',ordTransID='" . escape_string($vsTRANSID) . "',ordDate='" . date('Y-m-d H:i:s',time()+($GLOBALS['dateadjust']*60*60)) . "',ordPrivateStatus='' WHERE ordAuthNumber='' AND ordID='" . $ordID . "'") or ect_error();
					do_order_success($ordID,$emailAddr,$sendEmail,FALSE,TRUE,TRUE,TRUE);
				}elseif($vsERRCODE==252){
					ect_query("UPDATE cart SET cartCompleted=2 WHERE cartCompleted=0 AND cartOrderID=".$ordID) or ect_error();
					ect_query("UPDATE orders SET ordAuthNumber='FDS Review' WHERE ordAuthNumber='' AND ordID=".$ordID) or ect_error();
					$vsRESPMSG=$GLOBALS['xxAuNetR'];
				}elseif($vsERRCODE==27||$vsERRCODE==127){
					ect_query("UPDATE orders SET ordPrivateStatus='".escape_string(strip_tags('(' . $vsERRCODE . ') ' . $vsRESPMSG))."' WHERE ordAuthNumber='' AND ordID='" . $ordID . "'") or ect_error();
					$isavsmismatch=TRUE;
				}elseif($vsERRCODE==6||$vsERRCODE==7||$vsERRCODE==8||$vsERRCODE==78){
					ect_query("UPDATE orders SET ordPrivateStatus='".escape_string(strip_tags('(' . $vsERRCODE . ') ' . $vsRESPMSG))."' WHERE ordAuthNumber='' AND ordID='" . $ordID . "'") or ect_error();
					$vsRESPMSG=$GLOBALS['xxCCErro'];
				}
			}
			if($saveerrcode!='') $vsERRCODE=$saveerrcode;
		}else{
			$vsRESULT='0';
			$vsRESPMSG=$GLOBALS['xxTranAp'];
			$pos=strpos($vsAUTHCODE, '-');
			if(! ($pos===FALSE))
				$vsAUTHCODE=substr($vsAUTHCODE, $pos + 1);
		}
	}elseif(getpost('method')=='14'){ // Custom Payment Processor
		retrieveorderdetails($ordID, $thesessionid);
		$sSQL="SELECT ordID,ordHandling,ordShipping,ordStateTax,ordCountryTax,ordHSTTax,ordTotal,ordDiscount,ordIP,ordAuthNumber FROM orders WHERE ordID='" . $ordID . "'";
		$result=ect_query($sSQL) or ect_error();
		$rs=ect_fetch_assoc($result);
		$ordShipping=$rs['ordShipping'];
		$ordStateTax=$rs['ordStateTax'];
		$ordCountryTax=$rs['ordCountryTax'];
		$ordHSTTax=$rs['ordHSTTax'];
		$ordTotal=$rs['ordTotal'];
		$ordHandling=$rs['ordHandling'];
		$ordDiscount=$rs['ordDiscount'];
		$ordIP=$rs['ordIP'];
		$ordAuthNumber=trim($rs['ordAuthNumber']);
		$vsAUTHCODE=$ordAuthNumber;
		ect_free_result($result);
		$grandtotal=($ordShipping+$ordStateTax+$ordCountryTax+$ordHSTTax+$ordTotal+$ordHandling)-$ordDiscount;
		if($vsAUTHCODE==''){
			include './vsadmin/inc/customppreturn.php';
		}else{
			$vsRESULT='0';
			$vsRESPMSG=$GLOBALS['xxTranAp'];
		}
	}elseif(getpost('method')=='18'){ // PayPal Direct
		@set_time_limit(120);
		$sSQL="SELECT ordID,ordName,ordLastName,ordCity,ordState,ordCountry,ordPhone,ordHandling,ordZip,ordEmail,ordShipping,ordStateTax,ordCountryTax,ordHSTTax,ordTotal,ordDiscount,ordAddress,ordAddress2,ordIP,ordAuthNumber,ordShipName,ordShipLastName,ordShipAddress,ordShipAddress2,ordShipCity,ordShipState,ordShipCountry,ordShipZip FROM orders WHERE ordID='" . $ordID . "'";
		$result=ect_query($sSQL) or ect_error();
		$rs=ect_fetch_assoc($result);
		ect_free_result($result);
		$grandtotal=($rs['ordShipping']+$rs['ordStateTax']+$rs['ordCountryTax']+$rs['ordHSTTax']+$rs['ordTotal']+$rs['ordHandling'])-$rs['ordDiscount'];
		$data2arr=explode('&',$data2);
		$password=urldecode(@$data2arr[0]);
		$isthreetoken=(trim(urldecode(@$data2arr[2]))=='1');
		$signature=''; $sslcertpath='';
		if($isthreetoken){
			$signature=urldecode(@$data2arr[1]);
			if(strpos($data1,'/')!==FALSE){
				$data1arr=explode('/',$data1);
				if($grandtotal<12) $data1=trim($data1arr[1]); else $data1=trim($data1arr[0]);
				$data1arr=explode('/',$password);
				if($grandtotal<12 && strpos($password,'/')!==FALSE) $password=trim($data1arr[1]); else $password=trim($data1arr[0]);
				$data1arr=explode('/',$signature);
				if($grandtotal<12 && strpos($signature,'/')!==FALSE) $signature=trim($data1arr[1]); else $signature=trim($data1arr[0]);
			}
		}else
			$sslcertpath=urldecode(@$data2arr[1]);
		$sSQL="SELECT countryCode FROM countries WHERE countryName='" . escape_string($rs['ordCountry']) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs2=ect_fetch_assoc($result))
			$countryCode=$rs2['countryCode'];
		ect_free_result($result);
		$sSQL="SELECT countryCode FROM countries WHERE countryName='" . escape_string($rs['ordShipCountry']) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs2=ect_fetch_assoc($result))
			$shipCountryCode=$rs2['countryCode'];
		else
			$shipCountryCode='';
		ect_free_result($result);
		if($countryCode=='US' || $countryCode=='CA'){
			$sSQL="SELECT stateAbbrev FROM states WHERE (stateCountryID=1 OR stateCountryID=2) AND stateName='" . escape_string($rs['ordState']) . "'";
			$result=ect_query($sSQL) or ect_error();
			if($rs2=ect_fetch_assoc($result)) $rs['ordState']=$rs2['stateAbbrev'];
			ect_free_result($result);
		}
		if($shipCountryCode=='US' || $shipCountryCode=='CA'){
			$sSQL="SELECT stateAbbrev FROM states WHERE (stateCountryID=1 OR stateCountryID=2) AND stateName='" . escape_string($rs['ordShipState']) . "'";
			$result=ect_query($sSQL) or ect_error();
			if($rs2=ect_fetch_assoc($result)) $rs['ordShipState']=$rs2['stateAbbrev'];
			ect_free_result($result);
		}
		$vsAUTHCODE=trim($rs['ordAuthNumber']);
		splitname($cardname, $firstname, $lastname);
		$cardtype=getcctypefromnum($cardnum);
		if(trim($rs['ordShipAddress'])!='') $doship='Ship'; else $doship='';
		$sXML=ppsoapheader($data1, $password, $signature) .
			'<soap:Body><DoDirectPaymentReq xmlns="urn:ebay:api:PayPalAPI">' .
			'<DoDirectPaymentRequest><Version xmlns="urn:ebay:apis:eBLBaseComponents">60.00</Version>' .
			'  <DoDirectPaymentRequestDetails xmlns="urn:ebay:apis:eBLBaseComponents">' .
			addtag('PaymentAction',$ppmethod==1?'Authorization':'Sale') .
			'	<PaymentDetails>' .
			'	  <OrderTotal currencyID="' . $countryCurrency . '">' . number_format($grandtotal,getDPs($countryCurrency),'.','') . '</OrderTotal>';
			if($rs['ordTotal']>=$rs['ordDiscount']){
				$sXML.='<ItemTotal currencyID="' . $countryCurrency . '">' . number_format($rs['ordTotal']-$rs['ordDiscount'],getDPs($countryCurrency),'.','') . '</ItemTotal>' .
					'<ShippingTotal currencyID="' . $countryCurrency . '">' . number_format($rs['ordShipping'],getDPs($countryCurrency),'.','') . '</ShippingTotal>' .
					'<HandlingTotal currencyID="' . $countryCurrency . '">' . number_format($rs['ordHandling'],getDPs($countryCurrency),'.','') . '</HandlingTotal>' .
					'<TaxTotal currencyID="' . $countryCurrency . '">' . number_format($rs['ordStateTax']+$rs['ordCountryTax']+$rs['ordHSTTax'],getDPs($countryCurrency),'.','') . '</TaxTotal>';
			}
			$sXML.=addtag('ButtonSource','ecommercetemplates_Cart_DP_US') .
			addtag('NotifyURL',$storeurlssl . 'vsadmin/ppconfirm.php') .
			addtag('Custom',$ordID) .
			'	  <ShipToAddress><Name>' . vrxmlencode(trim($rs['ord'.$doship.'Name'].' '.$rs['ord'.$doship.'LastName'])) . '</Name><Street1>' . vrxmlencode($rs['ord'.$doship.'Address']) . '</Street1><Street2>' . vrxmlencode($rs['ord'.$doship.'Address2']) . '</Street2><CityName>' . $rs['ord'.$doship.'City'] . '</CityName><StateOrProvince>' . $rs['ord'.$doship.'State'] . '</StateOrProvince><Country>' . ($doship!='' ? $shipCountryCode : $countryCode) . '</Country><PostalCode>' . $rs['ord'.$doship.'Zip'] . '</PostalCode></ShipToAddress>' .
			'	</PaymentDetails><CreditCard>' .
			addtag('CreditCardType',$cardtype) . addtag('CreditCardNumber',vrxmlencode($cardnum)) . addtag('ExpMonth',$exmon) . addtag('ExpYear',$exyear) .
			'	  <CardOwner>' .
			addtag('Payer',vrxmlencode($rs['ordEmail'])) .
			'<PayerName>' . addtag('FirstName',vrxmlencode($firstname)) . addtag('LastName',vrxmlencode($lastname)) . '</PayerName>' . addtag('PayerCountry',$countryCode) .
			'		<Address>' . addtag('Street1',vrxmlencode($rs['ordAddress'])) . addtag('Street2',vrxmlencode($rs['ordAddress2'])) . addtag('CityName',$rs['ordCity']) . addtag('StateOrProvince',$rs['ordState']) . addtag('Country',$countryCode) . addtag('PostalCode',$rs['ordZip']) . '</Address>' .
			'	  </CardOwner>' .
			addtag('CVV2',$cvv2);
		if($issuenum!=''){
			if(strlen($issuenum)==2) $sXML.=addtag('IssueNumber',$issuenum); else $sXML.=addtag('StartMonth',substr($issuenum,0,2)) . addtag('StartYear',substr($issuenum,2));
		}
		if(@$cardinalprocessor!='' && @$cardinalmerchant!='' && @$cardinalpwd!=''){
			$sXML.='<ThreeDSecureRequest>' . addtag('AuthStatus3ds',@$PAResStatus) . addtag('MpiVendor3ds',@$_SESSION['centinel_enrolled']) . addtag('Cavv',@$Cavv) . addtag('Eci3ds',@$EciFlag) . addtag('Xid',@$Xid) . '</ThreeDSecureRequest>';
		}
		$sXML.=' </CreditCard>' .
			addtag('IPAddress',trim($rs['ordIP'])) . addtag('MerchantSessionId',$rs['ordID']) . 
			'  </DoDirectPaymentRequestDetails>' .
			'</DoDirectPaymentRequest></DoDirectPaymentReq></soap:Body></soap:Envelope>';
		if($demomode) $sandbox='.sandbox'; else $sandbox='';
		$vsRESULT='-1';
		if($vsAUTHCODE==''){
			if($blockuser){
				$success=FALSE;
				$vsRESPMSG=$multipurchaseblockmessage;
			}else
				$success=callcurlfunction('https://api' . ($isthreetoken?'-3t':'') . $sandbox . '.paypal.com/2.0/', $sXML, $res, $sslcertpath, $vsRESPMSG, 25);
			if($success){
				$xmlDoc=new vrXMLDoc($res);
				$vsERRCODE=$vsAUTHCODE=$vsRESPMSG=$vsAVSADDR=$vsTRANSID=$vsCVV2='';
				$nodeList=$xmlDoc->nodeList->childNodes[0];
				for($i=0; $i < $nodeList->length; $i++){
					if($nodeList->nodeName[$i]=='SOAP-ENV:Body'){
						$e=$nodeList->childNodes[$i];
						for($j=0; $j < $e->length; $j++){
							if($e->nodeName[$j]=='DoDirectPaymentResponse'){
								$ee=$e->childNodes[$j];
								for($jj=0; $jj < $ee->length; $jj++){
									if($ee->nodeName[$jj]=='Ack'){
										if($ee->nodeValue[$jj]=='Success' || $ee->nodeValue[$jj]=='SuccessWithWarning'){
											$vsRESULT=1;
											$vsRESPMSG=$GLOBALS['xxTranAp'];
										}
									}elseif($ee->nodeName[$jj]=='TransactionID'){
										$vsAUTHCODE=$ee->nodeValue[$jj];
									}elseif($ee->nodeName[$jj]=='AVSCode'){
										$vsAVSADDR=$ee->nodeValue[$jj];
									}elseif($ee->nodeName[$jj]=='CVV2Code'){
										$vsCVV2=$ee->nodeValue[$jj];
									}elseif($ee->nodeName[$jj]=='Errors'){
										$shortmsg=$themsg=$thecode='';
										$iswarning=FALSE;
										$ff=$ee->childNodes[$jj];
										for($kk=0; $kk < $ff->length; $kk++){
											if($ff->nodeName[$kk]=='ShortMessage'){
												$shortmsg=$ff->nodeValue[$kk];
											}elseif($ff->nodeName[$kk]=='LongMessage'){
												$themsg=$ff->nodeValue[$kk];
											}elseif($ff->nodeName[$kk]=='ErrorCode'){
												$thecode=$ff->nodeValue[$kk];
											}elseif($ff->nodeName[$kk]=='SeverityCode'){
												$iswarning=($ff->nodeValue[$kk]=='Warning');
											}
										}
										if(! $iswarning){
											$vsRESPMSG=($themsg!=''?$themsg:$shortmsg) . ($vsRESPMSG!=''?'<br>'.$vsRESPMSG:'');
											$vsERRCODE=(int)$thecode;
										}
									}
								}
							}
						}
					}
				}
				if((int)$vsRESULT==1){
					$vsRESULT='0'; // Keep in sync with Payflow Pro
					ect_query("UPDATE cart SET cartDateAdded='" . date('Y-m-d',time()+($GLOBALS['dateadjust']*60*60)) . "',cartCompleted=1 WHERE cartCompleted<>1 AND cartOrderID='" . $ordID . "'") or ect_error();
					ect_query("UPDATE orders SET ordStatus=3,ordAuthStatus='',ordAVS='".escape_string($vsAVSADDR)."',ordCVV='".escape_string($vsCVV2)."',ordAuthNumber='" . escape_string($vsAUTHCODE) . "',ordDate='" . date('Y-m-d H:i:s',time()+($GLOBALS['dateadjust']*60*60)) . "',ordPrivateStatus='' WHERE ordAuthNumber='' AND ordID='" . $ordID . "'") or ect_error();
					do_order_success($ordID,$emailAddr,$sendEmail,FALSE,TRUE,TRUE,TRUE);
				}elseif($vsERRCODE!=''){
					$vsERRCODE=(int)$vsERRCODE;
					ect_query("UPDATE orders SET ordPrivateStatus='".escape_string(strip_tags('(' . $vsERRCODE . ') ' . $vsRESPMSG))."' WHERE ordAuthNumber='' AND ordID='" . $ordID . "'") or ect_error();
					if($vsERRCODE==10502||$vsERRCODE==10504||$vsERRCODE==10508||$vsERRCODE==10521||$vsERRCODE==10527||$vsERRCODE==10534||$vsERRCODE==10535||$vsERRCODE==10541||$vsERRCODE==12000||$vsERRCODE==12001||$vsERRCODE==15004)
						$vsRESPMSG=$GLOBALS['xxCCErro'];
				}
			}
		}else{
			$vsRESULT='0';
			$vsRESPMSG=$GLOBALS['xxTranAp'];
			$pos=strpos($vsAUTHCODE, "-");
			if(! ($pos===FALSE))
				$vsAUTHCODE=substr($vsAUTHCODE, $pos + 1);
		}
	}elseif(getpost('method')=='10'){ // Capture Card
		print 'DISABLED!!<br>';
	}else{
		print 'Error';
		exit;
	}
	if($centinelenrolled!='Y'&&((getpost('method')!='8'&&getpost('method')!='22')||$iframe=='')){
		logevent(substr(getipaddress(), 0, 24),'TRANSACTION',$vsRESULT=='0','cart'.$GLOBALS['extension'],'ORDERS');
		if($vsRESPMSG==$GLOBALS['xxAuNetR']){ ?>
		<div class="cart4details">
			<div class="cart4header cartheader"><?php print $GLOBALS['xxTnxOrd']?></div>
			<div class="copayresultrow">
				<div class="cobhl cobhl4"><?php print $GLOBALS['xxTrnRes']?></div><div class="cobll" align="left"><?php print $vsRESPMSG?></div>
			</div>
			<div class="copayresultrow">
				<div class="cobhl cobhl4"><?php print $GLOBALS['xxOrdNum']?></div><div class="cobll cobll4"><?php print $ordID?></div>
			</div>
			<div class="copayresultrow">
				<div class="cobhl cobhl4"><?php print $GLOBALS['xxAutCod']?></div><div class="cobll cobll4">FDS Review</div>
			</div>
		</div>
<?php	}elseif($vsRESULT=='0'){ ?>
	  <form method="post" action="thanks<?php print $GLOBALS['extension']?>" name="checkoutform">
		<input type="hidden" name="xxpreauth" value="<?php print $ordID?>" />
		<input type="hidden" name="xxpreauthmethod" value="<?php print (int)getpost('method')?>" />
		<input type="hidden" name="thesessionid" value="<?php print $thesessionid?>" />
		<div class="cart4details">
			<div class="cart4header cartheader"><?php print $GLOBALS['xxTnxOrd']?></div>
			<div class="copayresultrow">
				<div class="cobhl cobhl4"><?php print $GLOBALS['xxTrnRes']?></div><div class="cobll cobll4"><?php print $vsRESPMSG?></div>
			</div>
			<div class="copayresultrow">
				<div class="cobhl cobhl4"><?php print $GLOBALS['xxOrdNum']?></div><div class="cobll cobll4"><?php print $ordID?></div>
			</div>
			<div class="copayresultrow">
				<div class="cobhl cobhl4"><?php print $GLOBALS['xxAutCod']?></div><div class="cobll cobll4"><?php print $vsAUTHCODE?></div>
			</div>
			<div class="cobll cart2column cart4buttons"><?php print imageorsubmit(@$imgclickforreceipt,$GLOBALS['xxCliCon'],'clickforreceipt')?></div>
		</div>
	  </form>
	  <script>setTimeout("document.checkoutform.submit()",5000);</script>
<?php	}else{ ?>
	  <form method="post" action="cart<?php print $GLOBALS['extension']?>" name="checkoutform">
		<input type="hidden" name="mode" value="<?php print $isavsmismatch?'checkout':'go'?>" />
		<input type="hidden" name="orderid" value="<?php print $ordID?>" />
		<input type="hidden" name="sessionid" value="<?php print $thesessionid?>" />
		<input type="hidden" name="shipselectoridx" value="<?php print @$_SESSION['shipselectoridx']?>" />
		<input type="hidden" name="shipselectoraction" value="<?php print @$_SESSION['shipselectoraction']?>" />
		<input type="hidden" name="altrates" value="<?php print @$_SESSION['altrates']?>" />
		<div class="cart4details">
			<div class="cart4header cartheader"><?php print $GLOBALS['xxSorTrn']?></div>
			<div class="copayresultrow">
				<div class="cobhl cobhl4"><?php print $GLOBALS['xxTrnRes']?></div><div class="cobll cobll4 ectwarning"><?php print (@$vsERRCODE!=''&&@$GLOBALS['debugmode'] ? '(' . $vsERRCODE . ') ' : '') . $vsRESPMSG?></div>
			</div>
			<div class="cobll cart2column cart4buttons"><?php print imageorsubmit(@$imggoback,$GLOBALS['xxGoBack'],'gobackbutton')?></div>
		</div>
	  </form>
<?php	}
	}
}elseif($checkoutmode=='mailinglistsignup'){
	$validsignup=TRUE;
	if(strpos(getpost('mlsuemail'),'@')===FALSE || ! (is_numeric(getpost('mlsectgrp1')) && is_numeric(getpost('mlsectgrp2'))))
		$validsignup=FALSE;
	else{
		$suarr=explode('@',getpost('mlsuemail'));
		if(strlen($suarr[0])!=(int)getpost('mlsectgrp1') || strlen($suarr[1])!=(int)getpost('mlsectgrp2')) $validsignup=FALSE;
	}
	if($validsignup) addtomailinglist(getpost('mlsuemail'),getpost('mlsuname'));
	print '<div style="padding:24px;text-align:center;font-weight:bold">&nbsp;<br>&nbsp;<br>' . ($validsignup?$GLOBALS['xxThkSub']:'Sorry, there was a checksum error signing you up to the mailing list') . '</div>';
	if($warncheckspamfolder==TRUE) print '<div class="chkspamfolder ectwarning">' . $GLOBALS['xxSpmWrn'] . '</div>';
	if(getpost('rp')!='') $thehref=htmlspecials(str_replace(array('"','<'),'',getpost('rp'))); else $thehref=$GLOBALS['storehomeurl'];
	print '<div style="padding:24px;text-align:center;font-weight:bold">' . imageorbuttontag(@$imgcontinueshopping, $GLOBALS['xxCntShp'], 'continueshopping', $thehref, FALSE) . '<br>&nbsp;</div>';
	$_SESSION['MLSIGNEDUP']=TRUE;
}
if(getget('emailconf')!='' || getget('unsubscribe')!=''){
	if(getget('emailconf')!='') $theemail=getget('emailconf'); else $theemail=getget('unsubscribe');
	$sSQL="SELECT email,isconfirmed FROM mailinglist WHERE email='" . escape_string($theemail) . "'";
	$result=ect_query($sSQL) or ect_error();
	$foundemail=FALSE;
	if($rs=ect_fetch_assoc($result)){
		$foundemail=TRUE;
		$isconfirmed=($rs['isconfirmed']!=0);
	}
	ect_free_result($result);
	print '<div class="cartemailconf"><div class="cartemailconftitle">' . $GLOBALS['xxMLConf'] . '</div><div class="cartemailconfaction">';
	if(! $foundemail)
		print $GLOBALS['xxEmNtFn'];
	elseif(getget('unsubscribe')!=''){
		ect_query("DELETE FROM mailinglist WHERE email='" . escape_string($theemail) . "'") or ect_error();
		print $GLOBALS['xxSucUns'];
	}elseif($isconfirmed)
		print $GLOBALS['xxAllSub'];
	else{
		$thecheck=substr(md5($origZip.':'.$GLOBALS['checksumtext'].':'.$theemail.':'.$adminSecret), 0, 12);
		if($thecheck==getget('check')){
			ect_query("UPDATE mailinglist SET isconfirmed=1 WHERE email='" . escape_string($theemail) . "'") or ect_error();
			print $GLOBALS['xxSubAct'];
		}else
			print $GLOBALS['xxSubNAc'];
	}
	print '</div><div class="cartemailconfcontinue"><a class="ectlink" href="' . $GLOBALS['storehomeurl'] . '" onmouseover="window.status=\'' . jsescape($GLOBALS['xxCntShp']) . '\';return true" onmouseout="window.status=\'\';return true">' . jsescape($GLOBALS['xxCntShp']) . '</a></div>';
	print '</div>';
}elseif(getget('mode')=='gw'){
	print '<form method="post" action="cart'.$GLOBALS['extension'].'?mode=gw">' . whv("doupdate","1") . '<div class="cartgiftwrapdiv">';
	print '<div class="giftwrapdetails_cntnr">';
		print '<div class="giftwrapdetails giftwrapid">' . $GLOBALS['xxCODets'] . '</div>';
		print '<div class="giftwrapdetails giftwrapname">' . $GLOBALS['xxCOName'] . '</div>';
		print '<div class="giftwrapdetails giftwrapquant">' . $GLOBALS['xxQuant'] . '</div>';
		print '<div class="giftwrapdetails giftwrapyes">' . $GLOBALS['xxGifWra'] . '</div>';
	print '</div>';
	if(getpost('doupdate')=='1'){
		foreach(@$_POST as $objItem=>$objValue){
			if(substr($objItem,0,5)=='gwset' && is_numeric($objValue)){
				$thecartid=substr($objItem,5);
				if(is_numeric($thecartid) && is_numeric($objValue)){
					$sSQL="UPDATE cart SET cartGiftWrap=" . $objValue . ",cartGiftMessage='" . escape_string(strip_tags(@$_POST['gwmessage' . $thecartid])) . "' WHERE cartID=" . $thecartid . " AND " . getsessionsql();
					ect_query($sSQL) or ect_error();
				}
			}
		}
		updategiftwrap();
		print '<div class="giftwrapupdate">';
		print '<meta http-equiv="Refresh" content="2; URL=cart'.$GLOBALS['extension'].'">';
		print '<div class="giftwrapupdating">' . $GLOBALS['xxGifUpd'] . '</div>';
		print '<div class="giftwrappleasewait">' . $GLOBALS['xxPlsWait'] . ' <a class="ectlink" href="cart'.$GLOBALS['extension'].'">' . $GLOBALS['xxClkHere'] . '</a>.</div></div>';
	}else{
		$sSQL='SELECT cartID,cartProdID,cartProdName,cartProdPrice,cartQuantity,pStaticPage,pDisplay,pGiftWrap,cartGiftWrap,cartGiftMessage FROM cart LEFT JOIN products ON cart.cartProdID=products.pID WHERE pGiftWrap<>0 AND cartCompleted=0 AND ' . getsessionsql() . ' ORDER BY cartID';
		$result=ect_query($sSQL) or ect_error();
		if(ect_num_rows($result)==0){
			print '<class="giftwrapupdate">' . $GLOBALS['xxGifNop'] . '</div>';
		}else{
			while($rs=ect_fetch_assoc($result)){
				print '<div class="giftwrapline">';
					print '<div class="giftwraplineid">' . $rs['cartProdID'] . '</div>';
					print '<div class="giftwraplinename">' . $rs['cartProdName'] . '</div>';
					print '<div class="giftwraplinequant">' . $rs['cartQuantity'] . '</div>';
					print '<div class="giftwraplineyes"><select size="1" name="gwset' . $rs['cartID'] . '" onchange="document.getElementById(\'gwmessage' . $rs['cartID'] . '\').disabled=this[this.selectedIndex].value!=\'1\';"><option value="0">' . $GLOBALS['xxNo'] . '</option><option value="1"' . ($rs['cartGiftWrap']!=0 ? ' selected="selected"' : '') . '>' . $GLOBALS['xxYes'] . '</option></select></div>';
					print '<div class="giftwrapmessage"><div class="giftwraptmessage">' . $GLOBALS['xxGifMes'] . '</div><div class="giftwraplinemessage"><textarea placeholder="' . placeholder($GLOBALS['xxGwMeYe']) . '" class="gwmessage' . $rs['cartID'] . '" name="gwmessage' . $rs['cartID'] . '" id="gwmessage' . $rs['cartID'] . '" rows="3" cols="34"' . ($rs['cartGiftWrap']==0 ? ' disabled="disabled"' : '') . '>' . htmlspecials($rs['cartGiftMessage']) . '</textarea></div></div>';
				print '</div>';
			}
			print '<div class="giftwrapbuttons"><input type="submit" value="Update Selections" class="ectbutton giftwrapsubmit" /> <input type="button" class="ectbutton giftwrapcancel" value="' . $GLOBALS['xxCancel'] . '" onclick="document.location=\'cart'.$GLOBALS['extension'].'\'" /></div>';
		}
		ect_free_result($result);
	}
	print '</div></form>';
}elseif((substr(getget('token'),0,2)!='EC' || $checkoutmode=='paypalcancel') && ($checkoutmode=='dologin' || $checkoutmode=='donewaccount' || $checkoutmode=='update' || $checkoutmode=='paypalcancel' || $checkoutmode=='savecart' || $checkoutmode=='movetocart' || $checkoutmode=='acceptstock' || $checkoutmode=='') && $cartisincluded!=TRUE){
	getadminshippingparams();
	if(getsessionid()=='') print 'The PHP session has not been started. This can cause problems with the shopping cart function. For help please go to <a class="ectlink" href="https://www.ecommercetemplates.com/support/">https://www.ecommercetemplates.com/support/</a>';
	if(@$_SESSION['AmazonLoginTimeout']!=''&&time()>=$_SESSION['AmazonLoginTimeout']){
		$_SESSION['AmazonLogin']='';
		$_SESSION['AmazonLoginTimeout']='';
	}
	$amazonpaycheckout=@$_SESSION['AmazonLogin']!=''&&@$_SESSION['AmazonLoginTimeout']!=''&&getget('amazonpay')=='go';
	$cartpath=$storeurlssl.'cart'.$GLOBALS['extension'];
	$loginerror='';
	if(getget('mode')=='logout'){
		$_SESSION['clientID']=NULL; unset($_SESSION['clientID']);
		$_SESSION['clientUser']=NULL; unset($_SESSION['clientUser']);
		$_SESSION['clientActions']=NULL; unset($_SESSION['clientActions']);
		$_SESSION['clientLoginLevel']=NULL; unset($_SESSION['clientLoginLevel']);
		$_SESSION['clientPercentDiscount']=NULL; unset($_SESSION['clientPercentDiscount']);
		$GLOBALS['xxSryEmp']=$GLOBALS['xxLOSuc'];
		setacookie('WRITECLL','',-7);
		setacookie('WRITECLP','',-7);
		if(@$storeurlssl!=$storeurl) print '<script src="'.$storeurlssl.'vsadmin/savecookie.php?DELCLL=Y"></script>';
	}
	$addextrarows=0;
	if($shipType==0) $estimateshipping=FALSE;
	$wantstateselector=(FALSE||@$forcestateselector||@$GLOBALS['defaultshipstate']!='')&&@$estimateshipping;
	$wantcountryselector=FALSE;
	$wantzipselector=FALSE;
	$shipcountry=$origCountry;
	if(@$estimateshipping==TRUE){
		if(@$GLOBALS['commercialloc']===2) $commercialloc_=TRUE;
		if($cartisincluded!=TRUE){
			if(@$_SESSION['clientID']!='' && getpost('country')=='' && @$_SESSION['country']=='' && $shipType>=1){
				$sSQL="SELECT addState,addCountry,addZip FROM address INNER JOIN countries ON address.addCountry=countries.countryName WHERE addCustID='".escape_string($_SESSION['clientID'])."' ORDER BY addIsDefault DESC";
				$result=ect_query($sSQL) or ect_error();
				if($rs=ect_fetch_assoc($result)){
					$_SESSION['country']=$rs['addCountry']; $_SESSION['state']=$rs['addState']; $_SESSION['zip']=$rs['addZip'];
				}
				ect_free_result($result);
			}
			if(getpost('state')!=''){
				$shipstateid=(int)getpost('state');
				$_SESSION['state']=getpost('state');
			}elseif(@$_SESSION['state']!='')
				$shipstateid=$_SESSION['state'];
			else
				$shipstate=@$GLOBALS['defaultshipstate'];
			if(getpost('country')!=''){
				$shipcountry=getcountryfromid(getpost('country'));
				$_SESSION['country']=$shipcountry;
			}elseif(@$_SESSION['country']!='')
				$shipcountry=$_SESSION['country'];
			else{
				$shipCountryCode=$origCountryCode;
				$shipcountry=$origCountry;
			}
		}
		$sSQL="SELECT countryID,countryTax,countryCode,countryFreeShip FROM countries WHERE countryName='" . escape_string($shipcountry) . "'";
		for($index=1;$index<=2;$index++){
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				if(trim_(@$_SESSION['clientID'])!='' && ((int)$_SESSION['clientActions'] & 2)==2) $countryTaxRate=0; else $countryTaxRate=$rs['countryTax'];
				$shipCountryID=$rs['countryID'];
				$shipCountryCode=$rs['countryCode'];
				$freeshipavailtodestination=($rs['countryFreeShip']==1);
				$shiphomecountry=($rs['countryID']==$origCountryID) || (($rs['countryID']==1 || $rs['countryID']==2) && @$GLOBALS['usandcasplitzones']);
				break;
			}
			$sSQL='SELECT countryID,countryTax,countryCode,countryFreeShip FROM admin INNER JOIN countries ON admin.adminCountry=countries.countryID WHERE adminID=1';
		}
		ect_free_result($result);
		$sSQL='SELECT shipInsurance'.($shiphomecountry?'Dom':'Int').',insurance'.($shiphomecountry?'Dom':'Int').'Min,insurance'.($shiphomecountry?'Dom':'Int').'Percent,noCarrier'.($shiphomecountry?'Dom':'Int').'Ins FROM admin WHERE adminID=1';
		$result=ect_query($sSQL) or ect_error();
		$rs=ect_fetch_assoc($result);
		$addshippinginsurance=$rs['shipInsurance'.($shiphomecountry?'Dom':'Int')];
		$shipinsurancemin=$rs['insurance'.($shiphomecountry?'Dom':'Int').'Min'];
		$shipinsurancepercent=$rs['insurance'.($shiphomecountry?'Dom':'Int').'Percent'];
		if($addshippinginsurance==3){ $forceinsuranceselection=TRUE; $addshippinginsurance=2; }
		$nocarrierinsurancerates=$rs['noCarrier'.($shiphomecountry?'Dom':'Int').'Ins']!=0;
		ect_free_result($result);
		if($cartisincluded!=TRUE){
			if(getpost('zip')!=''){
				$destZip=getpost('zip');
				$_SESSION['zip']=getpost('zip');
			}elseif(@$_SESSION['zip']!='')
				$destZip=$_SESSION['zip'];
			elseif(@$nodefaultzip!=TRUE && $origCountryCode==$shipCountryCode)
				$destZip=$origZip;
			else
				$destZip='';
		}
		if($shipCountryID==1 || $shipCountryID==2) $shipStateAbbrev=getstateabbrev(is_numeric($shipstateid) ? $shipstateid : $shipstate);
		if($shiphomecountry){
			$sSQL='SELECT stateTax,stateAbbrev,stateFreeShip,stateName FROM states WHERE stateCountryID=' . $shipCountryID . ' AND ' . (is_numeric($shipstateid) ? "stateID='" . escape_string($shipstateid) . "'" : "(stateAbbrev='" . escape_string($shipstate) . "' OR stateName='" . escape_string($shipstate) . "')");
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				if($shipCountryID==$origCountryID || (($shipCountryID==1||$shipCountryID==2) && @$GLOBALS['usandcasplitzones'])) $stateTaxRate=$rs['stateTax']; else $stateTaxRate=0;
				$freeshipavailtodestination=($freeshipavailtodestination && ($rs['stateFreeShip']==1));
				$shipstate=$rs['stateName'];
			}
			ect_free_result($result);
		}else
			$shipstate='';
		$ordState=$shipstate;
		$shipType=getshiptype();
		$addextrarows=1;
		if($shipType==2 || $shipType==5){ // weight / price based
			$wantcountryselector=TRUE;
			if($splitUSZones)$wantstateselector=TRUE;
		}elseif($shipType==3 || $shipType==4 || $shipType>=6){
			$wantzipselector=TRUE;
			$wantcountryselector=TRUE;
		}
		if(($shipType==4 || $shipType==11) && @$upsnegdrates==TRUE) $wantstateselector=TRUE;
		if(! @$nodiscounts && ! $wantstateselector){
			$sSQL="SELECT cpnID FROM coupons WHERE cpnCntry=1 AND cpnType=0 AND cpnNumAvail>0 AND cpnStartDate<='" . date('Y-m-d', time()+($GLOBALS['dateadjust']*60*60)) ."' AND cpnEndDate>='" . date('Y-m-d', time()+($GLOBALS['dateadjust']*60*60)) ."' AND ((cpnLoginLevel>=0 AND cpnLoginLevel<=".$minloglevel.') OR (cpnLoginLevel<0 AND -1-cpnLoginLevel='.$minloglevel.'))';
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)) $statelimiteddiscount=TRUE; else $statelimiteddiscount=FALSE;
			ect_free_result($result);
			if($statelimiteddiscount){
				$sSQL='SELECT stateID FROM states WHERE stateFreeShip=0 AND stateEnabled<>0 AND stateCountryID=' . $origCountryID;
				$result=ect_query($sSQL) or ect_error();
				if(ect_num_rows($result)>0) $wantstateselector=TRUE;
				ect_free_result($result);
			}
		}
		if(($adminAltRates==1 || $adminAltRates==2) && (! $wantzipselector || ! $wantcountryselector)){
			$sSQL='SELECT altrateid FROM alternaterates WHERE (usealtmethod<>0 OR usealtmethodintl<>0) AND altrateid IN (3,4,6,7,8,9)';
			$result=ect_query($sSQL) or ect_error();
			if(ect_num_rows($result)>0){ $wantzipselector=TRUE; $wantcountryselector=TRUE; }
			ect_free_result($result);
		}
		if(($adminAltRates==1 || $adminAltRates==2) && ! $wantstateselector && $splitUSZones){
			$sSQL='SELECT altrateid FROM alternaterates WHERE (usealtmethod<>0 OR usealtmethodintl<>0) AND altrateid IN (2,5)';
			$result=ect_query($sSQL) or ect_error();
			if(ect_num_rows($result)>0) $wantstateselector=TRUE;
			ect_free_result($result);
		}
		if(($adminAltRates==1 || $adminAltRates==2) && ! $wantcountryselector){
			$sSQL='SELECT altrateid FROM alternaterates WHERE (usealtmethod<>0 OR usealtmethodintl<>0) AND altrateid>=2';
			$result=ect_query($sSQL) or ect_error();
			if(ect_num_rows($result)>0) $wantcountryselector=TRUE;
			ect_free_result($result);
		}
		$stateSQL='';
		if($wantstateselector){
			$stateSQL='SELECT stateID,stateAbbrev,stateName,stateName2,stateName3,stateCountryID,countryName FROM states INNER JOIN countries ON states.stateCountryID=countries.countryID WHERE countryEnabled<>0 AND stateEnabled<>0 AND (stateCountryID=' . $origCountryID . ((($shipType==4 || $shipType==11) && $upsnegdrates==TRUE) || $origCountryID==1 || $origCountryID==2 ? ' OR stateCountryID=1 OR stateCountryID=2' : '') . ') ORDER BY stateCountryID,' . getlangid('stateName',1048576);
 			$result=ect_query($stateSQL) or ect_error();
			if(ect_num_rows($result)==0){ $wantstateselector=FALSE; $splitUSZones=FALSE; }
			ect_free_result($result);
		}
		if($wantstateselector){$wantcountryselector=TRUE;$addextrarows++;}else{$shipstate='';$shipStateAbbrev='';}
		if($wantcountryselector)$addextrarows++;
		if(zipisoptional($shipCountryID))$wantzipselector=FALSE;
		if($wantzipselector)$addextrarows++;
	}else{
		$_SESSION['xsshipping']=NULL; unset($_SESSION['xsshipping']);
	}
	initshippingmethods();
	$loyaltypointsavailable=0;
	$redeempoints=TRUE;
	$_SESSION['noredeempoints']='';
	if(@$GLOBALS['loyaltypoints']!='' && @$_SESSION['clientID']!=''){
		if(getget('redeempoints')=='no'){
			$_SESSION['noredeempoints']=TRUE;
			$redeempoints=FALSE;
		}
		$sSQL='SELECT loyaltyPoints FROM customerlogin WHERE clID=' . $_SESSION['clientID'];
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			$loyaltypointsavailable=$rs['loyaltyPoints']; $addextrarows++;
		}
		ect_free_result($result);
	}
	$stockalreadysubtracted=FALSE;
	$sSQL="SELECT ordID FROM orders WHERE ordStatus>1 AND ordAuthNumber='' AND ordAuthStatus<>'MODWARNOPEN' AND " . getordersessionsql();
	$result=ect_query($sSQL) or ect_error();
	if(ect_num_rows($result)>0) $stockalreadysubtracted=TRUE;
	ect_free_result($result);
	if(@$GLOBALS['showtaxinclusive']!=0) $addextrarows++;
	if($stockalreadysubtracted) $stockwarning=FALSE; else do_stock_check(TRUE,$backorder,$stockwarning);
	$alldata=$theqs='';
	if(getget('pla')!='') $GLOBALS['hideoptpricediffs']=TRUE;
	foreach(@$_GET as $key=>$val)
		if($key=='pli'||$key=='pla') $theqs.='&'.urlencode(strip_tags($key)) . '=' . urlencode(strip_tags($val));
?><script><?php print $GLOBALS['wpjavascriptcomments']?>/* <![CDATA[ */
var ectinwhichlist='';
var currqs='<?php print jsescape($theqs)?>';
function checkchecked(){
	ischecked=false
	var inputs=document.getElementsByTagName('input');
	for(var i=0; i < inputs.length; i++)
		if(inputs[i].type=='checkbox'){
			if(inputs[i].checked&&inputs[i].name.substr(0,5)=='delet') ischecked=true;
		}
	if(! ischecked) alert("<?php print jscheck($GLOBALS['xxNotSel'])?>");
	return(ischecked);
}
function dodelete(cid,inlist){
ectinwhichlist=inlist;
var ECinput=document.createElement("input");
ECinput.setAttribute("type", "hidden");
ECinput.setAttribute("name", "delet"+cid);
ECinput.setAttribute("value", "ON");
document.forms.checkoutform.appendChild(ECinput);
return doupdate(document.forms.checkoutform);
}
function setestimatorwarn(tobjt,showalert,tmsg){
	var tobj=document.getElementById(tobjt);
	if(tobj)ectaddclass(tobj,'ectwarning');
	if(showalert)alert(tmsg);
	return false;
}
function revealestimatorgo(){
if(document.getElementById('state')&&(document.getElementById('state').disabled||document.getElementById('state').selectedIndex!=0))ectremoveclass(document.getElementById('state'),'ectwarning');
if(document.getElementById('zip'))ectremoveclass(document.getElementById('zip'),'ectwarning');
if(document.getElementById('country'))ectremoveclass(document.getElementById('country'),'ectwarning');
document.getElementById('updateestimator').style.display='';
}
function updateestimator(inlist,showalert){
ectinwhichlist=inlist;
<?php	if($wantzipselector){ ?>
	if(document.getElementById('zip').value=='')
		return(setestimatorwarn('zip',showalert,'<?php print jscheck($GLOBALS['xxPlsZip'])?>'));
<?php	}
		if($wantstateselector){ ?>
	if(!(document.getElementById('state').disabled||document.getElementById('state').selectedIndex!=0))
		return(setestimatorwarn('state',showalert,'<?php print jscheck($GLOBALS['xxPlsSel'])?>\n'+document.getElementById('statetxt').innerHTML));
		<?php	} ?>
	return doupdate(document.forms.checkoutform);
}
function doupdate(tform){
	tform.mode.value='update';
	tform.action='cart<?php print $GLOBALS['extension']?>'+(currqs+(ectinwhichlist!=''?'&lid='+ectinwhichlist+'#oc':'')).replace('&','?');
	tform.onsubmit='';
	tform.submit();
	return false;
}
function dosaveitem(lid){
	var ECinput=document.createElement("input");
	ECinput.setAttribute("type", "hidden");
	ECinput.setAttribute("name", "delet"+whichcartid);
	ECinput.setAttribute("value", "ON");
	document.forms.checkoutform.appendChild(ECinput);
	document.forms.checkoutform.mode.value=lid=='x'?'movetocart':'savecart';
	document.forms.checkoutform.listid.value=lid;
	document.forms.checkoutform.action='cart<?php print $GLOBALS['extension']?>'+(currqs+(ectinwhichlist!=''?'&lid='+ectinwhichlist+'#oc':'')).replace('&','?');
	document.forms.checkoutform.onsubmit='';
	document.forms.checkoutform.submit();
	return(false);
}
var cartoversldiv,whichcartid;
function cartdispsavelist(clid,inlist,el){
	ectinwhichlist=inlist;
	whichcartid=clid;
	cartoversldiv=false;
	var sld=document.getElementById('savecartlist');
	var parentdiv=el.parentNode;
	parentdiv.insertBefore(sld,parentdiv.firstChild);
	for(var sldindex=0;sldindex<sld.childNodes.length;sldindex++){
		if(sld.childNodes[sldindex].id=='savecartlist'+inlist)
			sld.childNodes[sldindex].style.display='none';
		else if(sld.childNodes[sldindex].style)
			sld.childNodes[sldindex].style.display='';
	}
	sld.style.visibility="visible";
	setTimeout('cartchecksldiv()',2000);
	return(false);
}
function cartchecksldiv(){
	var sld=document.getElementById('savecartlist');
	if(! cartoversldiv)
		sld.style.visibility='hidden';
}
function selaltrate(id){
	document.forms.checkoutform.altrates.value=id;
	doupdate(document.forms.checkoutform);
}
<?php		if(@$_SESSION['clientID']!='' && (@$_SESSION['clientActions']&64)==64){
				$cartidlist='';
				$sSQL='SELECT cartID FROM cart WHERE cartCompleted=0 AND '.getsessionsql();
				$result=ect_query($sSQL) or ect_error();
				while($rs=ect_fetch_assoc($result)){
					$cartidlist.=$rs['cartID'].',';
				}
				ect_free_result($result);
				if($cartidlist!=''){
					$cartidlist=commaseplist($cartidlist); ?>
function dosharecart(){
	document.getElementById('sharecartinput').value='<?php
		$securitykey=base64_encode(hash_hmac('sha256', $_SESSION['clientID'] . 'this is a saved cart' . $cartidlist, $GLOBALS['adminSecret'], true));
		print $storeurl.'cart' . $GLOBALS['extension'] . '?sharecart=' . $_SESSION['clientID'] . '&key=' . urlencode($securitykey) . '&list=' . $cartidlist;
	?>';
	document.getElementById('sharecartbutton').style.display='none';
	document.getElementById('sharecartinput').style.display='';
	document.getElementById('sharecartinput').select();
	document.execCommand('copy');
}
<?php			}
			}
	if(($adminAltRates==2 && @$_SESSION['xsshipping']!='')||!@$estimateshipping) $adminAltRates=0;
	if($adminAltRates==2){
		$sSQL='SELECT altrateid,'.getlangid('altratetext',65536).' FROM alternaterates WHERE usealtmethod'.$international.'<>0 ORDER BY altrateorder'.$international.',altrateid';
		$result2=ect_query($sSQL) or ect_error();
		if(ect_num_rows($result2)>0){
			print "var shipservicetext=[];\r\n";
			print 'var extraship=[';
			$addcomma='';
			$servicetext='';
			while($rs=ect_fetch_assoc($result2)){
				$servicetext.='shipservicetext[' . $rs['altrateid'] . ']="' . $rs[getlangid('altratetext',65536)] . '";' . "\r\n";
				if($rs['altrateid']!=$shipType){
					print $addcomma . $rs['altrateid'];
					$addcomma=',';
				}
			}
			print "];\r\n";
			print $servicetext . "\r\n"; ?>
function addCommas(ns,decs,thos){
if((dpos=ns.indexOf(decs))<0)dpos=ns.length;
dpos-=3;
while(dpos>0){
	ns=ns.substr(0,dpos)+thos+ns.substr(dpos);
	dpos-=3;
}
return(ns);
}
function formatestprice(i){
<?php
	$tempStr=FormatEuroCurrency(0);
	print "var pTemplate='".$tempStr."';\r\n";
	if(strstr($tempStr,',') || strstr($tempStr,'.')){ ?>
if(i==Math.round(i))i=i.toString()+".00";
else if(i*10.0==Math.round(i*10.0))i=i.toString()+"0";
else if(i*100.0==Math.round(i*100.0))i=i.toString();
<?php
	}
	print 'i=addCommas(i.toString()'.(strstr($tempStr,',')?".replace(/\\./,','),',','.'":",'.',','").');';
	print 'pTemplate=pTemplate.toString().replace(/\d[,.]*\d*/,i.toString());';
	print 'return(pTemplate);';
?>}
function acajaxcallback(){
	if(ajaxobj.readyState==4){
		var restxt=ajaxobj.responseText;
		var gssr=restxt.split('SHIPSELPARAM=');
		if(gssr[2]!='ERROR'&&parseFloat(gssr[1])<bestestimate){
			if(document.getElementById('estimatorcell')){
				document.getElementById('estimatorcell').colSpan='1';
				document.getElementById('estimatorcell').align='right';
				var newcell=document.getElementById('estimatorrow').insertCell(-1);
				newcell.className='cobll';
				newcell.innerHTML='&nbsp;';
				document.getElementById('estimatorcell').id='';
			}
			bestestimate=parseFloat(gssr[1]);
			bestcarrier=parseInt(gssr[4]);
			document.getElementById('estimatorspan').innerHTML=formatestprice(bestestimate);
			if(document.getElementById('shippingtotal_cntnr'))document.getElementById('shippingtotal_cntnr').style.display='';
			var discounts=0;
			if(document.getElementById('discountspan')){
				discounts=document.getElementById('discountspan').innerHTML.replace(/[^0-9\.\,]+/g,'');
				var testlatin=/\,\d\d$/;
				if(testlatin.test(discounts))
					discounts=parseFloat(discounts.replace(/\./g,'').replace(/,/g,'.'));
				else
					discounts=parseFloat(discounts.replace(/,/g,''));
			}
<?php	if(@$GLOBALS['showtaxinclusive']!=0) print "var countrytax=parseFloat(gssr[3]);document.getElementById('countrytaxspan').innerHTML=formatestprice(countrytax);\r\n"; else print "var countrytax=0;\r\n"; ?>
			document.getElementById('grandtotalspan').innerHTML=(formatestprice(Math.round((vstotalgoods+bestestimate+countrytax-discounts)*100)/100.0));
				}else if(gssr[2]=='ERROR'&&document.getElementById('estimatorerrors')){
			if(document.getElementById('estimatorerrors').innerHTML.indexOf(gssr[0])==-1){
				if(gssr[0]=='<?php print jsescape($GLOBALS['xxInvZip'])?>'||gssr[0]=='<?php print jsescape($GLOBALS['xxPlsZip'])?>'||gssr[0].indexOf('The postal code')>=0){
					var x=document.getElementsByClassName("cartzipselectortext");
					for(var aci=0;aci<x.length;aci++) if(x[aci].className.indexOf('ectwarning')==-1)x[aci].className+=' ectwarning';
					var x=document.getElementsByClassName("cartzipselector");
					for(var aci=0;aci<x.length;aci++) if(x[aci].className.indexOf('ectwarning')==-1)x[aci].className+=' ectwarning';

				}
				if(gssr[0]=='<?php print jsescape($GLOBALS['xxPlsSta'])?>'){
					var x=document.getElementsByClassName("cartstateselectortext");
					for(var aci=0;aci<x.length;aci++) if(x[aci].className.indexOf('ectwarning')==-1)x[aci].className+=' ectwarning';
					var x=document.getElementsByClassName("cartstateselector");
					for(var aci=0;aci<x.length;aci++) if(x[aci].className.indexOf('ectwarning')==-1)x[aci].className+=' ectwarning';

				}
				document.getElementById('estimatorerrors').innerHTML+='<div class="estimatorerror ectwarning">'+gssr[0]+'</div>';
				document.getElementById('estimatorerrors').className='estimatorerrors';
			}
		}
		getalternatecarriers();
	}
}
function getalternatecarriers(){
	if(extraship.length>0){
		var shiptype=extraship.shift();
		if(document.getElementById('estimatorchecktext')){
			document.getElementById('estimatorchecktext').innerHTML='Checking carrier';
			document.getElementById('estimatorcheckcarrier').innerHTML=shipservicetext[shiptype];
		}else
			document.getElementById('checkaltspan').innerHTML='Checking ' + shipservicetext[shiptype] + ":";
		ajaxobj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
		ajaxobj.onreadystatechange=acajaxcallback;
		ajaxobj.open("GET", "vsadmin/shipservice.php?ratetype=estimator&best="+bestestimate+"&shiptype="+shiptype+"&sessionid=<?php print urlencode($thesessionid)?>&destzip=<?php print urlencode($destZip)?>&sc=<?php print urlencode($shipCountryID)?>&sta=<?php print urlencode($shipstateid)?>", true);
		ajaxobj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		ajaxobj.send(null);
	}else{
		if(document.getElementById('estimatorchecktext')){
			document.getElementById('estimatorchecktext').innerHTML="<?php print $GLOBALS['xxBesRaU']?>";
			document.getElementById('estimatorcheckcarrier').innerHTML=shipservicetext[bestcarrier];
		}else
			document.getElementById('checkaltspan').innerHTML="<?php print $GLOBALS['xxBesRaU']?> " + shipservicetext[bestcarrier] + ":";
		document.forms.checkoutform.altrates.value=bestcarrier;
	}
}
<?php	}
		ect_free_result($result2);
	} ?>
function applycertcallback(){
	if(ajaxobj.readyState==4){
		var retvals=ajaxobj.responseText.split('&');
		alert(retvals[1].replace(/<\/?[^>]+(>|$)/g, ""));
		if(retvals[0]=='success'){document.getElementById("cpncode").value='';document.location.reload();}
	}
}
function applycert(){
	var cpncode=document.getElementById("cpncode").value;
	if(cpncode!=""){
		ajaxobj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
		ajaxobj.onreadystatechange=applycertcallback;
		ajaxobj.open("GET", "vsadmin/ajaxservice.php?action=applycert&stg1=1&cpncode="+cpncode, true);
		ajaxobj.send(null);
	}
}
function removecert(cpncode){
	if(cpncode!=''){
		ajaxobj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
		ajaxobj.onreadystatechange=applycertcallback;
		ajaxobj.open("GET", "vsadmin/ajaxservice.php?action=applycert&stg1=1&act=delete&cpncode="+cpncode, true);
		ajaxobj.send(null);
	}
}
function actionupdate(cid,tform,listid){
ectinwhichlist=listid;
document.getElementById('quant'+cid).name=document.getElementById('quant'+cid).id;
doupdate(tform);
}
function acceptstock(){
	document.forms.checkoutform.mode.value='acceptstock';
	document.forms.checkoutform.submit();
}
function showupdatebutton(cid,cartlineunique,listid){
document.getElementById('cartlinetot'+cartlineunique).innerHTML='<input type="button" class="ectbutton cartlineupdate" value="<?php print jscheck($GLOBALS['xxUpdate'])?>" onclick="actionupdate('+cid+',this.form,\''+listid+'\')" />';
}
/* ]]> */<?php print $GLOBALS['wpjavascriptendcomments']?></script>
<?php
	$cartliststring='';
	if(@$_SESSION['clientID']!='' && @$GLOBALS['enablewishlists']){ // Wish List Popup
		$cartliststring.='0,';
		$sSQL="SELECT listID,listName FROM customerlists WHERE listOwner='".escape_string($_SESSION['clientID'])."'";
		$result=ect_query($sSQL) or ect_error();
		$cartlistnumber=1;
		print '<div id="savecartlist" class="savecartlist" onmouseover="cartoversldiv=true;" onmouseout="cartoversldiv=false;setTimeout(\'cartchecksldiv()\',1000)">';
			print '<div id="savecartlist' . (ect_num_rows($result)+1) . '" onclick="dosaveitem(\'x\')">' . $GLOBALS['xxShoCar'] . "</div>\n";
			print '<div class="savecartdivider">-</div>' . "\n";
			print '<div id="savecartlist0" onclick="dosaveitem(\'0\')">' . $GLOBALS['xxMyWisL'] . "</div>\n";
			while($rs=ect_fetch_assoc($result)){
				$cartliststring.=$rs['listID'].',';
				print '<div id="savecartlist' . $cartlistnumber++ . '" onclick="dosaveitem(' . $rs['listID'] . ')">' . htmlspecials($rs['listName']) . "</div>\n";
			}
			ect_free_result($result);
		print '</div>';
	}
	if(($GLOBALS['adminPayLater'] & 48)!=0){
		if(getpayprovdetx(27,$data1,$data2,$data3,$data4,$data5,$data6,$ppflag1,$ppflag2,$ppflag3,$ppbits,$demomode,$ppmethod)){
			if($ppflag1==0)
				print '<script src="https://www.paypal.com/sdk/js?client-id=' . $data1 . '&currency=' . $GLOBALS['countryCurrency'] . '&components=messages" data-partner-attribution-id="EcommerceTemplates_Ecom_PPCP"></script>'."\n";
			if(($GLOBALS['adminPayLater'] & 32)==32){
				print '<div data-pp-message data-pp-placement="cart" data-pp-amount="" data-pp-style-layout="flex" data-pp-style-ratio="20x1" class="paylaterbanner cartpaylaterbanner"></div>';
			}
		}
	}
	if(@$GLOBALS['xxCoStp1']!=''){
		$sSQL='SELECT cartID FROM cart WHERE cartCompleted=0 AND '.getsessionsql();
		$result=ect_query($sSQL) or ect_error();
		if(ect_num_rows($result)>0)
			print '<div class="checkoutsteps">' . $GLOBALS['xxCoStp1'] . '</div>';
	}
	print '<div class="cart1details cartlists">'; // {
	if(@$GLOBALS['enableclientlogin'] && !@$GLOBALS['noclientloginprompt'] && !$amazonpaycheckout){
		print '<div class="cartlistdiv cartlisthead"><div class="ectdivhead cartlistname cartlistlogin">';
		if(@$_SESSION['clientID']!=''){
			print '<div class="cartloggedin">';
			print imageorbuttontag(@$GLOBALS['imgcartlogout'],$GLOBALS['xxLogout'] . ' ' . htmlspecials($_SESSION['clientUser']),'ectlink','return dologoutaccount()',TRUE);
			if(@$GLOBALS['enablewishlists']) print ' <button type="button" class="ectbutton" onclick="document.location=\''.$customeraccounturl.'#list\';return false">'.$GLOBALS['xxCreaGR'].'</button>';
			if(getget('warncheckspamfolder')=='true') print '<div class="thanksubscribe">' . $GLOBALS['xxThkSub'] . '</div><div class="spamwarn">' . $GLOBALS['xxSpmWrn'] . '</div>';
			if(getget('cartchanged')=='true') print '<div class="cartchanged">'.$GLOBALS['xxCarCha'].'</div>';
			print '</div>';
		}else{
			print '<div class="loginprompt">' . imageorbuttontag(@$imgloginaccount,$GLOBALS['xxLogAcc'],'logintoaccount',"displayloginaccount()",TRUE);
			if(@$GLOBALS['allowclientregistration']) print imageorbuttontag(@$imgcreateaccount,$GLOBALS['xxCreAcc'],'createaccount',"displaynewaccount()",TRUE);
			print '</div>';
		}
		print '</div></div>';
	}
	$haspubliclist=FALSE;
	if(is_numeric(getget('pli')) && getget('pla')!='' && strpos(','.$cartliststring.',',','.getget('pli').',')===FALSE){
		$sSQL="SELECT listID,listName FROM customerlists WHERE listID='".escape_string(getget('pli'))."' AND listAccess='".escape_string(getget('pla'))."'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			$haspubliclist=TRUE;
			$cartliststring.=getget('pli').',';
		}else
			print '<div class="ectwarning">That public list was not found or has been deleted.</div>';
		ect_free_result($result);
	}
	if($GLOBALS['onvacation']!=0){
		$cartliststring="";
		$vacationmessage="";
		print '<div class="ectwarning vacationmessage" style="text-align:center;font-size:1.3em;padding:16px">';
		$result=ect_query('SELECT vacationmessage FROM admin WHERE adminID=1') or ect_error();
		if($rs=ect_fetch_assoc($result)) $vacationmessage=$rs['vacationmessage']; else $vacationmessage='The store is currently offline.';
		print $vacationmessage;
		print '</div>';
		if(@$GLOBALS['enableclientlogin']) displaysoftlogin();
	}
	$opencartid=@$GLOBALS['noopencartid']?'':' id="oc"';
	$cartlineunique=0;
	$cartliststringarray=$GLOBALS['onvacation']!=0?array():explode(',',$cartliststring.' ');
	$saveshowtaxinclusive=$GLOBALS['showtaxinclusive'];
	$saveestimateshipping=$estimateshipping;
	$savestateTaxRate=$stateTaxRate;
	$savecountryTaxRate=$countryTaxRate;
	$savehandling=$GLOBALS['handling'];
	foreach($cartliststringarray as $cartlistnumber=>$listid){
		$checkpriceschanged=[];
		$GLOBALS['priceschangedwarning']='';
		$listid=trim($listid);
		$shipfreegoods=$totalgoods=$totalquantity=$shipping=$stateTax=$countryTax=$totaldiscounts=$freeshipamnt=$loyaltypointdiscount=0;
		$handling=$savehandling;
		$ispubliclist=FALSE;
		$cartlistclass='cartlistgift';
		if($listid==='0') $cartlistclass='cartlistwish'; elseif($listid==='') $cartlistclass='cartlistshop';
		print '<div class="cartlistdiv ' . $cartlistclass . '">'; // {
		if(is_numeric(getget('lid'))) $displaylistid=getget('lid'); else $displaylistid='';
		if(is_numeric(getget('pli')) && getget('pla')!='') $displaylistid=getget('pli');
		$checkoutsteptxt='&nbsp;';
		$numitems=0;
		if(is_numeric(getget('pli')) && (string)$listid==getget('pli') && $haspubliclist){
			$checkoutmode='savedcart';
			$GLOBALS['showtaxinclusive']=0;
			$estimateshipping=FALSE;
			$sSQL="SELECT listID,listName FROM customerlists WHERE listID='".escape_string(getget('pli'))."' AND listAccess='".escape_string(getget('pla'))."'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				$listname=$rs['listName'];
				$querystr='cartCompleted=3 AND cartListID='.$listid;
				$ispubliclist=TRUE;
			}
			ect_free_result($result);
		}elseif(@$_SESSION['clientID']!='' && $listid!='0' && $listid!=''){
			$checkoutmode='savedcart';
			$GLOBALS['showtaxinclusive']=0;
			$estimateshipping=FALSE;
			$sSQL="SELECT listID,listName FROM customerlists WHERE listID='".escape_string($listid)."' AND listOwner='".escape_string($_SESSION['clientID'])."'";
			$result=ect_query($sSQL) or ect_error();
			if(! ($rs=ect_fetch_assoc($result))) $querystr='cartCompleted=0 AND '.getsessionsql(); else{ $listname=$rs['listName']; $querystr='cartCompleted>=0 AND cartListID='.$listid; }
			ect_free_result($result);
		}elseif($listid==='0'){
			$listname=$GLOBALS['xxMyWisL'];
			$checkoutmode='savedcart';
			$GLOBALS['showtaxinclusive']=0;
			$estimateshipping=FALSE;
			$querystr='cartCompleted=3 AND cartListID=0 AND '.getsessionsql();
		}else{
			$listname=$GLOBALS['xxShoCar'];
			$checkoutmode='';
			$GLOBALS['showtaxinclusive']=$saveshowtaxinclusive;
			$estimateshipping=$saveestimateshipping;
			$stateTaxRate=$savestateTaxRate;
			$countryTaxRate=$savecountryTaxRate;
			$querystr='cartCompleted=0 AND '.getsessionsql();
			$checkoutsteptxt='1';
			// Check price changes
			$sSQL='SELECT cartID,cartProdID,cartOrigProdID,cartProdPrice,'.$WSP.'pPrice FROM cart LEFT JOIN products ON cart.cartProdID=products.pID WHERE ' . $querystr;
			$result=ect_query($sSQL) or ect_error();
			while($rsCart=ect_fetch_assoc($result)){
				if($rsCart['cartProdID']!=$donationid && $rsCart['cartProdID']!=$giftcertificateid){
					$checkpriceschanged[$rsCart['cartID']]=$rsCart['cartProdPrice'];
					if(! is_null($rsCart['pPrice'])) checkpricebreaks($rsCart['cartProdID'],$rsCart['pPrice'],TRUE,trim_($rsCart['cartOrigProdID']));
				}
			}
		}
		$sSQL='SELECT COUNT(*) AS numitems FROM cart LEFT JOIN products ON cart.cartProdID=products.pID WHERE ' . $querystr;
		$result2=ect_query($sSQL) or ect_error();
		if($rs2=ect_fetch_assoc($result2))
			if(! is_null($rs2['numitems'])) $numitems=$rs2['numitems']; else $numitems=0;
		ect_free_result($result2);
		if($numitems<=0) $checkoutsteptxt='&nbsp;';		
		print '<div class="ectdivhead cartlistname'.($listid!==''?' cartlistgiftreg':'').($listid===''?' cartlistcart':'').'"'.((string)$cartlistnumber==getget('lid')||(string)$listid==getpost('listid')?$opencartid:'').' style="cursor:pointer" onclick="document.getElementById(\'cartlistid'.$cartlistnumber."').style.display==''?document.getElementById('cartlistimgid".$cartlistnumber."').src='images/arrow-down.png':document.getElementById('cartlistimgid".$cartlistnumber."').src='images/arrow-up.png';document.getElementById('cartlistid".$cartlistnumber."').style.display=(document.getElementById('cartlistid".$cartlistnumber.'\').style.display==\'\'?\'none\':\'\')"><div class="checkoutstep'.($checkoutsteptxt!='&nbsp;'?' checkoutstepof3':'').'">' . $checkoutsteptxt . '</div><div class="cartname">' . htmlspecials($listname) . ' (' . $numitems . ')</div><div class="cartlistimg"><img src="images/arrow-' . (displaycartclosed()?'down':'up') . '.png" id="cartlistimgid'.$cartlistnumber.'" alt="Show / Hide Cart" /></div></div>' . "\r\n";
		if((string)$cartlistnumber==getget('lid')||(string)$listid==getpost('listid')) $opencartid='';
		print '<div class="cartlistcontents" id="cartlistid'.$cartlistnumber.'"' . (displaycartclosed()?' style="display:none"':'') . '>';
		$sSQL="SELECT cartID,cartProdID,cartOrigProdID,cartProdName,cartProdPrice,cartQuantity,pWeight,pShipping,pShipping2,pExemptions,pSection,pDims,pTax,pStaticPage,pDisplay,'' AS pImage,'' AS pLargeImage,cartCompleted,pGiftWrap,cartGiftWrap,".getaltlang('pStaticURL',8388608).",pMinQuant,pID,".getlangid('pDescription',2).','.getlangid('pLongDescription',4).' FROM cart LEFT JOIN products ON cart.cartProdID=products.pID LEFT OUTER JOIN sections ON products.pSection=sections.sectionID WHERE ' . $querystr . ' ORDER BY cartID';
		$result=ect_query($sSQL) or ect_error();
		$GLOBALS['itemsincart']=ect_num_rows($result);
		if(@$GLOBALS['enableclientlogin']) displaysoftlogin();
		print '<form method="post"' . ($checkoutmode==''?' name="checkoutform" onkeydown="return preventreturn(this,event)"':'') . ' action="' . $cartpath . '"' . ($GLOBALS['itemsincart']>0?' onsubmit="return changechecker(this)"':'') . '>';
		print whv('mode','checkout') . whv('sessionid',getsessionid()) . whv('PARTNER',strip_tags(trim_(@$_COOKIE['PARTNER']))) . whv('cart','') . whv('listid','');
		if(@$_SESSION['noredeempoints']==TRUE) writehiddenidvar('noredeempoints', '1');
		if($adminAltRates!=0) print whv('altrates',getpost('altrates'));
		print '<div class="cartcontentsdiv">';
		if(@$carterror!='') print '<div class="carterror ectwarning">' . $carterror . '</div>';
		if($noshowcart){
			// do nothing
		}elseif($GLOBALS['itemsincart']>0){
			$index=0;
			while($rsCart=ect_fetch_assoc($result)){
				$GLOBALS['cartrows'][$index++]=$rsCart;
				if(array_key_exists($rsCart['cartID'],$checkpriceschanged)){
					if($checkpriceschanged[$rsCart['cartID']]!=$rsCart['cartProdPrice']){
						$GLOBALS['pricechangedtext']='The price of the item &quot;%prodname%&quot; has changed from %fromprice% to %toprice%';
						$GLOBALS['priceschangedwarning'].='<div class="ectwarning pricechangedwarning">' . str_replace(array('%prodname%','%fromprice%','%toprice%'),array($rsCart['cartProdName'],FormatEuroCurrency($checkpriceschanged[$rsCart['cartID']]),FormatEuroCurrency($rsCart['cartProdPrice'])),$GLOBALS['pricechangedtext']) . '</div>';
					}
				}
			}
			$totaldiscounts=0;
			$changechecker='';			
			showcartlines(FALSE);
			if(@$GLOBALS['showtaxinclusive']==0){
				$stateTaxRate=0;
				$countryTaxRate=0;
			}
			if($checkoutmode=='savedcart'||@$GLOBALS['nopriceanywhere']){
				$addextrarows=0;
			}else{
				calculatediscounts($totalgoods,FALSE,$rgcpncode);
				if(@$_SESSION['giftcerts']!=''){
					$sSQL="SELECT gcID,gcRemaining FROM giftcertificate WHERE gcRemaining>0 AND gcAuthorized<>0 AND gcID IN ('" . str_replace(' ',"','",escape_string(@$_SESSION['giftcerts'])) . "')";
					$result=ect_query($sSQL) or ect_error();
					while($rs=ect_fetch_assoc($result)) $giftcertsamount+=$rs['gcRemaining'];
					ect_free_result($result);
				}
				if($totaldiscounts>$totalgoods+(@$GLOBALS['showtaxinclusive']==3?$countryTax:0)) $totaldiscounts=$totalgoods+(@$GLOBALS['showtaxinclusive']==3?$countryTax:0);
				if($totaldiscounts==0)
					$_SESSION['discounts']='';
				else{
					$_SESSION['discounts']=$totaldiscounts;
					$addextrarows++;
				}
			}
			$GLOBALS['avalarastate']=0;
			if(@$estimateshipping==TRUE){
				if(@$_SESSION['xsshipping']=='' && $success){
					if(calculateshipping()){
						insuranceandtaxaddedtoshipping();
						calculateshippingdiscounts(FALSE);
						calculatetaxandhandling();
						$_SESSION['xsshipping']=($shipping+$handling)-$freeshipamnt;
					}else{
						$freeshipmethodexists=TRUE;
						calculateshippingdiscounts(FALSE);
						calculatetaxandhandling();
						$handling=$orighandling=0;
					}
				}elseif(@$_SESSION['xsshipping']=='' && ! $success){
					calculatetaxandhandling();
					$handling=$orighandling=0;
				}else{
					$shipping=isset($_SESSION['xsshipping'])?@$_SESSION['xsshipping']:0;
					$stateTax=isset($_SESSION['xsstatetax'])?@$_SESSION['xsstatetax']:0;
					$countryTax=isset($_SESSION['xscountrytax'])?@$_SESSION['xscountrytax']:0;
					$handling=$orighandling=0;
					calculatetaxandhandling();
				}
			}else{
				$freeshipmethodexists=TRUE;
				calculateshippingdiscounts(FALSE);
				$shipping=$handling=$orighandling=$freeshipamnt=0;
				calculatetaxandhandling();
			}
			if(!$amazonpaycheckout&&!@$GLOBALS['nopriceanywhere']){
				print '<div class="cartshippingandtotals">'; // { cartshippingandtotals
				if(@$estimateshipping!=TRUE || @$nohandlinginestimator==TRUE){ $handling=0; $handlingchargepercent=0; }
				print '<div class="cartshippingdetails">';
				if(@$estimateshipping==TRUE){
					if(strpos($errormsg,$GLOBALS['xxInvZip'])!==FALSE || strpos($errormsg,$GLOBALS['xxPlsZip'])!==FALSE) $invalidzip=TRUE; else $invalidzip=FALSE;
					if(strpos($errormsg,$GLOBALS['xxPlsSta'])!==FALSE) $invalidstate=TRUE; else $invalidstate=FALSE;
					print (@$GLOBALS['xxEstimatorTitle']!='' ? '<div class="estimatortitle">' . $GLOBALS['xxEstimatorTitle'] . '</div>' : '');
					print '<div ' . ($errormsg!=''?'class="estimatorerrors" ':'') . 'id="estimatorerrors">' . ($errormsg!='' ? '<div class="estimatorerror ectwarning">' . $errormsg . '</div>':'') . '</div>';
					if($adminAltRates>0){
						print '<div class="shipestimatemarkup_cntnr"><div class="cartestimatortext">';
						writeestimatormenu();
						print "</div></div>\r\n";
					}
					if($wantstateselector){
						print '<div class="cartstateselector_cntnr"><div class="cartstateselectortext' . ($invalidstate ? ' ectwarning' : '') . '">';
						print '<label class="ectlabel" for="state" id="statetxt">'.$GLOBALS['xxAllSta'].'</label>';
						print '</div><div class="cartstateselector' . ($invalidstate ? ' ectwarning' : '') . '">';
						print '<select name="state" id="state" class="ectselectinput nofixw cartstateselector' . ($invalidstate ? ' ectwarning' : '') . '" size="1" onchange="revealestimatorgo()">'; show_states($shipstate); print '</select>';
						print "</div></div>\r\n";
					}
					if($wantcountryselector){
						print '<div class="cartcountryselector_cntnr"><div class="cartcountryselectortext">';
						print labeltxt($GLOBALS['xxCountry'],'country');
						print '</div><div class="cartcountryselector">';
						print '<select name="country" id="country" class="ectselectinput nofixw" size="1"' . ($mobilebrowser?' style="font-size:10px"':'') . ' onchange="' . ($wantstateselector||$wantzipselector ? "dynamiccountries(this,'');" : '') . "updateestimator('".$cartlistnumber.'\',false)">';
						$sSQL='SELECT countryID,countryName,countryCode,' . getlangid('countryName',8) . ' AS cnameshow FROM countries WHERE countryEnabled=1 ORDER BY countryOrder DESC,' . getlangid('countryName',8);
						$result=ect_query($sSQL) or ect_error();
						while($rs=ect_fetch_assoc($result)){
							print '<option value="' . $rs['countryID'] . '"';
							if($shipcountry==$rs['countryName']) print ' selected="selected"';
							$cnameshow=$rs['cnameshow'];
							if($cnameshow=='United States of America' && $mobilebrowser) $cnameshow='USA';
							print '>' . $cnameshow . "</option>\r\n";
						}
						ect_free_result($result);
						print '</select>';
						print "</div></div>\r\n";
					}
					if($wantzipselector){
						print '<div class="cartzipselector_cntnr"><div class="cartzipselectortext' . ($invalidzip ? ' ectwarning' : '') . '">';
						print '<label class="ectlabel" for="zip" id="ziptxt">'.$GLOBALS['xxZip'].'</label>';
						print '</div><div class="cartzipselector' . ($invalidzip ? ' ectwarning' : '') . '">';
						print '<input type="text" name="zip" id="zip" class="ecttextinput nofixw cartzipselector' . ($invalidzip ? ' ectwarning' : '') . '" size="8" value="' . htmlspecials($destZip) . '" onkeydown="revealestimatorgo()" autocapitalize="characters" />';
						print "</div></div>\r\n";
					}
					if($wantstateselector || $wantcountryselector || $wantzipselector){
						print '<div id="updateestimator" class="updateestimator" style="display:none">' . imageorbuttontag(@$GLOBALS['imgupdateestimator'],$GLOBALS['xxUpdEst'],'updateestimator',"updateestimator('".$cartlistnumber.'\',true)',TRUE) . '</div>';
					}
				}
				if(@$GLOBALS['xxEstimatorEnd']!='' && $checkoutmode!='savedcart') print '<div class="cartestimatorend">' . $GLOBALS['xxEstimatorEnd'] . '</div>';
				print '</div>';
				print '<div class="carttotals">'; // {
				print '<div class="cartsubtotal_cntnr"><div class="cartsubtotaltext">' . $GLOBALS['xxSubTot'] . '</div><div class="cartsubtotal">' . FormatEuroCurrency($totalgoods) . "</div></div>\r\n";
				if($estimateshipping){
					print '<div class="shippingtotal_cntnr" id="shippingtotal_cntnr"' . ($errormsg!='' ? ' style="display:none"' : '') . '><div class="shippingtotaltext">' . ($handling==0 || $errormsg!='' ? $GLOBALS['xxShpEst'] : $GLOBALS['xxShHaEs']) . '</div><div class="shippingtotal" id="estimatorspan">';
					if($errormsg!='')
						print $errormsg;
					elseif($freeshipamnt==($shipping+$handling))
						print $GLOBALS['xxFree'];
					else
						print FormatEuroCurrency(($shipping+$handling)-$freeshipamnt);
					print '</div></div>';
				}
				if(@$GLOBALS['showtaxinclusive']!=3) displaydiscounts();
				if(@$GLOBALS['showtaxinclusive']!=0){
					if($stateTax>0 && $origCountryID==2 && $shipCountryID==2){
						print '<div class="cartcountrytax_cntnr"><div class="cartcountrytaxtext">';
						print $xxStaTax;
						print '</div><div class="cartcountrytax">';
						print '<span id="countrytaxspan">' . FormatEuroCurrency($stateTax) . '</span>';
						print "</div></div>\n";
					}else
						$stateTax=0;
					print '<div class="cartcountrytax_cntnr"><div class="cartcountrytaxtext">';
					print $usehst?$GLOBALS['xxHST']:$GLOBALS['xxCntTax'];
					print '</div><div class="cartcountrytax">';
					print '<span id="countrytaxspan">' . FormatEuroCurrency($countryTax) . '</span>';
					print "</div></div>\r\n";
					if(@$GLOBALS['showtaxinclusive']==3) displaydiscounts();
				}else{
					$stateTax=0;
					$countryTax=0;
				}
				print '<div class="cartgrandtotal_cntnr"><div class="cartgrandtotaltext">';
				if(getget('pla')==''){
					print ($checkoutmode=='savedcart' ? $GLOBALS['xxItmTot'] : $GLOBALS['xxGndTot']);
					print '</div><div class="cartgrandtotal"'.($checkoutmode!='savedcart'?' id="grandtotalspan"':'') . '>';
					print FormatEuroCurrency(($totalgoods+$shipping+$handling+$stateTax+$countryTax)-($totaldiscounts+$freeshipamnt+$loyaltypointdiscount));
				}
				print '</div></div>';
				if(getget('pla')==''){
					if(($GLOBALS['adminPayLater'] & 16)==16){
						print '<div data-pp-message data-pp-style-text-align="right" data-pp-amount="' . (($totalgoods+$shipping+$handling+$stateTax+$countryTax)-($totaldiscounts+$freeshipamnt+$loyaltypointdiscount)) . '" class="paylaterquote cartpaylaterquote"></div>'."\n";
					}
				}
				if($giftcertsamount!=0){
					print '<div class="cartgiftcert_cntnr"><div class="cartgiftcerttext ectdscntt">' . $GLOBALS['xxAppGC'] . '</div><div class="cartgiftcert ectdscnt">' . FormatEuroCurrency(min($giftcertsamount,($totalgoods+$shipping+$handling+$stateTax+$countryTax)-($totaldiscounts+$freeshipamnt+$loyaltypointdiscount))) . '</div></div>';
				}
				if($checkoutmode!='savedcart'){
					$sSQL="SELECT cpnID FROM coupons WHERE cpnIsCoupon<>0 AND cpnNumAvail>0 AND cpnStartDate<='" . date('Y-m-d', time()+($GLOBALS['dateadjust']*60*60)) ."' AND cpnEndDate>='" . date('Y-m-d', time()+($GLOBALS['dateadjust']*60*60)) . "' AND ((cpnLoginLevel>=0 AND cpnLoginLevel<=".$minloglevel.') OR (cpnLoginLevel<0 AND -1-cpnLoginLevel='.$minloglevel.')) LIMIT 0,1';
					$result=ect_query($sSQL) or ect_error();
					$hasacoupon=ect_num_rows($result)>0;
					ect_free_result($result);
					if($hasacoupon){
						print '<div class="cartcoupon_cntnr">';
						print '<div class="cartcoupontext">' . labeltxt($GLOBALS['xxGifNum'],'cpncode') . '</div>';
						if(trim_(@$_SESSION['giftcerts'])!=''){
							$cpnarr=explode(' ', trim_(@$_SESSION['giftcerts']));
							foreach($cpnarr as $key=>$value)
								print '<div class="cartcouponapplied">' . imageorlink('',$GLOBALS['xxRemove'].' : '.$value,'applycoupon removecoupon1',"removecert('".$value."')",TRUE) . '</div>';
						}
						if(trim_(@$_SESSION['cpncode'])!=''){
							$cpnarr=explode(' ', trim_(@$_SESSION['cpncode']));
							foreach($cpnarr as $key=>$value)
								print '<div class="cartcouponapplied">' . imageorlink('',$GLOBALS['xxRemove'].' : '.$value,'applycoupon removecoupon1',"removecert('".$value."')",TRUE) . '</div>';
						}
						print '<div class="cartcoupon"><input type="text" name="cpncode" class="ecttextinput cpncart1" placeholder="' . placeholder(@$GLOBALS['nogiftcertificate']?$GLOBALS['xxGifNum']:$GLOBALS['xxCoGfPl']) . '" id="cpncode" autocomplete="off" /> ' . imageorbuttontag(@$GLOBALS['imgapplycoupon'],$GLOBALS['xxApply'],'applycoupon applycoupon1','applycert()',TRUE) . '</div>';
						print '</div>';
					}
				}
				print '</div></div>'; // carttotals cartshippingandtotals } }
				if($checkoutmode!='savedcart'){
					if(@$_SESSION['tofreeshipamount']!='')
						print '<div class="tofreeshipping">' . replace($GLOBALS['xxToFSAm'],'%s',FormatEuroCurrency($_SESSION['tofreeshipamount'])) . '</div>';
					elseif(@$_SESSION['tofreeshipquant']!='')
						print '<div class="tofreeshipping">' . replace($GLOBALS['xxToFSQu'],'%s',$_SESSION['tofreeshipquant']) . '</div>';
				}
			}
			if($amazonpaycheckout || @$_SESSION['AmazonLogin']!=''){
				if(getpayprovdetails(21,$data1,$data2,$data3,$demomode,$ppmethod)){
					print '<script>window.onAmazonLoginReady=function(){amazon.Login.setClientId("' . $data1 . '");};</script>';
					print '<script src="' . getamazonjsurl($demomode) . '"></script>';
				}
			}
			if($amazonpaycheckout){
				if(time()>=$_SESSION['AmazonLoginTimeout']){
					$_SESSION['AmazonLogin']=$_SESSION['AmazonLoginTimeout']='';
				}else{
					if(getpayprovdetails(21,$data1,$data2,$data3,$demomode,$ppmethod)){
						$data2arr=explode('&',$data2);
						$data2=$data2arr[0];
						$sellerid=@$data2arr[1];

						print '<div class="amazoncontent">';
							print '<div class="amazonaddressandwallet">';
								print '<div id="addressBookWidgetDiv"></div>';
								print '<div id="walletWidgetDiv"></div>';
							print '</div>';
						print '<div class="amazonbuttons"><div class="paynowamazon">' . imageorbuttontag(@$imgamazonpaynow,'Click to Check Totals'.($shipType!=0?' / Select Shipping':''),'amazonpaynow','amazonpaynow()',TRUE) . '</div><div class="amazonlogout2">' . imageorlink(@$imgamazonlogout,'Logout of your Amazon account','amazonlogout','return amazonlogout()',TRUE) . '</div></div>';
						print '</div>'; ?>
<script>
var amznorderreferenceid='';
var addressselected=false,paymentselected=false;
new OffAmazonPayments.Widgets.AddressBook({
  sellerId: '<?php print $sellerid?>',
  onOrderReferenceCreate: function(orderReference) {
	amznorderreferenceid=orderReference.getAmazonOrderReferenceId();
  },
  onAddressSelect: function(orderReference) {
	addressselected=true;
	paymentselected=false;
  },
  design: {
	designMode: 'responsive'
  },
  onError: function(error) {
	alert(error.getErrorMessage());
  }
}).bind("addressBookWidgetDiv");

new OffAmazonPayments.Widgets.Wallet({
  sellerId: '<?php print $sellerid?>',
  onPaymentSelect: function(orderReference) {
	paymentselected=true;
  },
  design: {
	designMode: 'responsive'
  },
  onError: function(error) {
  }
}).bind("walletWidgetDiv");
function amazonpaynow(){
	if(amznorderreferenceid!='')
		document.location='cart<?php print $GLOBALS['extension']?>?amzrefid='+amznorderreferenceid;
	else
		alert("Please select an address and payment method.");
}
</script>
<?php				}
				}
			}else{ // cartcheckoutbuttons
				print '<div class="cartcheckoutbuttons">'; // {
				if(trim_(@$_SESSION['clientID'])!=''){
					srand((int)((float)microtime()*1000000));
					$sequence=ip2long($GLOBALS['REMOTE_ADDR']);
					if($sequence===FALSE) $sequence=0;
					ect_query("DELETE FROM tmplogin WHERE tmplogindate < '" . date("Y-m-d H:i:s", time()-(3*60*60*24)) . "' OR tmploginid='" . escape_string($thesessionid) . "'") or ect_error();
					ect_query("INSERT INTO tmplogin (tmploginid, tmploginname, tmploginchk, tmplogindate) VALUES ('" . escape_string($thesessionid) . "','" . escape_string($_SESSION['clientID']) . "','" . $sequence . "','" . date('Y-m-d H:i:s', time()) . "')") or ect_error();
					print whv('checktmplogin',$sequence);
					if(($_SESSION['clientActions'] & 8)==8 || ($_SESSION['clientActions'] & 16)==16){
						if(@$GLOBALS['minwholesaleamount']!='') $GLOBALS['minpurchaseamount']=$GLOBALS['minwholesaleamount'];
						if(@$GLOBALS['minwholesalequantity']!='') $GLOBALS['minpurchasequantity']=$GLOBALS['minwholesalequantity'];
						if(@$GLOBALS['minwholesalemessage']!='') $GLOBALS['minpurchasemessage']=$GLOBALS['minwholesalemessage'];
					}
				}else
					print whv('checktmplogin','x');
				$estimate=($totalgoods+$shipping+$handling+$stateTax+$countryTax)-($totaldiscounts+$freeshipamnt+$loyaltypointdiscount);
				if($checkoutmode=='savedcart'){
					// Do nothing
				}elseif($totalgoods<@$GLOBALS['minpurchaseamount'] || $totalquantity<@$GLOBALS['minpurchasequantity']){
					print '<div class="checkoutopts cominpurchase ectwarning">' . @$GLOBALS['minpurchasemessage'] . '</div>';
				}elseif(@$GLOBALS['forceclientlogin'] && @$_SESSION['clientID']==''){
					print '<div class="checkoutopts coforcelogin">' . $GLOBALS['xxBfChk'] . ' <a class="ectlink" href="#" onclick="return displayloginaccount()">' . $GLOBALS['xxLogin'] . '</a>' . (@$GLOBALS['allowclientregistration'] ? ' ' . $GLOBALS['xxOr'] . ' <a class="ectlink" href="#" onclick="return displaynewaccount()">' . $GLOBALS['xxCrAc'] . '</a>' : '') . '.</div>';
				}elseif($stockwarning){
					// Do nothing
				}else{
					$sSQL='SELECT payProvID,payProvData1,payProvData2,payProvData3,payProvDemo,payProvBits,payProvMethod,payProvFlag1 FROM payprovider WHERE payProvEnabled=1 AND payProvLevel<=' . $minloglevel . (@$paypalhostedsolution?' AND payProvID<>18':'') . ($estimate<=0?' AND payProvID<>19':'') . ' ORDER BY payProvOrder';
					$result=ect_query($sSQL) or ect_error();
					$regularcheckoutshown=FALSE;
					while($rs=ect_fetch_assoc($result)){
						if($rs['payProvID']==21){
							if(getget('access_token')!=''&&getget('token_type')=='bearer'&&getget('expires_in')!=''&&getget('scope')!=''){
								if(callcurlfunction('https://api.' . ($rs['payProvDemo']?'sandbox.':'') . 'amazon.com/auth/o2/tokeninfo?access_token=' . urlencode(getget('access_token')),'',$res,'',$errormsg, FALSE)){
									if($res!=''){
										$resarray=explode(',',trim($res,'{}'));
										foreach($resarray as $key){
											$keypair=explode(':',$key);
											if($keypair[0]=='"aud"'&&$keypair[1]=='"'.$rs['payProvData1'].'"'){
												$_SESSION['AmazonLogin']=trim($res,'{}');
													if(ob_get_length()!==FALSE)
														header('Location: '.$storeurlssl.'cart'.$GLOBALS['extension'].'?amazonpay=go');
													else
														print '<meta http-equiv="Refresh" content="0; URL='.$storeurlssl.'cart'.$GLOBALS['extension'].'?amazonpay=go">';
											}elseif($keypair[0]=='"exp"'){
												$_SESSION['AmazonLoginTimeout']=time()+(int)$keypair[1];
											}
										}
									}
								}
							}else{

		print '<div class="checkoutopts coopt21" id="AmazonPayButton"></div>';
		print '<script>window.onAmazonLoginReady=function(){amazon.Login.setClientId("' . $rs['payProvData1'] . '");};</script>';
		print '<script src="' . getamazonjsurl($demomode) . '"></script>';
?>					
<script>
var authRequest;
OffAmazonPayments.Button("AmazonPayButton", "<?php print $rs['payProvData2']?>", { // MERCHANT_ID
	type: "<?php print @$_SESSION['AmazonLogin']!=''?'PwA':'LwA'?>",
	authorization: function () {
		loginOptions = { scope: "profile postal_code payments:widget payments:shipping_address", popup: true };
		authRequest = amazon.Login.authorize(loginOptions, "<?php print $storeurlssl.'cart'.$GLOBALS['extension'].'?amazonpay=go'?>");
	},
	onError: function (error) {
		alert("handle error function");
	}
});
function amazonlogout(){
	amazon.Login.logout();
	document.location='cart<?php print $GLOBALS['extension']?>?amazon=logout';
	return false;
}
</script>
<?php
							}
						}elseif($rs['payProvID']==25&&(($rs['payProvBits']&32)==32)){
			$includebraintree=TRUE;
			$success=TRUE;
			$url='https://api.' . ($rs['payProvDemo']?'sandbox.':'') . 'braintreegateway.com:443/merchants/'.$rs['payProvData1'].'/client_token';
			$sXML='<?xml version="1.0" encoding="UTF-8"?><client_token><version type="integer">2</version></client_token>';
			$GLOBALS['xmlfnheaders']=array("Accept: application/xml","Content-Type: application/xml");
			$GLOBALS['xmlfnuser']=$rs['payProvData2'];
			$GLOBALS['xmlfnpassword']=$rs['payProvData3'];
			if(callcurlfunction($url,$sXML,$res,'',$errormsg,FALSE)){
				if($res!=''){
					if(strpos($res,'<')!==FALSE){
						$resxml=@new SimpleXMLElement($res);
						if(($clientToken=$resxml->value)!=''){
							//print $clientToken;
						}elseif(@$resxml->message!=''){
							print '<div style="color:#FF0000">' . $resxml->message . '</div>';
							$success=FALSE;
						}else
							print '<div style="color:#FF0000">Braintree: ' . str_replace('<','&lt;',$res) . '</div>';
					}else
						print '<div style="color:#FF0000">Braintree: ' . $res . '</div>';
				}else{
					print '<div style="color:#FF0000">Invalid response from Braintree.</div>';
					$success=FALSE;
				}
			}else{
				print '<div style="color:#FF0000">' . $errormsg . '</div>';
				$success=FALSE;
			}
?>
	<div id="braintree-button" class="checkoutopts coopts25"></div>
	<!-- PayPal Script -->
	<script src="https://www.paypalobjects.com/api/checkout.js" data-version-4></script>
	<!-- Braintree Scripts -->
	<script src="https://js.braintreegateway.com/web/3.138.0/js/client.min.js"></script>
	<script src="https://js.braintreegateway.com/web/3.138.0/js/paypal-checkout.min.js"></script>
	<script src="https://js.braintreegateway.com/web/3.138.0/js/data-collector.min.js"></script>

<script>
function onCancel(){
}
function onError(err){
	alert(err.message);
}
function setupFinish(data) {
	document.getElementById('btname').value=data.details.firstName;
	document.getElementById('btlastname').value=data.details.lastName;
	document.getElementById('btaddress').value=data.details.shippingAddress.line1;
	document.getElementById('btcity').value=data.details.shippingAddress.city;
	document.getElementById('btstate').value=data.details.shippingAddress.state;
	document.getElementById('btzip').value=data.details.shippingAddress.postalCode;
	document.getElementById('btcountry').value=data.details.shippingAddress.countryCode;
	document.getElementById('btemail').value=data.details.email;
	document.getElementById('btphone').value=data.details.phone?data.details.phone:'';
	document.getElementById('btnonce').value=data.nonce;
	document.getElementById('braintreeform').submit();
}
var auth='<?php print $clientToken?>';
var braintreePaypalOptions={
	flow: 'checkout',
	intent: 'authorize',
	enableShippingAddress: true,
	currency: '<?php print $countryCurrency?>',
	amount: '<?php print number_format($estimate,2,'.','')?>'
};
var checkoutJs={
	commit: false,
	locale: 'en_US',
	style: {
		size: 'medium',
		color: 'gold',
		shape: 'pill'
	}
};
braintree.client.create({
	authorization: auth
}, function (clientErr, clientInstance){
	// braintree.dataCollector.create({ client: clientInstance, paypal: true }, function (err, data){console.log('Risk Data:', data);});
	braintree.paypalCheckout.create({
		client: clientInstance
	}, function (paypalCheckoutErr, paypalCheckoutInstance){
		var braintreeEnvironment=clientInstance.getConfiguration().gatewayConfiguration.environment;
		if (paypalCheckoutErr) {
			alert('Error creating PayPal Checkout:'+paypalCheckoutErr);
			return;
		}
		paypal.Button.render({
			env: braintreeEnvironment === 'production' ? 'production' : 'sandbox',
			payment: function(){
				return paypalCheckoutInstance.createPayment(braintreePaypalOptions);
			},   
			onAuthorize: function(data, actions){
				return paypalCheckoutInstance.tokenizePayment(data).then(setupFinish);
			},
			onCancel: onCancel,
			onError: onError,
			locale: checkoutJs.locale,
			commit: checkoutJs.commit,
			style: checkoutJs.style
		}, '#braintree-button');
	});
});
</script>
<?php					}elseif($rs['payProvID']==19){
							$wantbillmelater=FALSE;
							$data2arr=explode('&',$rs['payProvData2']);
							$wantbillmelater=(trim(urldecode(@$data2arr[3]))=='1');
							if($wantbillmelater){
								print '<div class="checkoutopts coopt' . $rs['payProvID'] . '"><input type="image" src="https://www.paypalobjects.com/webstatic/en_US/btn/btn_bml_SM.png" onclick="document.forms.checkoutform.cart.value=\'\';document.forms.checkoutform.mode.value=\'billmelater\';" alt="Bill Me Later" title="' . $GLOBALS['xxPPPBlu'] . "\" /></div>\r\n";
							}
							print '<div class="checkoutopts coopt' . $rs['payProvID'] . '"><input type="image" src="https://www.paypal.com/en_US/i/btn/btn_xpressCheckoutsm.gif" onclick="document.forms.checkoutform.cart.value=\'\';document.forms.checkoutform.mode.value=\'paypalexpress1\';" alt="PayPal Express" title="' . $GLOBALS['xxPPPBlu'] . "\" /></div>\r\n";
						}elseif(! $regularcheckoutshown){
							$regularcheckoutshown=TRUE;
							print '<div class="checkoutopts checkoutoptsregular coopt' . $rs['payProvID'] . '">' . imageorsubmit(@$imgcheckoutbutton,(@$GLOBALS['xxCOTxt1']!=''?$GLOBALS['xxCOTxt1']:$GLOBALS['xxCOTxt']) . '" onclick="document.forms.checkoutform.action=\''.$cartpath.'\';document.forms.checkoutform.cart.value=\'\';document.forms.checkoutform.mode.value=\'checkout\';" title="'.$GLOBALS['xxPrsChk'] . '" id="checkoutbutton1','checkoutbutton checkoutbutton1') . "</div>\r\n";
						}
						if($rs['payProvID']==27&&$rs['payProvFlag1']==1&&$estimate>0){
							$data1=$rs['payProvData1'];
							$data2=$rs['payProvData2'];
							$data3=$rs['payProvData3'];
							$demomode=$rs['payProvDemo'];
							$ppmethod=$rs['payProvMethod'];
							print '<div id="ppcoverdiv" class="ectopaque" style="display:none;text-align:center"><img src="images/preloader.gif" style="margin-top:250px" class="ectpreloader"></div>';
							print '<div class="checkoutopts coopt27">';
							paypalcheckoutjs(TRUE,FALSE,($GLOBALS['adminPayLater']&48)!=0);
							print '</div>';
						}
					}
					ect_free_result($result);
					if(@$_SESSION['AmazonLogin']!='') print '<div class="checkoutopts checkoutbutton1 amazonlogout1">' . imageorlink(@$imgamazonlogout,'Logout of your Amazon account','amazonlogout','return amazonlogout()',TRUE) . '</div>';
				}
				print '</div>'; // } cartcheckoutbuttons
				if($checkoutmode!='savedcart' && @$GLOBALS['googletagid']!=''){
					print '<script>gtag("event","view_cart",{ currency:"' . $countryCurrency . '",value:' . $totalgoods . ',items:[' . getcartforganalytics('') . ']});</script>'."\n";
				}
			}
			if($checkoutmode!='savedcart'){ ?>
<script><?php print $GLOBALS['wpjavascriptcomments']?>/* <![CDATA[ */
<?php
	if(@$_SESSION['AmazonLogin']!=''){ ?>
function amazonlogout(){
	amazon.Login.logout();
	document.location='cart<?php print $GLOBALS['extension']?>?amazon=logout';
	return false;
}
<?php
	}
	if($wantstateselector||$wantzipselector){
		createdynamicstates($stateSQL);
		print "dynamiccountries(document.getElementById('country'),'');setinitialstate('');\r\n";
	}
	if($adminAltRates==2 && ((($shipping+$handling)-$freeshipamnt)>0 || $errormsg!='')){
		print "var bestcarrier=".$shipType.";var bestestimate=" . ((($shipping+$handling)-$freeshipamnt) + ($errormsg!=''?1000000:0)) . ";\r\n";
		print 'var vstotalgoods=' . $totalgoods . ";\r\ngetalternatecarriers();\r\n";
	}
?>
function changechecker(){
<?php	if($minquantityerror||$deleteditemerror) print 'alert("' . ($minquantityerror?jscheck($GLOBALS['xxMinSom']):'') . ($deleteditemerror?($minquantityerror?'\n':'').jscheck($GLOBALS['xxHasDel']):'') . '");return false;';
	if($totalgoods < @$GLOBALS['minpurchaseamount']) print 'if((document.forms.checkoutform.mode.value!="dologin")&&(document.forms.checkoutform.mode.value!="donewaccount"))return false;' ?>
dowarning=false;
<?php print $changechecker?>
if(document.getElementById("cpncode"))document.getElementById("cpncode").value="";
if(dowarning) return !confirm("<?php print jscheck($GLOBALS['xxWrnChQ'])?>");
return true;
}
function preventreturn(tobj,evt){
if(evt.keyCode==13&&evt.target!=ectById('checkoutbutton1')){
	evt.preventDefault();
	if(document.getElementById('zip')&&document.getElementById('zip')===document.activeElement)
		updateestimator('',true);
}
}
/* ]]> */<?php print $GLOBALS['wpjavascriptendcomments']?></script>
<input type="hidden" name="estimate" value="<?php print number_format($estimate,2,'.','') ?>" />
<?php		}
			if((@$_SESSION['clientActions']&64)==64&&$checkoutmode==''){ ?>
				<div class="sharecart" style="text-align:center">
					<input type="button" class="ectbutton widecheckout1" id="sharecartbutton" value="Share Cart" style="width:90%;padding:5px" onclick="dosharecart()" />
					<input type="text" id="sharecartinput" style="width:90%;display:none;padding:5px" />
				</div>
<?php		}
		}else{
			$cartEmpty=TRUE;
			print '<div class="emptycart">';
			if($checkoutmode=='savedcart')
				print '<div class="emptycartemptylist">' . $GLOBALS['xxLisEmp'] . '</div>';
			else{
				print '<div class="sorrycartempty">' . $GLOBALS['xxSryEmp'] . '</div>';
				print '<div class="cartemptyclickhere">' . (getget('pli')!=''?$GLOBALS['xxEmpWis']:$GLOBALS['xxGetSta'] . ' <a class="ectlink" href="'.$GLOBALS['storehomeurl'].'"><strong>'.$GLOBALS['xxClkHere'].'</strong></a>') . '</div>';
			} ?>
<script><?php print $GLOBALS['wpjavascriptcomments']?>/* <![CDATA[ */
var ectvalue=Math.floor(Math.random()*10000 + 1);
document.cookie="ECTTESTCART=" + ectvalue + "; path=/<?php print (@$_SERVER['HTTPS']=='on'?'; secure':'')?>";
if((document.cookie+";").indexOf("ECTTESTCART=" + ectvalue + ";") < 0) document.write("<?php print jscheck($GLOBALS['xxNoCk'] . ' ' . $GLOBALS['xxSecWar'])?>");
/* ]]> */<?php print $GLOBALS['wpjavascriptendcomments']?></script>
<noscript><div class="ectwarning"><?php print $GLOBALS['xxNoJS'] . " " . $GLOBALS['xxSecWar']?></div></noscript>
<?php		print '<div class="emptycartcontinue">';
			if($thefrompage!='' && (@$actionaftercart==2 || @$actionaftercart==3)) $thehref=htmlspecials($thefrompage); else $thehref=$GLOBALS['storehomeurl'];
			print imageorbuttontag(@$imgcontinueshopping,$GLOBALS['xxCntShp'],'',$thehref,FALSE);
			print '</div></div>';
		}
		print '</div>';
		print '</form>';
		if($includebraintree){ ?>
			<form method="post" action="cart<?php print $GLOBALS['extension']?>" id="braintreeform" action="<?php print $cartpath ?>"<?php print ($GLOBALS['itemsincart']>0?' onsubmit="return changechecker(this)"':'')?>>
			<input type="hidden" name="mode" value="go" />
			<input type="hidden" name="sessionid" value="<?php print htmlspecials($thesessionid)?>" />
			<input type="hidden" name="payprovider" value="26" />
			<input type="hidden" name="ordname" id="btname" />
			<input type="hidden" name="lastname" id="btlastname" />
			<input type="hidden" name="address" id="btaddress" />
			<input type="hidden" name="address2" id="btaddress2" />
			<input type="hidden" name="city" id="btcity" />
			<input type="hidden" name="state" id="btstate" />
			<input type="hidden" name="zip" id="btzip" />
			<input type="hidden" name="country" id="btcountry" />
			<input type="hidden" name="phone" id="btphone" />
			<input type="hidden" name="email" id="btemail" />
			<input type="hidden" name="nonce" id="btnonce" />
			</form>
<?php	}
		print "</div></div>\r\n"; // }
	}
	print '</div>'; // } cartlists
}
?>