<?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
global $digidownloadsecret;
if(@$digidownloadsecret=='') $digidownloadsecret='this is some secwet text';
if(@$GLOBALS['xxNoWtIn']=='') @$GLOBALS['xxNoWtIn']=' (Shipping Insurance Declined)';
if(@$dateformatstr=='') $dateformatstr='m/d/Y';
if(@$emailcr=='')$emailcr="\r\n";
$GLOBALS['hasimageupload']=FALSE;
function vrhmac($key, $text){
	$idatastr="                                                                ";
	$odatastr="                                                                ";
	$hkey=(string)$key;
	$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 order_success($sorderid,$sEmail,$sendstoreemail){
	do_order_success($sorderid,$sEmail,$sendstoreemail,TRUE,TRUE,TRUE,TRUE);
}
function getemailrecpt($oid){
	global $xxOrdId,$xxBilAdd,$xxShpAdd,$xxPhone,$xxEmail,$xxShpMet,$xxWtIns,$xxNoWtIn,$xxCerCLo,$xxSatDeR,$xxAddInf,$xxCODets,$xxCOName,$xxCOUPri,$xxQuant,$xxTotal,$xxSubTot,$xxDscnts,$xxShipHa,$xxFree,$xxShippg,$xxHndlg,$xxStaTax,$xxHST,$xxCntTax,$xxGndTot,$ordGrandTotal;
	global $extraorderfield1,$extraorderfield2,$extracheckoutfield1,$extracheckoutfield2,$combineshippinghandling,$hideoptpricediffs,$willpickuptext,$emailcr,$loyaltypoints,$xxGWrSel;
	$recpt='';
	$sSQL="SELECT ordID,ordName,ordLastName,ordAddress,ordAddress2,ordCity,ordState,ordZip,ordCountry,ordEmail,ordPhone,ordShipName,ordShipLastName,ordShipAddress,ordShipAddress2,ordShipCity,ordShipState,ordShipZip,ordShipCountry,ordShipPhone,ordPayProvider,ordAuthNumber,ordTotal,ordDate,ordStateTax,ordCountryTax,ordHSTTax,ordHandling,ordShipping,ordAffiliate,ordShipType,ordShipCarrier,ordDiscount,ordDiscountText,ordComLoc,ordExtra1,ordExtra2,ordShipExtra1,ordShipExtra2,ordCheckoutExtra1,ordCheckoutExtra2,ordSessionID,payProvID,ordAddInfo FROM orders INNER JOIN payprovider ON payprovider.payProvID=orders.ordPayProvider WHERE ordAuthNumber<>'' AND ordID='".escape_string($oid)."'";
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		$recpt.='<table width="100%" border="0" cellspacing="1" cellpadding="3">';
		$recpt.='  <tr>';
		$recpt.='	<td valign="top" colspan="5">';
		$recpt.='	  <table width="100%" border="0" cellspacing="1" cellpadding="3">';
		if(trim_($rs['ordShipAddress'])!='') $hasshipaddress=TRUE; else $hasshipaddress=FALSE;
		$recpt.='		<tr>';
		$recpt.='		  <td valign="top"><strong>'.$xxOrdId.':</strong></td>';
		$recpt.='		  <td valign="top">'.$rs['ordID'].'</td>';
		$recpt.='		  <td>&nbsp;</td><td>&nbsp;</td>';
		$recpt.='		</tr>'.$emailcr;
		if(trim_(@$extraorderfield1)!=''){
			$recpt.='	<tr>';
			$recpt.='	  <td valign="top"><strong>'.$extraorderfield1.':</strong></td>';
			$recpt.='	  <td valign="top">'.$rs['ordExtra1'].'</td>';
			if($hasshipaddress){
				$recpt.=' <td valign="top"><strong>'.$extraorderfield1.':</strong></td>';
				$recpt.=' <td valign="top">'.$rs['ordShipExtra1'].'</td>';
			}
			$recpt.='	</tr>'.$emailcr;
		}
		$recpt.='		<tr>';
		$recpt.='		  <td valign="top" width="20%"><strong>'.$xxBilAdd.':</strong></td>';
		$recpt.='		  <td valign="top">';
		$recpt.=trim_($rs['ordName'].' '.$rs['ordLastName']) . '<br />';
		$recpt.=$rs['ordAddress'] . '<br />';
		if(trim_($rs['ordAddress2'])!='') $recpt.=$rs['ordAddress2'] . '<br />';
		$recpt.=$rs['ordCity'] . ', ' . $rs['ordState'] . '<br />';
		$recpt.=$rs['ordZip'] . '<br />';
		$recpt.=$rs['ordCountry'] . '<br />';
		$recpt.='		  </td>';
		if($hasshipaddress){
			$recpt.='	  <td valign="top" width="20%"><strong>'.$xxShpAdd.':</strong></td>';
			$recpt.='	  <td valign="top">';
			$recpt.=trim_($rs['ordShipName'].' '.$rs['ordShipLastName']) . '<br />';
			$recpt.=$rs['ordShipAddress'] . '<br />';
			if(trim_($rs['ordShipAddress2'])!='') $recpt.=$rs['ordShipAddress2'] . '<br />';
			$recpt.=$rs['ordShipCity'] . ', ' . $rs['ordShipState'] . '<br />';
			$recpt.=$rs['ordShipZip'] . '<br />';
			$recpt.=$rs['ordShipCountry'] . '<br />';
			$recpt.='	  </td>';
		}
		$recpt.='		</tr>'.$emailcr;
		if(trim_(@$extraorderfield2)!=''){
			$recpt.='	<tr>';
			$recpt.='	  <td valign="top"><strong>'.$extraorderfield2.':</strong></td>';
			$recpt.='	  <td valign="top">'.$rs['ordExtra2'].'</td>';
			if($hasshipaddress){
				$recpt.='  <td valign="top"><strong>'.$extraorderfield2.':</strong></td>';
				$recpt.='  <td valign="top">'.$rs['ordShipExtra2'].'</td>';
			}
			$recpt.='	</tr>'.$emailcr;
		}
		$recpt.='		<tr>';
		$recpt.='		  <td valign="top"><strong>'.$xxPhone.':</strong></td>';
		$recpt.='		  <td valign="top">'.$rs['ordPhone'].'</td>';
		if($hasshipaddress){
			$recpt.='	  <td valign="top"><strong>'.$xxPhone.':</strong></td>';
			$recpt.='	  <td valign="top">'.$rs['ordShipPhone'].'</td>';
		}
		$recpt.='		</tr>'.$emailcr;
		$recpt.='		<tr>';
		$recpt.='		  <td valign="top"><strong>'.$xxEmail.':</strong></td>';
		$recpt.='		  <td valign="top">'.$rs['ordEmail'].'</td>';
		$ordShipType=$rs['ordShipType'];
		if($ordShipType!=''){
			$shiptext='<td valign="top"><strong>' . $xxShpMet . ':</strong></td><td valign="top">' . $ordShipType;
			if(@$willpickuptext!=$ordShipType){
				if(($rs['ordComLoc'] & 2)==2) $shiptext.=$xxWtIns; elseif(@$GLOBALS['forceinsuranceselection']) $shiptext.=$xxNoWtIn;
			}
			$shiptext.='<br />';
			if(($rs['ordComLoc'] & 1)==1) $shiptext.=$xxCerCLo . '<br />';
			if(($rs['ordComLoc'] & 4)==4) $shiptext.=$xxSatDeR . '<br />';
			$shiptext.='</td>';
		}else
			$shiptext='';
		if($hasshipaddress){
			if($shiptext=='') $recpt.='<td>&nbsp;</td><td>&nbsp;</td>'; else $recpt.=$shiptext;
		}
		$recpt.='		</tr>'.$emailcr;
		if(! $hasshipaddress){
			if($shiptext!='') $recpt.='<tr>' . $shiptext . '</tr>';
		}
		if(trim_(@$extracheckoutfield1)!='' && trim_($rs['ordCheckoutExtra1'])!=''){
			$recpt.='	<tr>';
			$recpt.='	  <td valign="top"><strong>'.$extracheckoutfield1.':</strong></td>';
			$recpt.='	  <td valign="top"'.($hasshipaddress?' colspan="3"':'').'>'.$rs['ordCheckoutExtra1'].'</td>';
			$recpt.='	</tr>'.$emailcr;
		}
		if(trim_(@$extracheckoutfield2)!='' && trim_($rs['ordCheckoutExtra2'])!=''){
			$recpt.='	<tr>';
			$recpt.='	  <td valign="top"><strong>'.$extracheckoutfield2.':</strong></td>';
			$recpt.='	  <td valign="top"'.($hasshipaddress?' colspan="3"':'').'>'.$rs['ordCheckoutExtra2'].'</td>';
			$recpt.='	</tr>'.$emailcr;
		}
		if(@$loyaltypoints!='') $recpt.='<!--%loyaltypointplaceholder%-->';
		$ordAddInfo=trim_($rs['ordAddInfo']);
		if($ordAddInfo!=''){
			$recpt.='	<tr>';
			$recpt.='	  <td valign="top"><strong>'.$xxAddInf.':</strong></td>';
			$recpt.='	  <td valign="top" colspan="3">'.str_replace(array("\r","\n"),array('','<br />'),$ordAddInfo).'</td>';
			$recpt.='	</tr>'.$emailcr;
		}
		$recpt.='<!--%digidownloadplaceholder%-->';
		$recpt.='	  </table>';
		$recpt.='	</td>';
		$recpt.='  </tr>'.$emailcr;
		$recpt.='<!--%digidownloaditems%-->';
		$recpt.='  <tr><td align="center" colspan="5"><hr class="receipthr" width="80%"></td></tr>';
		$recpt.='  <tr>';
		$recpt.='	<td class="receiptheading" width="15%" height="25" align="left"><strong>'.$xxCODets.'</strong></td>';
		$recpt.='	<td class="receiptheading" width="33%" height="25" align="left"><strong>'.$xxCOName.'</strong></td>';
		if(!@$GLOBALS['nopriceanywhere']) $recpt.='	<td class="receiptheading" width="14%" height="25" align="right"><strong>'.$xxCOUPri.'</strong></td>';
		$recpt.='	<td class="receiptheading" width="14%" height="25" align="right"><strong>'.$xxQuant.'</strong></td>';
		if(!@$GLOBALS['nopriceanywhere']) $recpt.='	<td class="receiptheading" width="14%" height="25" align="right"><strong>'.$xxTotal.'</strong></td>';
		$recpt.='  </tr>'.$emailcr;
	}
	ect_free_result($result);
	$sSQL="SELECT cartID,cartProdID,cartProdName,cartProdPrice,cartQuantity,cartGiftWrap FROM cart WHERE cartOrderID='" . escape_string($oid) . "' ORDER BY cartID";
	$result=ect_query($sSQL) or ect_error();
	while($alldata=ect_fetch_assoc($result)){
		$theoptions='';
		$theoptionspricediff=0;
		$isoutofstock=FALSE;
		$sSQL='SELECT coID,coOptGroup,coCartOption,coPriceDiff,coWeightDiff,optAltImage FROM cartoptions LEFT JOIN options ON cartoptions.coOptID=options.optID WHERE coCartID='.$alldata['cartID'].' ORDER BY coID';
		$opts=ect_query($sSQL) or ect_error();
		while($rs2=ect_fetch_assoc($opts)){
			$theoptionspricediff+=$rs2['coPriceDiff'];
			$theoptions.='<tr>';
			$theoptions.='<td class="receiptoption" align="right"><span style="font-size:0.82em"><strong>'.$rs2['coOptGroup'].':</strong></span></td>';
			$theoptions.='<td class="receiptoption" align="left"><span style="font-size:0.82em">' . (strpos($rs2['coCartOption'],"\n")===FALSE?'&nbsp;- ':'') . str_replace(array("\r","\n",$emailcr),array('','<br />','<br />'),strip_tags($rs2['coCartOption'])) . '</span></td>';
			if(!@$GLOBALS['nopriceanywhere']) $theoptions.='<td class="receiptoption" align="right"><span style="font-size:0.82em">' . ($rs2['coPriceDiff']==0 || @$hideoptpricediffs==TRUE ? '- ' : FormatEuroCurrency($rs2['coPriceDiff'])) . '</span></td>';
			$theoptions.='<td class="receiptoption">&nbsp;</td>';
			if(!@$GLOBALS['nopriceanywhere']) $theoptions.='<td class="receiptoption" align="right"><span style="font-size:0.82em">' . ($rs2['coPriceDiff']==0 || @$hideoptpricediffs==TRUE ? '- ' : FormatEuroCurrency($rs2['coPriceDiff']*$alldata['cartQuantity'])) . '</span></td>';
			$theoptions.='</tr>'.$emailcr;
		}
		ect_free_result($opts);
		$recpt.='  <tr>';
		$recpt.='	<td class="cobhl receipthl" align="left" height="25"><strong>' . $alldata['cartProdID'] . '</strong></td>';
		$recpt.='	<td class="cobhl receipthl" align="left">'.$alldata['cartProdName'];
		if($alldata['cartGiftWrap']!=0) $recpt.='<div class="giftwrap">' . $xxGWrSel . '</div>';
		if(!@$GLOBALS['nopriceanywhere']) $recpt.='</td><td class="cobhl receipthl" align="right">'.(@$hideoptpricediffs==TRUE ? FormatEuroCurrency($alldata['cartProdPrice'] + $theoptionspricediff) : FormatEuroCurrency($alldata['cartProdPrice'])).'</td>';
		$recpt.='	<td class="cobhl receipthl" align="right">'.$alldata['cartQuantity'].'</td>';
		if(!@$GLOBALS['nopriceanywhere']) $recpt.='	<td class="cobhl receipthl" align="right">'.(@$hideoptpricediffs==TRUE ? FormatEuroCurrency(($alldata['cartProdPrice'] + $theoptionspricediff)*$alldata['cartQuantity']) : FormatEuroCurrency($alldata['cartProdPrice']*$alldata['cartQuantity'])).'</td>';
		$recpt.='  </tr>'.$emailcr;
		$recpt.=$theoptions;
	}
	if(!@$GLOBALS['nopriceanywhere']){
		$recpt.='	  <tr>';
		$recpt.='		<td colspan="3">&nbsp;</td>';
		$recpt.='		<td align="right"><strong>'.$xxSubTot.':</strong></td>';
		$recpt.='		<td align="right">'.FormatEuroCurrency($rs['ordTotal']).'</td>';
		$recpt.='	  </tr>'.$emailcr;
		if($rs['ordDiscount']>0){
			$recpt.=' <tr>';
			$recpt.='	<td colspan="3">&nbsp;</td>';
			$recpt.='	<td align="right"><strong>'.$xxDscnts.':</strong></td>';
			$recpt.='	<td class="recptdiscount" align="right" style="color:#FF0000">'.FormatEuroCurrency($rs['ordDiscount']).'</td>';
			$recpt.=' </tr>'.$emailcr;
		}
		if($rs['ordShipCarrier']==0&&(($rs['ordShipping']+$rs['ordHandling'])==0)){
			// Do nothing
		}elseif(@$combineshippinghandling==TRUE){
			$recpt.=' <tr>';
			$recpt.='	<td colspan="2">&nbsp;</td>';
			$recpt.='	<td colspan="2" align="right"><strong>'.$xxShipHa.':</strong></td>';
			$recpt.='	<td align="right">'. (($rs['ordShipping']+$rs['ordHandling'])==0?'<p align="center"><span style="color:#FF0000;font-weight:bold">' . $xxFree . '</span></p>':FormatEuroCurrency($rs['ordShipping']+$rs['ordHandling'])).'</td>';
			$recpt.=' </tr>'.$emailcr;
		}else{
			if($rs['ordShipping']>0){
				$recpt.='  <tr>';
				$recpt.='	<td colspan="3">&nbsp;</td>';
				$recpt.='	<td align="right"><strong>'.$xxShippg.':</strong></td>';
				$recpt.='	<td align="right">'.FormatEuroCurrency($rs['ordShipping']).'</td>';
				$recpt.='  </tr>'.$emailcr;
			}
			if($rs['ordHandling']>0){
				$recpt.='	  <tr>';
				$recpt.='		<td colspan="3">&nbsp;</td>';
				$recpt.='		<td align="right"><strong>'.$xxHndlg.':</strong></td>';
				$recpt.='		<td align="right">'.FormatEuroCurrency($rs['ordHandling']).'</td>';
				$recpt.='	  </tr>'.$emailcr;
			}
		}
		if($rs['ordStateTax']>0){
			$recpt.='  <tr>';
			$recpt.='	<td colspan="3">&nbsp;</td>';
			$recpt.='	<td align="right"><strong>'.$xxStaTax.':</strong></td>';
			$recpt.='	<td align="right">'.FormatEuroCurrency($rs['ordStateTax']).'</td>';
			$recpt.='  </tr>'.$emailcr;
		}
		if($rs['ordHSTTax']>0){
			$recpt.='  <tr>';
			$recpt.='	<td colspan="3">&nbsp;</td>';
			$recpt.='	<td align="right"><strong>'.$xxHST.':</strong></td>';
			$recpt.='	<td align="right">'.FormatEuroCurrency($rs['ordHSTTax']).'</td>';
			$recpt.='  </tr>'.$emailcr;
		}
		if($rs['ordCountryTax']>0||@$GLOBALS['alwaysdisplaycountrytax']){
			$recpt.='  <tr>';
			$recpt.='	<td colspan="3">&nbsp;</td>';
			$recpt.='	<td align="right"><strong>'.$xxCntTax.':</strong></td>';
			$recpt.='	<td align="right">'.FormatEuroCurrency($rs['ordCountryTax']).'</td>';
			$recpt.='  </tr>'.$emailcr;
		}
		$recpt.='	  <tr>';
		$recpt.='		<td colspan="3">&nbsp;</td>';
		$recpt.='		<td class="cobhl receipthl" align="right"><strong>'.$xxGndTot.':</strong></td>';
		$recpt.='		<td class="cobhl receipthl" align="right">'.FormatEuroCurrency($ordGrandTotal).'</td>';
		$recpt.='	  </tr>'.$emailcr;
		$recpt.='	  <tr>';
		$recpt.='		<td align="center" colspan="5">&nbsp;</td>';
		$recpt.='	  </tr>';
	}
	$recpt.='	</table>'.$emailcr;
	return($recpt);
}
function getrecpt($oid){
	global $xxAddress,$xxName,$xxOrdId,$xxBilAdd,$xxShpAdd,$xxPhone,$xxEmail,$xxShpMet,$xxWtIns,$xxNoWtIn,$xxCerCLo,$xxSatDeR,$xxAddInf,$xxCODets,$xxCOName,$xxCOUPri,$xxQuant,$xxTotal,$xxSubTot,$xxDscnts,$xxShipHa,$xxFree,$xxShippg,$xxHndlg,$xxStaTax,$xxHST,$xxCntTax,$xxGndTot,$ordGrandTotal;
	global $extraorderfield1,$extraorderfield2,$extracheckoutfield1,$extracheckoutfield2,$combineshippinghandling,$hideoptpricediffs,$digidownloads,$willpickuptext,$emailcr,$loyaltypoints,$xxGWrSel;
	$recpt='';
	$sSQL="SELECT ordID,ordName,ordLastName,ordAddress,ordAddress2,ordCity,ordState,ordZip,ordCountry,ordEmail,ordPhone,ordShipName,ordShipLastName,ordShipAddress,ordShipAddress2,ordShipCity,ordShipState,ordShipZip,ordShipCountry,ordShipPhone,ordPayProvider,ordAuthNumber,ordTotal,ordDate,ordStateTax,ordCountryTax,ordHSTTax,ordHandling,ordShipping,ordAffiliate,ordShipType,ordShipCarrier,ordDiscount,ordDiscountText,ordComLoc,ordExtra1,ordExtra2,ordShipExtra1,ordShipExtra2,ordCheckoutExtra1,ordCheckoutExtra2,ordSessionID,payProvID,ordAddInfo FROM orders INNER JOIN payprovider ON payprovider.payProvID=orders.ordPayProvider WHERE ordAuthNumber<>'' AND ordID='".escape_string($oid)."'";
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		$hasshipaddress=(trim_($rs['ordShipAddress'])!='');
		// START : addressess {
		$recpt.='<div class="receiptaddresses">';
		// START : receiptbillingaddress {
		$recpt.='		<div class="receiptaddress receiptbillingaddress">';
		$recpt.='		  <div class="receiptsectionhead">' . $xxBilAdd . '</div>';
		if(trim_(@$extraorderfield1)!='' && trim_($rs['ordExtra1'])!='')
			$recpt.='		  <div class="receiptcontainer rcontextra1"><div class="receiptleft">' . $extraorderfield1 . '</div><div class="receiptright">' . $rs['ordExtra1'] . '</div></div>';
		$recpt.='		  <div class="receiptcontainer rcontname"><div class="receiptleft">' . $xxName . '</div><div class="receiptright">' . trim_($rs['ordName'] . ' ' . $rs['ordLastName']) . '</div></div>';
		$recpt.='		  <div class="receiptcontainer rcontaddress"><div class="receiptleft">' . $xxAddress . '</div><div class="receiptright">';
			$recpt.='<div>' . $rs['ordAddress'] . '</div>';
			if(trim_($rs['ordAddress2'])!='') $recpt.='<div>' . $rs['ordAddress2'] . '</div>';
			$recpt.='<div>' . $rs['ordCity'] . ', ' . $rs['ordState'] . '</div>';
			$recpt.='<div>' . $rs['ordZip'] . '</div>';
			$recpt.='<div>' . $rs['ordCountry'] . '</div>';
		$recpt.='		  </div></div>';
		$recpt.='		  <div class="receiptcontainer rcontphone"><div class="receiptleft">' . $xxPhone . '</div><div class="receiptright">' . $rs['ordPhone'] . '</div></div>';
		if(trim_(@$extraorderfield2)!='' && trim_($rs['ordExtra2'])!='')
			$recpt.='		  <div class="receiptcontainer rcontextra2"><div class="receiptleft">' . $extraorderfield2 . '</div><div class="receiptright">' . $rs['ordExtra2'] . '</div></div>';
		$recpt.='</div>';
		// END : receiptbillingaddress }
		
		if($hasshipaddress){
			// START : receiptshippingaddress {
			$recpt.='<div class="receiptaddress receiptshippingaddress">';
			$recpt.='		  <div class="receiptsectionhead">' . $xxShpAdd . '</div>';
			if(trim_(@$extraorderfield1)!='' && trim_($rs['ordShipExtra1'])!='')
				$recpt.='		  <div class="receiptcontainer rcontextra1"><div class="receiptleft">' . $extraorderfield1 . '</div><div class="receiptright">' . $rs['ordShipExtra1'] . '</div></div>';
			$recpt.='		  <div class="receiptcontainer rcontname"><div class="receiptleft">' . $xxName . '</div><div class="receiptright">' . trim_($rs['ordShipName'] . ' ' . $rs['ordShipLastName']) . '</div></div>';
			$recpt.='		  <div class="receiptcontainer rcontaddress"><div class="receiptleft">' . $xxAddress . '</div><div class="receiptright">';
			$recpt.='<div>' . $rs['ordShipAddress'] . '</div>';
			if(trim_($rs['ordShipAddress2'])!='') $recpt.='<div>' . $rs['ordShipAddress2'] . '</div>';
			$recpt.='<div>' . $rs['ordShipCity'] . ', ' . $rs['ordShipState'] . '</div>';
			$recpt.='<div>' . $rs['ordShipZip'] . '</div>';
			$recpt.='<div>' . $rs['ordShipCountry'] . '</div>';
			$recpt.='	  </div></div>';
			$recpt.='		  <div class="receiptcontainer rcontphone"><div class="receiptleft">' . $xxPhone . '</div><div class="receiptright">' . $rs['ordShipPhone'] . '</div></div>';
			if(trim_(@$extraorderfield2)!='' && trim_($rs['ordShipExtra2'])!='')
				$recpt.='		  <div class="receiptcontainer rcontextra2"><div class="receiptleft">' . $extraorderfield2 . '</div><div class="receiptright">' . $rs['ordShipExtra2'] . '</div></div>';
			$recpt.='</div>';
			// END : receiptshippingaddress }
		}
		$recpt.='	</div>' . "\r\n";
		// END : addressess }

		// START : receiptextra {
		$recpt.='		<div class="receiptextra">';
		$recpt.='		  <div class="receiptcontainer rcontorderid"><div class="receiptleft">' . $xxOrdId . '</div><div class="receiptright">' . $rs['ordID'] . '</div></div>';
		$recpt.='		  <div class="receiptcontainer rcontemail"><div class="receiptleft">' . $xxEmail . '</div><div class="receiptright">' . $rs['ordEmail'] . '</div></div>';

		$ordShipType=$rs['ordShipType'];
		if($ordShipType!=''){
			$shiptext='		  <div class="receiptcontainer rcontshipmethod"><div class="receiptleft">' . $xxShpMet . '</div><div class="receiptright"><div>' . $ordShipType . '</div>';
			if(@$willpickuptext!=$ordShipType){
				if(($rs['ordComLoc'] & 2)==2) $shiptext.='<div>' . $xxWtIns . '</div>'; elseif(@$GLOBALS['forceinsuranceselection']) $shiptext.='<div>' . $xxNoWtIn . '</div>';
			}
			if(($rs['ordComLoc'] & 1)==1) $shiptext.='<div>' . $xxCerCLo . '</div>';
			if(($rs['ordComLoc'] & 4)==4) $shiptext.='<div>' . $xxSatDeR . '</div>';
			$shiptext.='</div></div>' . "\r\n";
		}else
			$shiptext='';
		$recpt.=$shiptext;
		if(trim_(@$extracheckoutfield1)!='' && trim_($rs['ordCheckoutExtra1'])!='')
			$recpt.='		  <div class="receiptcontainer rcontextracheckout1"><div class="receiptleft">' . $extracheckoutfield1 . '</div><div class="receiptright">' . $rs['ordCheckoutExtra1'] . '</div></div>' . "\r\n";
		if(trim_(@$extracheckoutfield2)!='' && trim_($rs['ordCheckoutExtra2'])!='')
			$recpt.='		  <div class="receiptcontainer rcontextracheckout2"><div class="receiptleft">' . $extracheckoutfield2 . '</div><div class="receiptright">' . $rs['ordCheckoutExtra2'] . '</div></div>' . "\r\n";
		if(@$loyaltypoints!='') $recpt.='<!--%loyaltypointplaceholder%-->';
		$ordAddInfo=trim_($rs['ordAddInfo']);
		if($ordAddInfo!='')
			$recpt.='		  <div class="receiptcontainer rcontaddinfo"><div class="receiptleft">' . $xxAddInf . '</div><div class="receiptright">'.str_replace(array("\r","\n"),array('','<br />'),$ordAddInfo).'</div></div>' . "\r\n";
		$recpt.='<!--%digidownloadplaceholder%-->';
		$recpt.='	</div>' . "\r\n";
		// END : receiptextra }
		
		$recpt.='<!--%digidownloaditems%-->';
		$recpt.='<div class="receiptlist">' .
					'	<div class="receiptheadrow">';
		$recpt.='		<div class="receiptprodid">' . $xxCODets . '</div>';
		$recpt.='		<div class="receiptprodname">' . $xxCOName . '</div>';
		if(!@$GLOBALS['nopriceanywhere']) $recpt.='	<div class="receiptunitprice">' . $xxCOUPri . '</div>';
		$recpt.='		<div class="receiptquantity">' . $xxQuant . '</div>';
		if(!@$GLOBALS['nopriceanywhere']) $recpt.='	<div class="receipttotal">' . $xxTotal . '</div>';
		$recpt.='  </div>' . "\r\n";
	}
	ect_free_result($result);
	$sSQL="SELECT cartID,cartProdID,cartProdName,cartProdPrice,cartQuantity,cartGiftWrap,pUpload FROM cart LEFT JOIN products ON cart.cartProdID=products.pID WHERE cartOrderID='" . escape_string($oid) . "' ORDER BY cartID";
	$result=ect_query($sSQL) or ect_error();
	while($alldata=ect_fetch_assoc($result)){
		$theoptions='';
		$theoptionspricediff=0;
		$isoutofstock=FALSE;
		$sSQL='SELECT coID,coOptGroup,coCartOption,coPriceDiff,coWeightDiff,optAltImage FROM cartoptions LEFT JOIN options ON cartoptions.coOptID=options.optID WHERE coCartID='.$alldata['cartID'].' ORDER BY coID';
		$opts=ect_query($sSQL) or ect_error();
		while($rs2=ect_fetch_assoc($opts)){
			$theoptionspricediff+=$rs2['coPriceDiff'];
			$theoptions.='<div class="receiptlistrow receiptoptionrow">';
			$theoptions.='<div class="receiptoption receiptoptgroup">'.$rs2['coOptGroup'].'</div>';
			$theoptions.='<div class="receiptoption receiptoptname">' . (strpos($rs2['coCartOption'],"\n")===FALSE?'&nbsp;- ':'') . str_replace(array("\r","\n",$emailcr),array('','<br />','<br />'),strip_tags($rs2['coCartOption'])) . '</div>';
			if(!@$GLOBALS['nopriceanywhere']) $theoptions.='<div class="receiptoption receiptoptunitprice">' . ($rs2['coPriceDiff']==0 || @$hideoptpricediffs ? '- ' : FormatEuroCurrency($rs2['coPriceDiff'])) . '</div>';
			$theoptions.='<div class="receiptoption receiptoptquantity">&nbsp;</div>';
			if(!@$GLOBALS['nopriceanywhere']) $theoptions.='<div class="receiptoption receiptopttotal">' . ($rs2['coPriceDiff']==0 || @$hideoptpricediffs ? '- ' : FormatEuroCurrency($rs2['coPriceDiff']*$alldata['cartQuantity'])) . '</div>';
			$theoptions.='</div>' . "\r\n";
		}
		ect_free_result($opts);
		$recpt.='  <div class="receiptlistrow receiptitemrow">';
		$recpt.='		<div class="receiptprodid">';
		$thankspageimage='';
		if(@$GLOBALS['imgonthankspage']){
			$sSQL="SELECT imageSrc FROM productimages WHERE imageProduct='" . escape_string($alldata['cartProdID']) . "' AND (imageType=0 OR imageType=1) ORDER BY imageType,imageNumber";
			$imgresult=ect_query($sSQL) or ect_error();
			$thankspageimage=@$GLOBALS['defaultthankspageimage'];
			if($rs2=ect_fetch_assoc($imgresult)) $thankspageimage=$rs2['imageSrc'];
			ect_free_result($imgresult);
			if($thankspageimage!='') $recpt.='<div class="thankspageimg"><img class="thankspageimg" src="' . $thankspageimage . '" alt=""><div>';
		}
		$recpt.=$alldata['cartProdID'] . '</div>';
		if($thankspageimage!='') $recpt.='</div></div>';
		$recpt.='		<div class="receiptprodname">'.$alldata['cartProdName'] . ($alldata['cartGiftWrap']!=0?'<div class="giftwrap">' . $xxGWrSel . '</div>':'');
			$sSQL="SELECT productpackages.pID,quantity,pName,quantity FROM productpackages INNER JOIN products on productpackages.pID=products.pID WHERE packageID='" . escape_string($alldata['cartProdID']) . "'";
			$opts=ect_query($sSQL) or ect_error();
			if(ect_num_rows($opts)>0){
				$recpt.='<div class="receiptpackage">';
				while($rs2=ect_fetch_assoc($opts)){
					$recpt.='<div class="receiptpackagerow"><div class="ectleft">' . $rs2['pID'] . '</div><div class="ectright">' . $rs2['pName'] . '</div><div>' . $rs2['quantity'] . '</div></div>';
				}
				$recpt.='</div>';
			}
			ect_free_result($opts);
			if($alldata['pUpload']) $GLOBALS['hasimageupload']=TRUE;
		$recpt.='</div>';
		if(!@$GLOBALS['nopriceanywhere']) $recpt.='<div class="receiptunitprice">'.(@$hideoptpricediffs ? FormatEuroCurrency($alldata['cartProdPrice'] + $theoptionspricediff) : FormatEuroCurrency($alldata['cartProdPrice'])).'</div>';
		$recpt.='		<div class="receiptquantity">' . $alldata['cartQuantity'] . '</div>';
		if(!@$GLOBALS['nopriceanywhere']) $recpt.='<div class="receipttotal">'.(@$hideoptpricediffs ? FormatEuroCurrency(($alldata['cartProdPrice'] + $theoptionspricediff)*$alldata['cartQuantity']) : FormatEuroCurrency($alldata['cartProdPrice']*$alldata['cartQuantity'])).'</div>';
		$recpt.="  </div>\r\n";
		$recpt.=$theoptions;
	}
	$recpt.="  </div>\r\n";
	if(@$GLOBALS['hasimageupload']) $recpt.='<div id="imageuploadbutton" class="imageuploadbutton no-print"' . (! @$GLOBALS['imageuploadbybutton']?' style="display:none"':'') . '><button class="ectbutton" onclick="document.getElementById(\'imageuploadbutton\').style.display=\'none\';document.getElementById(\'imageuploadopdiv\').style.display=\'\';return false">' . $GLOBALS['xxImgUpl'] . '</button></div>';
	if(!@$GLOBALS['nopriceanywhere']){
		$recpt.='<div class="receipttotalscolumn">' .
					'<div class="receipttotalstable">';
		$recpt.='<div class="receipttotalsrow rectotsubtotal"><div class="ectleft">'.$xxSubTot.':</div><div class="ectright">'.FormatEuroCurrency($rs['ordTotal'])."</div></div>\r\n";
		if($rs['ordDiscount']>0)
			$recpt.='<div class="receipttotalsrow rectotdiscounts"><div class="ectleft">'.$xxDscnts.':</div><div class="ectright">'.FormatEuroCurrency($rs['ordDiscount'])."</div></div>\r\n";
		if($rs['ordShipCarrier']==0&&(($rs['ordShipping']+$rs['ordHandling'])==0)){
			// Do nothing
		}elseif(@$combineshippinghandling){
			$recpt.='<div class="receipttotalsrow rectotshiphand"><div class="ectleft">'.$xxShipHa.':</div><div class="ectright">'. (($rs['ordShipping']+$rs['ordHandling'])==0?'<p align="center"><span style="color:#FF0000;font-weight:bold">' . $xxFree . '</span></p>':FormatEuroCurrency($rs['ordShipping']+$rs['ordHandling']))."</div></div>\r\n";
		}else{
			if($rs['ordShipping']>0)
				$recpt.='<div class="receipttotalsrow rectotshipping"><div class="ectleft">'.$xxShippg.':</div><div class="ectright">'.FormatEuroCurrency($rs['ordShipping'])."</div></div>\r\n";
			if($rs['ordHandling']>0)
				$recpt.='<div class="receipttotalsrow rectothandling"><div class="ectleft">'.$xxHndlg.':</div><div class="ectright">'.FormatEuroCurrency($rs['ordHandling'])."</div></div>\r\n";
		}
		if($rs['ordStateTax']>0)
			$recpt.='<div class="receipttotalsrow rectotstatetax"><div class="ectleft">'.$xxStaTax.':</div><div class="ectright">'.FormatEuroCurrency($rs['ordStateTax'])."</div></div>\r\n";
		if($rs['ordHSTTax']>0)
			$recpt.='<div class="receipttotalsrow rectothsttax"><div class="ectleft">'.$xxHST.':</div><div class="ectright">'.FormatEuroCurrency($rs['ordHSTTax'])."</div></div>\r\n";
		if($rs['ordCountryTax']>0||@$GLOBALS['alwaysdisplaycountrytax'])
			$recpt.='<div class="receipttotalsrow rectotcountrytax"><div class="ectleft">'.$xxCntTax.':</div><div class="ectright">'.FormatEuroCurrency($rs['ordCountryTax'])."</div></div>\r\n";
		$recpt.='<div class="receipttotalsrow rectotgrandtotal"><div class="ectleft">'.$xxGndTot.':</div><div class="ectright">'.FormatEuroCurrency($ordGrandTotal).'</div></div>';
		$recpt.='</div>' .
			"</div>\r\n";
	}
	return($recpt);
}
function do_order_success($sorderid,$sEmail,$sendstoreemail,$doshowhtml,$sendcustemail,$sendaffilemail,$sendmanufemail){
	global $thereference,$emlNl,$htmlemails,$extraorderfield1,$extraorderfield2,$extraorderfield3,$shipType,$emailheader,$emailfooter,$emailencoding,$hideoptpricediffs,$xxWtIns,$xxNoWtIn,$ordGrandTotal,$ordID,$digidownloads,$dropshipheader,$digidownloademail,$xxPrint,$dropshipsubject,$xxHST,$encodecustomeremailsubject,$imgcontinueshopping,$imgprintversion,$giftcertificateid,$donationid,$dateformatstr,$recpt,$receiptheader,$xxCerCLo;
	global $xxHndlg,$xxDscnts,$xxOrdId,$xxCusDet,$xxEmail,$xxPhone,$xxShpDet,$xxShpMet,$xxAddInf,$xxPrId,$xxPrNm,$xxQuant,$xxUnitPr,$xxOrdTot,$xxStaTax,$xxCntTax,$xxShippg,$xxGndTot,$xxOrdStr,$xxTnxOrd,$xxTouSoo,$xxAff1,$xxAff2,$xxAff3,$xxThnks,$xxThkYou,$xxRecEml,$storeurl,$xxCntShp,$success,$ordAuthNumber,$orderText,$ordTotal,$digidownloadsecret,$useaddressline2,$combineshippinghandling,$xxShipHa,$extracheckoutfield1,$extracheckoutfield2;
	global $ordStateTax,$ordHSTTax,$ordCountryTax,$ordShipping,$ordHandling,$ordDiscount,$ordCity,$ordState,$ordCountry,$ordEmail,$affilID,$xxDigPro,$thankspagecontinue,$willpickuptext,$xxManRev,$emailcr,$loyaltypoints,$xxLoyPoi,$xxGWrSel,$xxGifMes,$xxSatDeR,$languageid;
	global $digidownloaddays,$digidownloadpath,$digidownloadpattern,$imgdownloadproducts,$digidownloadmethod,$warnexpireddownload;
	$success=TRUE;
	if(@$htmlemails==TRUE){
		$emlNl='<br />'.$emailcr;
		$xxThkYou='';
	}else
		$emlNl=$emailcr;
	$affilID='';
	$saveHeader='';
	if(! is_numeric($sorderid)){
		print '&nbsp;<br />&nbsp;<br />&nbsp;<br /><p align="center">Illegal Order ID</p><br />&nbsp;';
		return(FALSE);
	}
	$ordID=$sorderid;
	$hasdownload=FALSE;
	$orderloyaltypoints=0;
	$ordClientID=0;
	$ndropshippers=0;
	$savelangid=$languageid;
	$sSQL="SELECT ordID,ordName,ordLastName,ordAddress,ordAddress2,ordCity,ordState,ordZip,ordCountry,ordEmail,ordPhone,ordShipName,ordShipLastName,ordShipAddress,ordShipAddress2,ordShipCity,ordShipState,ordShipZip,ordShipCountry,ordShipPhone,ordPayProvider,ordAuthNumber,ordAuthStatus,ordTotal,ordDate,ordStateTax,ordCountryTax,ordHSTTax,ordHandling,ordShipping,ordAffiliate,ordDiscount,ordDiscountText,ordComLoc,ordExtra1,ordExtra2,ordShipExtra1,ordShipExtra2,ordCheckoutExtra1,ordCheckoutExtra2,ordSessionID,ordLang,ordAddInfo,ordShipType,payProvID,ordClientID,loyaltyPoints FROM orders LEFT JOIN payprovider ON payprovider.payProvID=orders.ordPayProvider WHERE ordAuthNumber<>'' AND ordID='" . escape_string($sorderid) . "'";
	$result=ect_query($sSQL) or ect_error();
	if(ect_num_rows($result) > 0){
		$rs=ect_fetch_assoc($result);
		$languageid=$rs['ordLang']+1;
		$orderloyaltypoints=$rs['loyaltyPoints'];
		$ordClientID=$rs['ordClientID'];
		$orderText='';
		$ordAuthNumber=$rs['ordAuthNumber'];
		$ordSessionID=$rs['ordSessionID'];
		$payprovid=$rs['payProvID'];
		$ordName=trim_($rs['ordName'] . ' ' . $rs['ordLastName']);
		$ordDate=$rs['ordDate'];
		$ordzip=$rs['ordZip'];
		$ordshipzip=$rs['ordShipZip'];
		if(time()-strtotime($ordDate)>(60*60*24*365) && ! (@$_SESSION['loggedon']!=''||@$_SESSION['clientID']===$rs['ordClientID'])){
			print '<div style="text-align:center;padding:50px">Please contact our customer services department for details of your order</div>';
			return TRUE;
		}
		$ordDateToTime=strtotime($ordDate);
		if($rs['ordShipType']=='MODWARNOPEN'){
			print '<div style="font-weight:bold;text-align:center">&nbsp;<br />&nbsp;<br />&nbsp;<br />' . $xxManRev . '&nbsp;<br />&nbsp;<br />&nbsp;<br />&nbsp;<br />';
			print imageorbutton(@$imgcontinueshopping,'&nbsp;'.$xxCntShp.'&nbsp;','continueshopping',(@$thankspagecontinue!=''?$thankspagecontinue:$storeurl),@$thankspagecontinue=='javascript:history.go(-1)'?TRUE:FALSE).'&nbsp;';
			print '</div>';
			$success=FALSE;
			ect_free_result($result);
			return;
		}
		$sSQL='SELECT '.getlangid('emailsubject',4096).','.getlangid('emailheaders',4096).','.getlangid('receiptheaders',4096).','.getlangid('dropshipsubject',4096).','.getlangid('dropshipheaders',4096).' FROM emailmessages WHERE emailID=1';
		$result2=ect_query($sSQL) or ect_error();
		if($rs2=ect_fetch_assoc($result2)){
			$emailsubject=trim_($rs2[getlangid('emailsubject',4096)]);
			$emailheader=trim_($rs2[getlangid('emailheaders',4096)]);
			$emailheader=str_replace('%emailmessage%','%messagebody%',$emailheader);
			$receiptheader=trim_($rs2[getlangid('receiptheaders',4096)]);
			if(strpos($emailheader, '%messagebody%')===FALSE) $emailheader.='%messagebody%';
			if(strpos($receiptheader, '%messagebody%')===FALSE) $receiptheader.='%messagebody%';
			$dropshipsubject=trim_($rs2[getlangid('dropshipsubject',4096)]);
			$dropshipheader=trim_($rs2[getlangid('dropshipheaders',4096)]);
			$dropshipheader=str_replace('%emailmessage%','%messagebody%',$dropshipheader);
			if(strpos($dropshipheader, '%messagebody%')===FALSE) $dropshipheader.='%messagebody%';
		}
		ect_free_result($result2);
		$sSQL='SELECT '.getlangid('pProvHeaders',4096).','.getlangid('pProvDropShipHeaders',4096).' FROM payprovider WHERE payProvID=' . $payprovid;
		$result2=ect_query($sSQL) or ect_error();
		if($rs2=ect_fetch_assoc($result2)){
			$payprovheader=trim_($rs2[getlangid('pProvHeaders',4096)]);
			$payprovheader=str_replace('%emailmessage%','%messagebody%',$payprovheader);
			if(strpos($payprovheader, '%messagebody%')===FALSE) $payprovheader.='%messagebody%';
			$payprovdropshipheader=trim_($rs2[getlangid('pProvDropShipHeaders',4096)]);
			$payprovdropshipheader=str_replace('%emailmessage%','%messagebody%',$payprovdropshipheader);
			if(strpos($payprovdropshipheader, '%messagebody%')===FALSE) $payprovdropshipheader.='%messagebody%';
		}
		ect_free_result($result2);
		$emailheader=str_replace('%messagebody%', $payprovheader, $emailheader);
		$dropshipheader=str_replace('%messagebody%', $payprovdropshipheader, $dropshipheader);
		$emailheader=str_replace('%nl%', '<br />', str_replace('%ordername%', $ordName, $emailheader));
		if(@$fordertimeformatstr!='') setlocale(LC_TIME, $adminLocale);
		$emailheader=str_replace('%orderdate%', (@$fordertimeformatstr!='' ? strftime($fordertimeformatstr, $ordDateToTime) : date($dateformatstr, $ordDateToTime) . ' ' . date('H:i', $ordDateToTime)), $emailheader);
		$receiptheader=str_replace('%nl%', '<br />', str_replace('%ordername%', $ordName, $receiptheader));
		$receiptheader=str_replace('%orderdate%', (@$fordertimeformatstr!='' ? strftime($fordertimeformatstr, $ordDateToTime) : date($dateformatstr, $ordDateToTime) . ' ' . date('H:i', $ordDateToTime)), $receiptheader);
		$dropshipheader=str_replace('%nl%', '<br />', str_replace('%ordername%', $ordName, $dropshipheader));
		$dropshipheader=str_replace('%orderdate%', (@$fordertimeformatstr!='' ? strftime($fordertimeformatstr, $ordDateToTime) : date($dateformatstr, $ordDateToTime) . ' ' . date('H:i', $ordDateToTime)), $dropshipheader);

		$orderText.=$xxOrdId . ': ' . $rs['ordID'] . '<br />';
		if($thereference!='') $orderText.='Transaction Ref' . ': ' . $thereference . '<br />';
		$orderText.=$xxCusDet . ': ' . '<br />';
		if(trim_(@$extraorderfield1)!='') $orderText.=$extraorderfield1 . ': ' . $rs['ordExtra1'] . '<br />';
		$orderText.=$ordName . '<br />';
		$orderText.=$rs['ordAddress'] . '<br />';
		if(trim_($rs['ordAddress2'])!='') $orderText.=$rs['ordAddress2'] . '<br />';
		$orderText.=$rs['ordCity'] . ', ' . $rs['ordState'] . '<br />';
		$orderText.=$rs['ordZip'] . '<br />';
		$orderText.=$rs['ordCountry'] . '<br />';
		$orderText.=$xxEmail . ': ' . $rs['ordEmail'] . '<br />';
		$custEmail=$rs['ordEmail'];
		$orderText.=$xxPhone . ': ' . $rs['ordPhone'] . '<br />';
		if(trim_(@$extraorderfield2)!='') $orderText.=$extraorderfield2 . ': ' . $rs['ordExtra2'] . '<br />';
		if(trim_($rs['ordShipName'])!='' || trim_($rs['ordShipLastName'])!='' || trim_($rs['ordShipAddress'])!=''){
			$orderText.=$xxShpDet . ': ' . '<br />';
			if(trim_(@$extraorderfield1)!='' && trim_($rs['ordShipExtra1'])!='') $orderText.=$extraorderfield1 . ': ' . $rs['ordShipExtra1'] . '<br />';
			$orderText.=$rs['ordShipName'] . ($rs['ordShipName']!='' && $rs['ordShipLastName']!='' ? ' ' : '') . $rs['ordShipLastName'] . '<br />';
			$orderText.=$rs['ordShipAddress'] . '<br />';
			if(trim_($rs['ordShipAddress2'])!='') $orderText.=$rs['ordShipAddress2'] . '<br />';
			$orderText.=$rs['ordShipCity'] . ', ' . $rs['ordShipState'] . '<br />';
			$orderText.=$rs['ordShipZip'] . '<br />';
			$orderText.=$rs['ordShipCountry'] . '<br />';
			if(trim_($rs['ordShipPhone']!='')) $orderText.=$xxPhone . ': ' . $rs['ordShipPhone'] . '<br />';
			if(trim_(@$extraorderfield2)!='' && trim_($rs['ordShipExtra2'])!='') $orderText.=$extraorderfield2 . ': ' . $rs['ordShipExtra2'] . '<br />';
		}
		$ordShipType=$rs['ordShipType'];
		if($ordShipType!=''){
			$orderText.='<br />' . $xxShpMet . ': ' . $ordShipType;
			if(@$willpickuptext!=$ordShipType){
				if(($rs['ordComLoc'] & 2)==2) $orderText.=$xxWtIns; elseif(@$GLOBALS['forceinsuranceselection']) $orderText.=$xxNoWtIn;
			}
			$orderText.='<br />';
			if(($rs['ordComLoc'] & 1)==1) $orderText.=$xxCerCLo . '<br />';
			if(($rs['ordComLoc'] & 4)==4) $orderText.=$xxSatDeR . '<br />';
		}
		if(trim_(@$extracheckoutfield1)!='' && trim_($rs['ordCheckoutExtra1'])!='') $orderText.=$extracheckoutfield1 . ': ' . $rs['ordCheckoutExtra1'] . '<br />';
		if(trim_(@$extracheckoutfield2)!='' && trim_($rs['ordCheckoutExtra2'])!='') $orderText.=$extracheckoutfield2 . ': ' . $rs['ordCheckoutExtra2'] . '<br />';
		$ordAddInfo=trim_($rs['ordAddInfo']);
		if($ordAddInfo!=''){
			$orderText.='<br />' . $xxAddInf . ': ' . '<br />';
			$orderText.=str_replace(array("\r","\n"),array('','<br />'),$ordAddInfo) . '<br />';
		}
		$ordTotal=$rs['ordTotal'];
		$ordStateTax=$rs['ordStateTax'];
		$ordDiscount=$rs['ordDiscount'];
		$ordDiscountText=$rs['ordDiscountText'];
		$ordCountryTax=$rs['ordCountryTax'];
		$ordHSTTax=$rs['ordHSTTax'];
		$ordShipping=$rs['ordShipping'];
		$ordHandling=$rs['ordHandling'];
		$affilID=trim_($rs['ordAffiliate']);
		$ordAddress=$rs['ordAddress'];
		$ordShipAddress=$rs['ordShipAddress'];
		$ordCity=$rs['ordCity'];
		$ordShipCity=$rs['ordShipCity'];
		$ordState=$rs['ordState'];
		$ordShipState=$rs['ordShipState'];
		$ordCountry=$rs['ordCountry'];
		$ordShipCountry=$rs['ordShipCountry'];
		$ordEmail=$rs['ordEmail'];
		if(FALSE && $sendcustemail&&!@$GLOBALS['isresendemail']){
			$firsttime=TRUE;
			$ordGrandTotal=($ordTotal+$ordStateTax+$ordCountryTax+$ordHSTTax+$ordShipping+$ordHandling)-$ordDiscount;
			$sSQL='SELECT dnID,dnLastUpdated FROM devicenotifications';
			$result2=ect_query($sSQL) or ect_error();
			while($rs2=ect_fetch_assoc($result2)){
				$badgecount=0;
				$sSQL="SELECT COUNT(*) AS tcnt FROM orders WHERE ordDate>'" . $rs2['dnLastUpdated'] . "'";
				$result3=ect_query($sSQL) or ect_error();
				if($rs3=ect_fetch_assoc($result3)){
					if(is_null($badgecount)) $badgecount=0; else $badgecount=$rs3['tcnt'];
				}
				if(callcurlfunction('https://www.ecommercetemplates.com/applesalealert.asp?id=' . $rs2['dnID'] . '&badges=' . $badgecount . '&store=' . urlencode($GLOBALS['storeurl']) . '&amount=' . urlencode(FormatEuroCurrency($ordGrandTotal)),'user=' . urlencode($GLOBALS['currConvUser']) . '&pass=' . urlencode($GLOBALS['currConvPw']),$sresult,"",$errormsg,12)){
					if(trim_($sresult)!='' && $firsttime) notification_err_msg($sresult);
				}elseif($firsttime)
					notification_err_msg($errormsg);
				$firsttime=FALSE;
			}
			ect_free_result($result2);
		}
	}else{
		$sendstoreemail=FALSE;
		$sendcustemail=FALSE;
		$sendaffilemail=FALSE;
		$sendmanufemail=FALSE;
		print '<div style="padding:40px;text-align:center">Cannot find details for order id: ' . $sorderid . '</div>';
		return(FALSE);
	}
	ect_free_result($result);
	$saveCustomerDetails=$orderText;
	if(@$loyaltypoints!='') $orderText.='%loyaltypointplaceholder%';
	$orderText.='%digidownloadplaceholder%';
	$reviewlinks=$reviewlinkshtml='';
	$loyaltypointtotal=0;
	if(@$GLOBALS['fromorderstatus']||@$GLOBALS['fromajaxservice']||@$GLOBALS['isresendemail']||!$sendcustemail)$GLOBALS['avalarastate']=0;
	if(@$GLOBALS['avalarastate']!=0){
		if($ordshipzip!=''){
			$destaddress=$ordShipAddress;
			$destcity=$ordShipCity;
			$deststate=$ordShipState;
			$shipcountry=$ordShipCountry;
			$destzip=$ordshipzip;
		}else{
			$destaddress=$ordAddress;
			$destcity=$ordCity;
			$deststate=$ordState;
			$shipcountry=$ordCountry;
			$destzip=$ordzip;
		}
		$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'];
			$shipCountryID=$rs['countryID'];
			$shipCountryCode=$rs['countryCode'];
		}
		$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":{
					"line1":' . json_encode($destaddress) . ',
					"city":' . json_encode($destcity) . ',
					"region":' . json_encode($deststate) . ',
					"country":' . json_encode($shipCountryCode) . ',
					"postalCode":' . json_encode($destzip) . '}
			  },"lines": [';
	}
	$addcomma='';
	$numtaxableitems=0;
	$sSQL='SELECT cartProdId,cartOrigProdId,cartProdName,cartProdPrice,cartQuantity,cartID,cartGiftWrap,pDropship,pDisplay,pStaticPage,'.getaltlang('pStaticURL',8388608).",pSKU,pDownload,cartGiftMessage,pTaxCode,pExemptions FROM cart LEFT JOIN products ON cart.cartProdId=products.pID WHERE cartOrderID='" . escape_string($sorderid) . "' ORDER BY cartID";
	$result=ect_query($sSQL) or ect_error();
	if(ect_num_rows($result) > 0){
		while($rs=ect_fetch_assoc($result)){
			if(($rs['cartProdId']==$giftcertificateid || $rs['cartProdId']==$donationid) && is_null($rs['pExemptions'])) $rs['pExemptions']=15;
			if($rs['cartProdId']==$giftcertificateid){
				$sSQL='UPDATE giftcertificate SET gcAuthorized=1,gcOrigAmount='.$rs['cartProdPrice'].',gcRemaining='.$rs['cartProdPrice'].' WHERE gcCartID=' . $rs['cartID'];
				ect_query($sSQL) or ect_error();
				if($sendcustemail){
					$sSQL='SELECT '.getlangid('giftcertsubject',4096).','.getlangid('giftcertemail',4096).','.getlangid('giftcertsendersubject',4096).','.getlangid('giftcertsender',4096).' FROM emailmessages WHERE emailID=1';
					$result2=ect_query($sSQL) or ect_error();
					if($rs2=ect_fetch_assoc($result2)){
						$giftcertsubject=trim_($rs2[getlangid('giftcertsubject',4096)]);
						$emailBody=trim_($rs2[getlangid('giftcertemail',4096)]);
						$senderSubject=trim_($rs2[getlangid('giftcertsendersubject',4096)]);
						$senderBody=trim_($rs2[getlangid('giftcertsender',4096)]);
					}
					ect_free_result($result2);
					$sSQL='SELECT gcID,gcTo,gcFrom,gcEmail,gcMessage FROM giftcertificate WHERE gcCartID='.$rs['cartID'];
					$result2=ect_query($sSQL) or ect_error();
					if($rs2=ect_fetch_assoc($result2)){
						$emailBody=str_replace('%toname%', $rs2['gcTo'], $emailBody);
						$emailBody=str_replace('%fromname%', $rs2['gcFrom'], $emailBody);
						$emailBody=str_replace('%value%', FormatEmailEuroCurrency($rs['cartProdPrice']), $emailBody);
						$emailBody=replaceemailtxt($emailBody, '%message%', trim_($rs2['gcMessage']), $replaceone);
						$emailBody=str_replace('%storeurl%', $storeurl, $emailBody);
						$emailBody=str_replace('%certificateid%', $rs2['gcID'], $emailBody);
						$emailBody=str_replace('<br />', $emlNl, $emailBody);
						dosendemail($rs2['gcEmail'], $sEmail, '', str_replace('%fromname%', $rs2['gcFrom'], $giftcertsubject), $emailBody);
						$senderBody=str_replace('%toname%', $rs2['gcTo'], $senderBody);
						dosendemail($custEmail, $sEmail, '', str_replace('%toname%', $rs2['gcTo'], $senderSubject), $senderBody . $emlNl . $emailBody);
					}
					ect_free_result($result2);
				}
			}
			$reviewprodid=$rs['cartProdId'];
			$reviewisstatic=$rs['pStaticPage'];
			$reviewstaticurl=$rs['pStaticURL'];
			$reviewprodname=$rs['cartProdName'];
			if(trim_($rs['cartOrigProdId'])!=''){
				$sSQL="SELECT pName,pStaticPage,pStaticURL FROM products WHERE pID='".escape_string($rs['cartOrigProdId'])."'";
				$result2=ect_query($sSQL) or ect_error();
				if($rs2=ect_fetch_assoc($result2)){
					$reviewprodid=$rs['cartOrigProdId'];
					$reviewisstatic=$rs2['pStaticPage'];
					$reviewstaticurl=$rs2['pStaticURL'];
					$reviewprodname=$rs2['pName'];
				}
				ect_free_result($result2);
			}
			if(!is_null($reviewisstatic)){
				$thelink=(@$GLOBALS['seodetailurls'] ? stripUrlPath($storeurl) : $storeurl) . getdetailsurl($reviewprodid,$reviewisstatic,$reviewprodname,$reviewstaticurl,'review=true','');
				$thelinkhtml='<a href="' . $thelink . '">' . htmlspecials($GLOBALS['xxClkRep'] . $reviewprodname) . '</a>';
				$reviewlinks.=($htmlemails?$thelinkhtml:str_replace('&amp;','&',$thelink)) . $emlNl;
				$reviewlinkshtml.=$thelinkhtml . '<br>';
			}
			$localhasdownload=FALSE;
			if(trim_($rs['pDownload'])!='') $localhasdownload=TRUE;
			$saveCartItems='--------------------------' . '<br />';
			$saveCartItems.=$xxPrId . ': ' . $rs['cartProdId'] . '<br />';
			$saveCartItems.=$xxPrNm . ': ' . $rs['cartProdName'] . '<br />';
			$saveCartItems.=$xxQuant . ': ' . $rs['cartQuantity'] . '<br />';
			if($rs['cartGiftWrap']!=0){
				$saveCartItems.=$xxGWrSel . '<br />';
				if($rs['cartGiftMessage']!='')
					$saveCartItems.=$xxGifMes . ': ' . $rs['cartGiftMessage'] . '<br />';
			}
			$orderText.=$saveCartItems;
			$theoptions='';
			$theoptionspricediff=0;
			$sSQL='SELECT coOptGroup,coCartOption,coPriceDiff,optRegExp FROM cartoptions LEFT JOIN options ON cartoptions.coOptID=options.optID WHERE coCartID=' . $rs['cartID'] . ' ORDER BY coID';
			$result2=ect_query($sSQL) or ect_error();
			while($rs2=ect_fetch_assoc($result2)){
				$theoptionspricediff+=$rs2['coPriceDiff'];
				$optionline=(@$htmlemails==true?'&nbsp;&nbsp;&nbsp;&nbsp;>&nbsp;':'> > > ') . $rs2['coOptGroup'] . ' : ' . str_replace(array("\r\n",$emailcr),array('<br />','<br />'),$rs2['coCartOption']);
				$theoptions.=$optionline;
				$saveCartItems.=$optionline . '<br />';
				if($rs2['coPriceDiff']==0 || @$hideoptpricediffs==TRUE || @$GLOBALS['nopriceanywhere'])
					$theoptions.='<br />';
				else{
					$theoptions.=' (';
					if($rs2['coPriceDiff'] > 0) $theoptions.='+';
					$theoptions.=FormatEmailEuroCurrency($rs2['coPriceDiff']) . ')' . '<br />';
				}
				if($rs2['optRegExp']=='!!') $localhasdownload=FALSE;
			}
			if(!@$GLOBALS['nopriceanywhere']) $orderText.=$xxUnitPr . ': ' . (@$hideoptpricediffs==TRUE ? FormatEmailEuroCurrency($rs['cartProdPrice'] + $theoptionspricediff) : FormatEmailEuroCurrency($rs['cartProdPrice'])) . '<br />';
			$orderText.=$theoptions;
			if($rs['pDropship'] != 0){
				$index=0;
				for($index=0; $index<$ndropshippers; $index++){
					if($dropShippers[$index][0]==$rs['pDropship']) break;
				}
				if($index>=$ndropshippers){
					$ndropshippers=$index+1;
					$dropShippers[$index][1]='';
				}
				$dropShippers[$index][0]=$rs['pDropship'];
				$dropShippers[$index][1].=$saveCartItems . ($rs['pSKU']!=''?'SKU:'.$rs['pSKU'].'<br />':'');
			}
			if($localhasdownload==TRUE) $hasdownload=TRUE;
			ect_free_result($result2);

			if(($rs['pExemptions']&1)!=1){
				if(@$GLOBALS['avalarastate']!=0){
					$avalarajson.=$addcomma.'{"quantity":'.$rs['cartQuantity'].',
						  "amount":'.(($rs['cartProdPrice']+$theoptionspricediff)*$rs['cartQuantity']).',
						  ' . (trim_($rs['pTaxCode'])!=''?'"taxCode":"' . $rs['pTaxCode'] . '",':'') . ($ordDiscount>0?'"discounted":"true",':'') . '
						  "itemCode":"'.$rs['cartProdId'].'","description":'.json_encode($rs['cartProdName']).'}';
					$addcomma=',';
				}
				$numtaxableitems++;
			}
		}
		if($numtaxableitems==0||((int)@$_SESSION["clientActions"] & 1)==1) $GLOBALS['avalarastate']=0;
		$orderText.='--------------------------' . '<br />';
		if(!@$GLOBALS['nopriceanywhere']){
			$orderText.=$xxOrdTot . ' : ' . FormatEmailEuroCurrency($ordTotal) . '<br />';
			if(@$combineshippinghandling==TRUE){
				$orderText.=$xxShipHa . ' : ' . FormatEmailEuroCurrency($ordShipping+$ordHandling) . '<br />';
			}else{
				if($shipType != 0) $orderText.=$xxShippg . ' : ' . FormatEmailEuroCurrency($ordShipping) . '<br />';
				if((float)$ordHandling!=0.0) $orderText.=$xxHndlg . ' : ' . FormatEmailEuroCurrency($ordHandling) . '<br />';
			}
			if((float)$ordDiscount!=0.0) $orderText.=$xxDscnts . ' : ' . FormatEmailEuroCurrency($ordDiscount) . '<br />';
			if((float)$ordStateTax!=0.0) $orderText.=$xxStaTax . ' : ' . FormatEmailEuroCurrency($ordStateTax) . '<br />';
			if((float)$ordCountryTax!=0.0) $orderText.=$xxCntTax . ' : ' . FormatEmailEuroCurrency($ordCountryTax) . '<br />';
			if((float)$ordHSTTax!=0.0) $orderText.=$xxHST . ' : ' . FormatEmailEuroCurrency($ordHSTTax) . '<br />';
			$ordGrandTotal=($ordTotal+$ordStateTax+$ordCountryTax+$ordHSTTax+$ordShipping+$ordHandling)-$ordDiscount;
			$orderText.=$xxGndTot . ' : ' . FormatEmailEuroCurrency($ordGrandTotal) . '<br />';
		}
	}else{
		print '<div style="margin:50px;text-align:center">Cannot find details for cart id: ' . $sorderid . '</div>';
		return(FALSE);
	}
	ect_free_result($result);

	if(@$GLOBALS['avalarastate']!=0){
		if(@$GLOBALS['taxShipping']>0 && ($ordShipping>0)){
			$avalarajson.=',{"quantity":1,"amount":'.($ordShipping).',"taxCode":' . json_encode(@$GLOBALS['avalarafreightcode']!=''?$GLOBALS['avalarafreightcode']:'FR020100') . ',"itemCode":"freight","description":'.json_encode('Shipping').'}';
		}
		if(@$GLOBALS['taxHandling']>0 && $ordHandling>0){
			$avalarajson.=',{"quantity":1,"amount":'.($ordHandling).',"taxCode":' . json_encode(@$GLOBALS['avalarahandlingcode']!=''?$GLOBALS['avalarahandlingcode']:'OH010000') . ',"itemCode":"handling","description":'.json_encode('Handling').'}';
		}
		$avalarajson.='],' . ($ordDiscount>0 ? '"discount":' . $ordDiscount . ',' : '') . '
			"type":"Sales' . ($GLOBALS['avalarastate']<0?'Order':'Invoice') . '",
			"date":"' . date("Y-m-d\TH:i:s+00:00",time()+($GLOBALS['dateadjust']*60*60)) . '","code":' . json_encode($sorderid) . ',
			"customerCode":' . json_encode($ordEmail) . ',"purchaseOrderNo":"' . $sorderid . '","commit":true,
			' . (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)){
			$jsarray=json_decode($jres);
			$stateTax=@$jsarray->{'totalTax'};
			$countryTax=0;
		}
		//print $avalarajson . "<hr>" . $jres . "<br>";
	}
	if(@$loyaltypoints!='' && $orderloyaltypoints==0 && $sendmanufemail){
		$loyaltypointtotal=(int)(($ordTotal-$ordDiscount)*$loyaltypoints);
		if($loyaltypointtotal>0){
			if(($payprovid==4 || $payprovid==17) && @$GLOBALS['loyaltypointnoemail'])
				$loyaltypointtotal=0;
			elseif(@$GLOBALS['loyaltypointsnowholesale'] || @$GLOBALS['loyaltypointsnopercentdiscount']){
				$sSQL="SELECT clActions FROM customerlogin WHERE clID=" . $ordClientID;
				$result=ect_query($sSQL) or ect_error();
				if($rs=ect_fetch_assoc($result)){
					if(@$GLOBALS['loyaltypointsnowholesale'] && ($rs['clActions'] & 8)==8) $loyaltypointtotal=0;
					if(@$GLOBALS['loyaltypointsnopercentdiscount'] && ($rs['clActions'] & 16)==16) $loyaltypointtotal=0;
				}
				ect_free_result($result);
			}
			$sSQL="UPDATE orders SET loyaltyPoints=" . $loyaltypointtotal . " WHERE ordID='" . escape_string($sorderid) . "'";
			ect_query($sSQL) or ect_error();
			$sSQL="UPDATE customerlogin SET loyaltyPoints=loyaltyPoints+" . $loyaltypointtotal . " WHERE clID=" . $ordClientID;
			ect_query($sSQL) or ect_error();
		}
	}
	$numloyaltypoints=0;
	if($loyaltypoints!=''){
		$sSQL="SELECT loyaltyPoints FROM orders WHERE ordID='" . escape_string($sorderid) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result))
			$numloyaltypoints=$rs['loyaltyPoints'];
		ect_free_result($result);
		if($numloyaltypoints>0)
			$orderText=str_replace('%loyaltypointplaceholder%',$xxLoyPoi . ': ' . $numloyaltypoints . '<br />',$orderText);
		else
			$orderText=str_replace('%loyaltypointplaceholder%','',$orderText);
	}
	if($hasdownload==TRUE && @$digidownloademail!=''){
		$fingerprint=vrhmac($digidownloadsecret, $sorderid . $ordAuthNumber . $ordSessionID);
		$fingerprint=substr($fingerprint, 0, 14);
		$digidownloademail=str_replace('%orderid%',$ordID,$digidownloademail);
		$digidownloademail=str_replace('%password%',$fingerprint,$digidownloademail);
		$digidownloademail=str_replace('%nl%',$emlNl,$digidownloademail);
		$orderEmailText=str_replace('%digidownloadplaceholder%',$digidownloademail,$orderText);
	}else
		$orderEmailText=str_replace('%digidownloadplaceholder%',"",$orderText);
	$orderText=str_replace('%digidownloadplaceholder%',"",$orderText);
	$emailheader=replaceemailtxt($emailheader, '%reviewlinks%', $reviewlinks, $replaceone);
	$receiptheader=replaceemailtxt($receiptheader, '%reviewlinks%', $reviewlinkshtml, $replaceone);
	$emailrecpt=getemailrecpt($ordID);
	$recpt=getrecpt($ordID);
	if(@$loyaltypoints!=''){
		if($numloyaltypoints>0){
			$recpt=str_replace('<!--%loyaltypointplaceholder%-->','<div class="receiptcontainer rcontloyaltypoints"><div class="receiptleft">' . $xxLoyPoi . '</div><div class="receiptright">' . $numloyaltypoints . '</div></div>',$recpt);
			$emailrecpt=str_replace('<!--%loyaltypointplaceholder%-->','<tr><td valign="top"><strong>' . $xxLoyPoi . ':</strong></td><td valign="top" colspan="3">' . $numloyaltypoints . '</td></tr>',$emailrecpt);
		}else{
			$recpt=str_replace('<!--%loyaltypointplaceholder%-->','',$recpt);
			$emailrecpt=str_replace('<!--%loyaltypointplaceholder%-->','',$emailrecpt);
		}
	}
	if($hasdownload==FALSE){
		$recpt=str_replace('<!--%digidownloadplaceholder%-->','',$recpt);
		$recpt=str_replace('<!--%digidownloaditems%-->','',$recpt);
		$emailrecpt=str_replace('<!--%digidownloadplaceholder%-->','',$emailrecpt);
		$emailrecpt=str_replace('<!--%digidownloaditems%-->','',$emailrecpt);
	}
	$emlhdrs='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><style type="text/css">body{font-size:11px; font-family: Tahoma, Helvetica, Arial, Verdana}hr{height: 0;border-width: 1px 0 0 0;border-style: solid;border-color: #006AC8;}</style></head>';
	$hasheaders=preg_match('/<html(.*?)>/i',$emailheader);
	if($sendstoreemail&&$GLOBALS['allStoreEmails']!=''){
		$allemailsarray=explode(',',$GLOBALS['allStoreEmails']);
		foreach($allemailsarray as $sstoreemail){
			if(@$htmlemails==TRUE)
				dosendemail($sstoreemail, $sEmail, $custEmail, str_replace(array('%orderid%','%ordername%'),array($sorderid,$ordName),$xxOrdStr),($hasheaders?'':$emlhdrs.'<body class="receiptbody">') . str_replace('<br />', $emlNl, str_replace('%messagebody%', str_replace('<!--%digidownloadplaceholder%-->','<tr><td valign="top"><strong>'.$xxDigPro.':</strong></td><td valign="top" colspan="3">' . $digidownloademail . '</td></tr>',$emailrecpt), $emailheader)) . ($hasheaders?'':'</body></html>'));
			else
				dosendemail($sstoreemail, $sEmail, $custEmail, str_replace(array('%orderid%','%ordername%'),array($sorderid,$ordName),$xxOrdStr),str_replace('<br />', $emlNl, str_replace('%messagebody%', $orderEmailText, $emailheader)));
		}
	}
	// And one for the customer
	if($sendcustemail){
		$thesubject=str_replace('%ordername%', $ordName, $xxTnxOrd);
		if(@$encodecustomeremailsubject==TRUE) $thesubject=encodeemailsubject($thesubject, $emailencoding);
		if(@$htmlemails==TRUE)
			dosendemail($custEmail, $sEmail, '', str_replace(array('%orderid%','%ordername%'),array($sorderid,$ordName),$emailsubject),($hasheaders?'':$emlhdrs.'<body class="receiptbody">') . str_replace('<br />', $emlNl, str_replace('%messagebody%', str_replace('<!--%digidownloadplaceholder%-->','<tr><td valign="top"><strong>'.$xxDigPro.':</strong></td><td valign="top" colspan="3">' . $digidownloademail . '</td></tr>',$emailrecpt), $emailheader)) . ($hasheaders?'':'</body></html>'));
		else
			dosendemail($custEmail, $sEmail, '', str_replace(array('%orderid%','%ordername%'),array($sorderid,$ordName),$emailsubject),(trim_(@$xxTouSoo)!='' ? $xxTouSoo . $emlNl . $emlNl : '') . str_replace('<br />', $emlNl, str_replace('%messagebody%', $orderEmailText, $emailheader)));
	}
	$languageid=$savelangid;
	// Drop Shippers
	if($sendmanufemail){
		for($index=0; $index < $ndropshippers; $index++){
			$sSQL='SELECT dsEmail,dsAction,dsEmailHeader FROM dropshipper WHERE dsID=' . $dropShippers[$index][0];
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				if(($rs['dsAction'] & 1)==1 || (int)$sendmanufemail==2){
					dosendemail($rs['dsEmail'], $sEmail, '', str_replace('%orderid%',$sorderid,$dropshipsubject), str_replace('<br />', $emlNl, str_replace('%messagebody%', (trim_($rs['dsEmailHeader'])!='' ? $emlNl . str_replace('%nl%', $emlNl, $rs['dsEmailHeader']) . $emlNl : '') . $saveCustomerDetails . $dropShippers[$index][1], $dropshipheader)));
				}
			}
			ect_free_result($result);
		}
	}
	if($sendaffilemail){
		if($affilID!=''){
			$sSQL="SELECT affilEmail,affilInform FROM affiliates WHERE affilID='" . escape_string($affilID) . "'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				if((int)$rs['affilInform']==1){
					$affiltext=$xxAff1 . ' ' . FormatEmailEuroCurrency($ordTotal-$ordDiscount) . '.'.$emlNl.$emlNl.$xxAff2.$emlNl.$emlNl.$xxThnks.$emlNl;
					dosendemail(trim_($rs['affilEmail']), $sEmail, '', str_replace('%orderid%',$sorderid,$xxAff3), $emlNl . $affiltext);
				}
			}
			ect_free_result($result);
		}
	}
	if($doshowhtml){
		if($GLOBALS['hasimageupload']&&!@$GLOBALS['fromajaxservice']&&time()-strtotime($ordDate)<(60*60*24*14)){
			$imagesperitem=1;
			$maximages=0;
			if(@$GLOBALS['uploaditemsperorder']!='') $imagesperitem=$GLOBALS['uploaditemsperorder'];
			$sSQL="SELECT " . (@$GLOBALS['uploaditemsbyquantity']?'SUM(cartQuantity)':'COUNT(cartID)') . " AS sumquant FROM cart INNER JOIN products ON cart.cartProdID=products.pID WHERE cartOrderID='" . escape_string($ordID) . "' AND products.pUpload<>0";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				$maxuploadfiles=$rs['sumquant']*$imagesperitem;
				if($maxuploadfiles>100) $maxuploadfiles=100;
			}
			ect_free_result($result);
			if(@$GLOBALS['debugmode']){
				print 'upload_max_filesize: ' . ini_get('upload_max_filesize') . '<br />';
				print 'post_max_size: ' . ini_get('post_max_size') . '<br />';
			}
			$filetypes='.bmp,.gif,.jpg,.jpe,.jpeg,.pdf,.png,.tif,.tiff,.webp';
			$maxfilesize=2*1024*1024;
			if(@$GLOBALS['uploadfiletypes']!='') $filetypes=$GLOBALS['uploadfiletypes'];
			if(@$GLOBALS['uploadmaxfilesize']!='') $maxfilesize=$GLOBALS['uploadmaxfilesize'];
			print '<div class="iuopaque" id="imageuploadopdiv"' . (@$GLOBALS['imageuploadbybutton']?' style="display:none"':'') . '>';
				print '<div class="iuwrap" id="imageuploaddiv">';
					print '<div style="padding:20px;text-align:center;font-size:1.25em;font-weight:bold;color:#333">' . $GLOBALS['xxImUplo'] . '</div>';
?>
<div class="imageupload imageuploadhead"><?php print $GLOBALS['xxImgUpl'] ?></div>
<div id="drag-area" class="imageupload imageuploadfile">
	<h4 class="header" id="uploadheader">Drag & Drop Files to Upload Here</h4>
	<p>Or browse for the files</p>
	<button type="button" id="browsebutton" class="ectbutton">-</button>
	<input id="fileselectinput" type="file" accept="<?php print $filetypes?>" hidden="hidden" multiple="multiple">
</div>
<div class="imageupload imageuploadcomments"><?php print $GLOBALS['xxImgCom']?><input type="text" id="comments" style="width:50%" maxlength="512" /></div>
<div class="imageupload imageuploadprogress"><progress id="progressBar" value="0" max="100" style="width:80%"></progress></div>
<div id="uploadedimages" class="uploadedimagestable" style="display:none">
	<div class="uploadedimagesrow"><div><h4>#</h4></div><div><h4><?php print $GLOBALS['xxImgFin']?></h4></div><div><h4><?php print $GLOBALS['xxImgSta']?></h4></div></div>
<?php			$alreadyuploaded=0;
				$sSQL='SELECT upFilename,upComments FROM imageuploads WHERE upOrderID=' . $ordID;
				$result=ect_query($sSQL) or ect_error();
				while($rs=ect_fetch_assoc($result)){
					print '<div class="uploadedimagesrow"><div>'.($alreadyuploaded+1).'.</div><div>' . $rs['upFilename'] . '</div><div>&#9989;</div></div>';
					$alreadyuploaded++;
				} ?>
</div>
<div class="imageupload imageuploadbuttons">
	<input class="ectbutton" type="button" value="<?php print $GLOBALS['xxDonUpl']?>" onclick="document.getElementById('imageuploadopdiv').style.display='none'">
</div>
<script>
<?php
if($alreadyuploaded>0) print 'document.getElementById("uploadedimages").style.display="table";';
?>
var fileselectinput=document.getElementById("fileselectinput");
var ectuploadimgsrc='';
var imuploadhasselected=false;
var fuajaxobj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
var filestoupload;
var uploadedimages=<?php print $alreadyuploaded?>;
document.getElementById('browsebutton').innerHTML="<?php print jscheck($GLOBALS['xxImgBrs'])?>".replace('%d',<?php print $maxuploadfiles?>-uploadedimages);
<?php if($maxuploadfiles-$alreadyuploaded<=0) print "document.getElementById('browsebutton').disabled=true;"?>
const dropArea = document.getElementById("drag-area"),
dragText = document.getElementById("uploadheader");
var button = document.getElementById("browsebutton");
button.onclick = ()=>{
	fileselectinput.click(); // click button causes input click
}
fileselectinput.addEventListener("change", function(){ hasselectedimage(this.files); });
function doneimageupload(){
	var successuploads=0;
	if(fuajaxobj.readyState==4){
		imgstatus='';
		if(fuajaxobj.status==200){
			var restxt=fuajaxobj.responseText;
			var resarr=restxt.split(':');
			for(var index=0;index<resarr.length;index++){
				if(document.getElementById('fileerror')) document.getElementById('fileerror').remove();
				if((uploadedimages+index+1)><?php print $maxuploadfiles?>){
					alert('You can only upload a maximum of <?php print $maxuploadfiles ?> files.');
				}else if(resarr[index]=='SUCCESS'){
					if(!document.getElementById('filename'+(uploadedimages+index))){
						var subnode=document.createElement("DIV");
						subnode.className='uploadedimagesrow';
						subnode.innerHTML='<div>'+((uploadedimages+index)+1)+'.</div><div id="filename'+(uploadedimages+index)+'">-</div><div id="uploaded'+(uploadedimages+index)+'">-</div>';
						document.getElementById('uploadedimages').appendChild(subnode);
					}
					document.getElementById('filename'+(uploadedimages+index)).innerHTML=filestoupload[index].name;
					document.getElementById('uploaded'+(uploadedimages+index)).innerHTML='&#9989;';
					successuploads++;
				}else if(resarr[index]=='MAXIMAGES')
					document.getElementById('uploaded'+(uploadedimages+index)).innerHTML='Max number of images has been uploaded';
				else{
					var subnode=document.createElement("DIV");
					subnode.className='uploadedimagesrow ectwarning';
					subnode.id='fileerror';
					subnode.innerHTML='<div>&#10060;</div><div>' + filestoupload[index].name + '</div><div>&#10060; ' + resarr[index] + '</div>';
					document.getElementById('uploadedimages').appendChild(subnode);
				}
			}
		}else{
			alert(fuajaxobj.status+":Refused by server");
			document.getElementById("progressBar").value=0;
		}
		uploadedimages+=successuploads;
		document.getElementById('browsebutton').innerHTML="<?php print jscheck($GLOBALS['xxImgBrs'])?>".replace('%d',<?php print $maxuploadfiles?>-uploadedimages);
		if(<?php print $maxuploadfiles?>-uploadedimages<=0) document.getElementById('browsebutton').disabled=true;
		document.getElementById("uploadedimages").style.display='table';
		document.getElementById("fileselectinput").value='';
		document.getElementById("comments").value='';
	}
}
function progressHandler(event){
	document.getElementById("progressBar").value=Math.round((event.loaded / event.total) * 100);
}
function errorHandler(event){
	alert("Upload Failed");
}
function abortHandler(event){
	alert("Upload Aborted");
}
function dosubmitimage(){
<?php	if(!@$GLOBALS['uploadnousemultipart']){ ?>
	var fd = new FormData();
	for(var index=0;index<<?php print $maxuploadfiles?>;index++){
		if(filestoupload[index]){
			fd.append('myFiles'+index, filestoupload[index]);
			fd.append('filename'+index, filestoupload[index].name);
		}
	}
	fd.append('orderid', '<?php print $ordID?>');
	fd.append('session', '<?php print $ordSessionID ?>');
	fd.append('check', '<?php print sha1('imageupload^' . $ordID . '^' . $GLOBALS['adminSecret'] . '^fromect' . $ordSessionID)?>');
	fd.append('comments', document.getElementById('comments').value);
<?php	}else{ ?>
	var postdata='orderid=<?php print $ordID?>';
	postdata+='&filename='+encodeURIComponent(filestoupload[index].name) +
		'&session=<?php print $ordSessionID ?>' +
		'&check=<?php print sha1('imageupload^' . $ordID . '^' . $GLOBALS['adminSecret'] . '^fromect' . $ordSessionID)?>' +
		'&comments='+encodeURIComponent(document.getElementById('comments').value) +
		'&imgsrc='+encodeURIComponent(ectuploadimgsrc);
<?php	} ?>
	fuajaxobj.onreadystatechange=doneimageupload;
	fuajaxobj.upload.addEventListener("progress", progressHandler, false);
	fuajaxobj.addEventListener("error", errorHandler, false);
	fuajaxobj.addEventListener("abort", abortHandler, false);
	fuajaxobj.open("POST",'vsadmin/ajaxservice.php?action=imageupload',true);
<?php	if(!@$GLOBALS['uploadnousemultipart']){ ?>
	fuajaxobj.send(fd);
<?php	}else{ ?>
	fuajaxobj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	fuajaxobj.send(postdata);
<?php	} ?>
}
function hasselectedimage(inputfiles){
	var reader,haserror=false,filelist='',separator='';
	if(inputfiles && inputfiles[0]){
		for(var index=0;index<inputfiles.length;index++){
			let fileType = inputfiles[index].type;
			let fileName = inputfiles[index].name;
			filelist=fileName+separator+filelist;
			separator=', ';
			let validExtensions=[<?php print '"' . strtolower(str_replace(',','","',$filetypes)) . '"'?>];
			let fileExtension='.'+fileName.split('.').pop().toLowerCase();;
			if(fileName.indexOf('.')==-1) fileExtension='xxx';
			if(!(validExtensions.includes(fileExtension))){
				alert("This is not a valid file type.");
				dropArea.classList.remove("hoverwithfile");
				dragText.textContent = "Drag & Drop Files to Upload Here";
				haserror=true;
			}else if(inputfiles[index].size><?php print $maxfilesize?>){
				alert('The file you have selected is too large to upload. (Max. <?php print ($maxfilesize/(1024*1024)).'M' ?>)');
				haserror=true;
			}else if((index+uploadedimages)>=<?php print $maxuploadfiles?>){
				alert('You can only upload a maximum of <?php print $maxuploadfiles ?> files.');
				haserror=true;
			}
		}
		if(!haserror){
			reader=new FileReader();
			reader.onload=function(e){
				filestoupload=inputfiles;
				dragText.textContent = 'Uploading . . . ' + filelist;
				ectuploadimgsrc=e.target.result;
				document.getElementById("progressBar").value=0;
				dosubmitimage();
			}
			reader.readAsDataURL(inputfiles[0]);
		}
	}
}
dropArea.addEventListener("dragover", (event)=>{
	event.preventDefault();
	dropArea.classList.add("hoverwithfile");
	dragText.textContent = "Release to Upload Files";
});
dropArea.addEventListener("dragleave", ()=>{
	dropArea.classList.remove("hoverwithfile");
	dragText.textContent = "Drag & Drop Files to Upload Here";
});
dropArea.addEventListener("drop", (event)=>{
	dropArea.classList.remove("hoverwithfile");
	event.preventDefault();
	hasselectedimage(event.dataTransfer.files);
});
</script>
<?php
				print '</div>';
			print '</div>';
		}
?>
<script>
<!--
function doprintcontent(){
	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()"><div class="printbody">\n';
	prnttext+=document.getElementById('printcontent').innerHTML+"\n";
	prnttext+='</div><' + '/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();
}
//-->
</script>
<?php

		$dltext = "";
		if(trim_(@$digidownloadpath)!=''){
			if(substr($digidownloadpath,-1)!='/'&&substr($digidownloadpath,-1)!='\\') $digidownloadpath.=DIRECTORY_SEPARATOR;
		}else
			$digidownloadpath='';
		if(@$digidownloaddays=="") $digidownloaddays=3;

		if(@$digidownloadsecret=="") $digidownloadsecret="this is some secwet text";
		$sSQL="SELECT cartID,cartProdID,cartProdName,cartProdPrice,cartSessionID,pDownload FROM products INNER JOIN cart ON products.pID=cart.cartProdID INNER JOIN orders ON cart.cartOrderID=orders.ordID WHERE ordStatus>=3 AND cartCompleted=1 AND cartOrderID='" . $ordID . "' AND ordAuthNumber='" . escape_string($ordAuthNumber) . "' AND pDownload<>'' AND ordDate > '" . date("Y-m-d", (time()-(60*60*24*$digidownloaddays))) . "'";
		$result=ect_query($sSQL) or ect_error();
		if(ect_num_rows($result) > 0){
			while($rs=ect_fetch_assoc($result)){
				$theid = $rs['cartProdID'];
				$hasdownload = TRUE;
				$noregexpcol=FALSE;
				if(($thedownload=trim($rs['pDownload']))!=''){
					if(strtolower($thedownload)=='a'){ // auto download
						$thedownload = str_replace("%pid%", $theid, trim_(@$digidownloadpattern));
					}
					$thedownloadarray=explode(',',$thedownload);
					$sSQL="SELECT optRegExp FROM cartoptions INNER JOIN options ON cartoptions.coOptID=options.optID WHERE coCartID=" . $rs["cartID"] . " ORDER BY coCartID";
					$result2=ect_query($sSQL) or $noregexpcol=TRUE;
					if($noregexpcol != TRUE){
						while($rs2=ect_fetch_assoc($result2)){
							$theexp = trim($rs2["optRegExp"]);
							if(substr($theexp, 0, 1)=="!"){
								$theexp = substr($theexp, 1);
								for($dlindex=0; $dlindex<count($thedownloadarray);$dlindex++){
									if(substr($theexp, 0, 1)=="!"){
										$hasdownload = FALSE;
										$thedownloadarray[$dlindex]='';
									}else{
										$theexp = str_replace('%s', $thedownloadarray[$dlindex], $theexp);
										if(strpos($theexp, " ") !== FALSE){ // Search and replace
											$exparr = explode(' ', $theexp, 2);
											$thedownloadarray[$dlindex] = str_replace($exparr[0], $exparr[1], $thedownloadarray[$dlindex]);
										}else
											$thedownloadarray[$dlindex] = $theexp;
									}
								}
							}
						}
					}
					ect_free_result($result2);
					for($dlindex=0; $dlindex<count($thedownloadarray);$dlindex++){
						if($thedownloadarray[$dlindex]!=''){
							$fingerprint = vrhmac($digidownloadsecret, $rs['cartID'] . $theid . $rs['cartSessionID'] . (@$digidownloadpath!=''?$thedownloadarray[$dlindex]:''));
							$dltext.='<div class="downloadlistrow"><div>' . $theid . '</div><div>' . $rs["cartProdName"] . '</div><div>';
							$ispdf=FALSE;
							if(@$digidownloadmethod!='filesystem') $ispdf=strtolower(substr($thedownloadarray[$dlindex],-4))=='.pdf';
							if(@$imgdownloadproducts!=''){
								if(@$digidownloadmethod=='filesystem'){
									$dltext .= '<input '.($imgdownloadproducts=='button'?'type="button"':'type="image" src="'.$imgdownloadproducts.'"').' value="' . htmlspecials($GLOBALS['xxDlPro'] . (@$digidownloadpath!=''?' - ' . $thedownloadarray[$dlindex]:'')) . '" class="'.($imgdownloadproducts=='button'?'ectbutton ':'').'downloadproducts" onclick="document.location=\'' . $GLOBALS['storeurlssl'] . 'vsadmin/dodownload.php?ref=' . $theid . '&id=' . $rs['cartID'] . '&sd=' . $rs["cartSessionID"] . '&rd=' . $fingerprint . '\'" />';
								}else{
									$dltext .= '<input '.($imgdownloadproducts=='button'?'type="button"':'type="image" src="'.$imgdownloadproducts.'"').' value="' . htmlspecials($GLOBALS['xxDlPro'] . (@$digidownloadpath!=''?' - ' . $thedownloadarray[$dlindex]:'')) . '" class="'.($imgdownloadproducts=='button'?'ectbutton ':'').'downloadproducts" onclick="' . ($ispdf?'window.open(\'' . jsescapel($digidownloadpath . $thedownloadarray[$dlindex]) . '\',\'_blank\')':'document.location=\'' . jsescapel($digidownloadpath . $thedownloadarray[$dlindex]) . '\'') . '" />';
								}
							}else{
								if(@$digidownloadmethod=='filesystem'){
									$dltext .= '<a class="ectlink" style="color:#FF0000;font-size:18px;font-weight:bold" href="' . $GLOBALS['storeurlssl'] . 'vsadmin/dodownload.php?ref=' . $theid . '&id=' . $rs['cartID'] . '&sd=' . $rs["cartSessionID"] . '&rd=' . $fingerprint . '">' . htmlspecials($GLOBALS['xxDlPro'] . (@$digidownloadpath!=''?' - ' . $thedownloadarray[$dlindex]:'')) . '</a>';
								}else{
									$dltext .= '<a class="ectlink" style="color:#FF0000;font-size:18px;font-weight:bold" href="' . str_replace('"', "&quot;", $digidownloadpath . $thedownloadarray[$dlindex]) . '"' . ($ispdf?' target="_blank"':'') . '>' . htmlspecials($GLOBALS['xxDlPro'] . (@$digidownloadpath!=''?' - ' . $thedownloadarray[$dlindex]:'')) . '</a>';
								}
							}
							$dltext.="</div></div>\r\n";
						}
					}
				}
			}
		}
		ect_free_result($result);
		if($dltext!=''){
			$dltext='<div class="receiptdownload">' .
					'  <div class="receiptsectionhead receiptdownloadhead">' . $GLOBALS['xxDlPros'] . '</div>' .
					'  <div class="downloadlist">' .
					'  <div class="downloadheadrow"><div>' . $GLOBALS['xxPrId'] . '</div><div>' . $GLOBALS['xxPrNm'] . '</div><div>' . $GLOBALS['xxDownl'] . '</div></div>' . $dltext . '  </div>' .
					"</div>\r\n";
		}elseif(@$warnexpireddownload){
			$dltext='<div class="receiptdownload receiptnodownload">' .
					'  <div class="receiptsectionhead receiptdownloadhead">' . $GLOBALS['xxDlPros'] . '</div>' .
					'  <div class="receiptnodownloadtext">There are no downloadable products associated with this order or the download time has expired.</div>' .
					"</div>\r\n";
		}
		if(@$GLOBALS['noshowdigiordertext']==TRUE){
			print $dltext;
		}else{
			$GLOBALS['recpt'] = str_replace('<!--%digidownloaditems%-->',$dltext,$GLOBALS['recpt']);
?>
			<div class="orderreceipt">
<?php		if(@$GLOBALS['xxThkYou']!='') print '<div class="recptthanks">' . $GLOBALS['xxThkYou'] . '</div>' ?>
				<div id="printcontent" class="recptbody"><?php print str_replace('%nl%','<br />',str_replace("%messagebody%", $recpt, $receiptheader))?></div>
				<div class="receiptbuttons">
<?php		if(trim_($xxRecEml)!='') print '<div class="receiptrecemail">' . $xxRecEml . '</div>';
			print '<div class="receiptcontinueshopping">' . imageorbutton(@$imgcontinueshopping,'&nbsp;'.$xxCntShp.'&nbsp;','continueshopping',(@$thankspagecontinue!=''?$thankspagecontinue:$storeurl),@$thankspagecontinue=='javascript:history.go(-1)'?TRUE:FALSE) . '</div>';
			print '<div class="receiptprintversion">' . imageorbutton(@$imgprintversion,'&nbsp;'.$xxPrint.'&nbsp;','printversion','doprintcontent()', TRUE) . '</div>';
?>				</div>
			</div>
<?php	}
	}
}
?>