<?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(@$dateformatstr=='') $dateformatstr='m/d/Y';
$admindatestr='Y-m-d';
if(@$admindateformat=='') $admindateformat=0;
if($admindateformat==1)
	$admindatestr='m/d/Y';
elseif($admindateformat==2)
	$admindatestr='d/m/Y';
$themask='yyyy-mm-dd';
if($admindateformat==1)
	$themask='mm/dd/yyyy';
elseif($admindateformat==2)
	$themask='dd/mm/yyyy';
$dropshipper='';
$haschangedonotherdevice=FALSE;
if(@$_SESSION['loginid']!=0 && @$_SESSION['dropshipper']!='' && @$_SESSION['dropshipper']!=0) $dropshipper=@$_SESSION['dropshipper'];
if(@$storesessionvalue=='') $storesessionvalue='virtualstore'.time();
if(@$_SESSION['loggedon']!=$storesessionvalue||@$GLOBALS['disallowlogin']||!@$GLOBALS['incfunctionsdefined']) exit;
if(getget('doedit')=='true' || getget('id')=='new') $doedit=TRUE; else $doedit=FALSE;
$isinvoice=(getget('invoice')=='true') && $dropshipper=='';
if(@$maxordersperpage=='')$maxordersperpage=250;
$iNumOfPages=0;
if(! is_numeric(getget('pg')) || strlen(getget('pg'))>8) $CurPage=1; else $CurPage=max(1, (int)getget('pg'));
function trimoldcartitems($cartitemsdel){
	$thetocdate=time() + ($GLOBALS['dateadjust']*60*60);
	$sSQL="SELECT adminDelUncompleted,adminClearCart FROM admin WHERE adminID=1";
	$result=ect_query($sSQL) or ect_error();
	$rs=ect_fetch_assoc($result);
	$delAfter=$rs['adminDelUncompleted'];
	$delSavedCartAfter=$rs['adminClearCart'];
	ect_free_result($result);
	if($delAfter!=0){
		$sSQL="SELECT ordID FROM orders WHERE ordAuthNumber='' AND ordDate<'" . date("Y-m-d H:i:s", $thetocdate-($delAfter*60*60*24)) . "' AND ordStatus=2 LIMIT 0,1000";
		$result=ect_query($sSQL) or ect_error();
		while($rs=ect_fetch_assoc($result)){
			release_stock($rs['ordID']);
			ect_query("UPDATE cart SET cartOrderID=0 WHERE cartOrderID=".$rs['ordID']);
			ect_query("DELETE FROM couponsapplied WHERE cpaOrdID=".$rs['ordID']);
			ect_query("DELETE FROM orders WHERE ordID=".$rs['ordID']);
		}
		ect_free_result($result);
	}
	$sSQL='SELECT cartID,listOwner FROM cart LEFT JOIN customerlists ON cart.cartListID=customerlists.listID WHERE cartCompleted=0 AND cartOrderID=0 AND ';
	$sSQL.="((cartClientID=0 AND cartDateAdded<'" . date("Y-m-d H:i:s", $cartitemsdel) . "') ";
	if($delSavedCartAfter!=0) $sSQL.="OR (cartDateAdded<'" . date("Y-m-d H:i:s", $thetocdate-($delSavedCartAfter*60*60*24)) . "') ";
	$sSQL.=') LIMIT 0,1000';
	$result=ect_query($sSQL) or ect_error();
	$rowcounter=0;
	if(ect_num_rows($result) > 0){
		$delOptions=$addcomma='';
		while($rs=ect_fetch_assoc($result)){
			if(! is_null($rs['listOwner'])){
				ect_query("UPDATE cart SET cartCompleted=3,cartClientID=" . $rs['listOwner'] . " WHERE cartID=" . $rs['cartID']) or ect_error();
			}else{
				$delOptions.=$addcomma . $rs['cartID'];
				$addcomma=',';
			}
			$rowcounter++;
		}
		if($delOptions!='') ect_query("DELETE FROM cartoptions WHERE coCartID IN (" . $delOptions . ')');
		if($delOptions!='') ect_query("DELETE FROM cart WHERE cartID IN (" . $delOptions . ')');
	}
	ect_free_result($result);
	return($rowcounter>950?'':'1');
}
function editspecial($data,$col,$size,$special){
	global $doedit;
	if($doedit) return('<input type="text" id="' . $col . '" name="' . $col . '" value="' . htmlspecialsucode($data) . '" size="' . $size . '" '.$special.'>'); else return(htmldisplay($data));
}
function editfunc($data,$col,$size){
	global $doedit;
	if($doedit) return('<input type="text" id="' . $col . '" name="' . $col . '" value="' . htmlspecialsucode($data) . '" size="' . $size . '">'); else return(htmldisplay($data));
}
function editnumeric($data,$col,$size,$evt){
	global $doedit;
	if($doedit) return('<input type="text" id="' . $col . '" name="' . $col . '" value="' . number_format(strip_tags($data),2,'.','') . '" size="' . $size . '" ' . $evt . '/>'); else return(FormatEuroCurrency(strip_tags($data)));
}
function getNumericField($fldname){
	$fldval=getpost($fldname);
	if(! is_numeric($fldval)) return(0); else return((float)$fldval);
}
function decodehtmlentities($thestr){
	return(str_replace(array('&quot;','&nbsp;'), array('"', ' '), $thestr));
}
function writesearchparams(){
	writehiddenvar('fromdate', @$_SESSION['fromdate']);
	writehiddenvar('todate', @$_SESSION['todate']);
	writehiddenvar('notstatus', @$_SESSION['notstatus']);
	writehiddenvar('notsearchfield', @$_SESSION['notsearchfield']);
	writehiddenvar('searchtext', @$_SESSION['searchtext']);
	if(is_array(@$_SESSION['ordStatus'])){
		foreach($_SESSION['ordStatus'] as $key => $val)
			writehiddenvar('ordStatus[]', $val);
	}
	if(is_array(@$_SESSION['ordstate'])){
		foreach($_SESSION['ordstate'] as $key => $val)
			writehiddenvar('ordstate[]', $val);
	}
	if(is_array(@$_SESSION['ordcountry'])){
		foreach($_SESSION['ordcountry'] as $key => $val)
			writehiddenvar('ordcountry[]', $val);
	}
	if(is_array(@$_SESSION['payprovider'])){
		foreach($_SESSION['payprovider'] as $key => $val)
			writehiddenvar('payprovider[]', $val);
	}
	if(is_array(@$_SESSION['orddiscount'])){
		foreach($_SESSION['orddiscount'] as $key => $val)
			writehiddenvar('orddiscount[]', $val);
	}
	writehiddenvar('ordersearchfield', @$_COOKIE['ordersearchfield']);
}
function showgetoptionsselect($oid){
	return('<div style="position:absolute"><select id="'.$oid.'" size="15" ' .
		'style="display:none;position:absolute;min-width:280px;top:0px;left:0px;" ' .
		'onblur="this.style.display=\'none\'" ' .
		'onchange="comboselect_onchange(this)" ' .
		'onclick="comboselect_onclick(this)" ' .
		'onkeyup="comboselect_onkeyup(event.keyCode,this)">' .
		'<option value="">Populating...</option>' .
		'</select></div>');
}
function getdates(){
	global $hastodate,$hasfromdate,$todate,$fromdate,$thetodate,$thefromdate;
	$hasfromdate=FALSE;
	$hastodate=FALSE;
	$fromdate=trim_(@$_REQUEST['fromdate']);
	$todate=trim_(@$_REQUEST['todate']);
	if($fromdate!=''){
		$hasfromdate=TRUE;
		if(is_numeric($fromdate))
			$thefromdate=time()-($fromdate*60*60*24);
		else
			$thefromdate=parsedate($fromdate);
	}else
		$thefromdate=strtotime(date('Y-m-d', time()+($GLOBALS['dateadjust']*60*60)));
	if($todate!=''){
		$hastodate=TRUE;
		if(is_numeric($todate))
			$thetodate=time()-($todate*60*60*24);
		else
			$thetodate=parsedate($todate);
	}else
		$thetodate=strtotime(date('Y-m-d', time()+($GLOBALS['dateadjust']*60*60)));
	if($hasfromdate && $hastodate){
		if($thefromdate > $thetodate){
			$tmpdate=$thetodate;
			$thetodate=$thefromdate;
			$thefromdate=$tmpdate;
		}
	}
}
function getordsearchwheresql(){
	global $whereSQL,$hastodate,$hasfromdate,$thetodate,$thefromdate,$dropshipper;
	$editablefield=@$_COOKIE['editablefield'];
	$searchtext=escape_string(getrequest('searchtext'));
	$ordersearchfield=getrequest('ordersearchfield');
	if($ordersearchfield!='')setcookie('ordersearchfield',$ordersearchfield,time()+31536000, '/', '', @$_SERVER['HTTPS']=='on');
	$ordstatus=@$_REQUEST['ordStatus'];
	$ordstate=@$_REQUEST['ordstate'];
	$ordcountry=@$_REQUEST['ordcountry'];
	$payprovider=@$_REQUEST['payprovider'];
	$orddiscount=@$_REQUEST['orddiscount'];
	if($ordersearchfield=='product' && $searchtext!='') $whereSQL.=' INNER JOIN cart ON orders.ordID=cart.cartOrderID ';
	if(($ordersearchfield=='ordid'||$ordersearchfield=='') && $searchtext!='' && is_numeric($searchtext)){
		$whereSQL.=" WHERE ordID='" . $searchtext . "' ";
	}else{
		if($editablefield=='abandoned'){
			if(getpost('abandonedstatus')=='recovered')
				$whereSQL.=" WHERE ordStatus>2 AND ordAuthNumber<>''";
			else
				$whereSQL.=" WHERE ordStatus=2 AND ordAuthNumber=''";
		}else{
			if(is_array($ordstatus)) $whereSQL.=' WHERE ' . (getrequest('notstatus')=='ON' ? 'NOT ' : '') . '(ordStatus IN (' . implode(',', $ordstatus) . '))'; else $whereSQL.=' WHERE ordStatus<>1';
		}
		if(is_array($ordstate)) $whereSQL.=' AND ' . (getrequest('notsearchfield')=='ON' ? 'NOT ' : '') . "(ordState IN ('" . implode("','", $ordstate) . "'))";
		if(is_array($ordcountry)) $whereSQL.=' AND ' . (getrequest('notsearchfield')=='ON' ? 'NOT ' : '') . "(ordCountry IN ('" . implode("','", $ordcountry) . "'))";
		if(is_array($payprovider)) $whereSQL.=' AND ' . (getrequest('notsearchfield')=='ON' ? 'NOT ' : '') . '(ordPayprovider IN (' . implode(',', $payprovider) . '))';
		if(is_array($orddiscount)) $whereSQL.=' AND ' . (getrequest('notsearchfield')=='ON' ? 'NOT ' : '') . '(cpaCpnID IN (' . implode(',', $orddiscount) . '))';
		if($hasfromdate)
			$whereSQL.=" AND ordDate BETWEEN '" . date('Y-m-d', $thefromdate) . "' AND '" . date('Y-m-d', ($hastodate ? $thetodate+96400 : $thefromdate+96400)) . "'";
		elseif($searchtext=='' && $ordstatus=='' && $ordstate=='' && $ordcountry=='' && $payprovider=='' && $orddiscount=='')
			$whereSQL.=" AND ordDate BETWEEN '" . date('Y-m-d', time()+($GLOBALS['dateadjust']*60*60)) . "' AND '" . date('Y-m-d', time()+($GLOBALS['dateadjust']*60*60)+96400) . "'";
		if($searchtext!=''){
			if($ordersearchfield=='ordid' || $ordersearchfield=='' || $ordersearchfield=='name'){
				if(@$GLOBALS['usefirstlastname']){
					splitfirstlastname($searchtext,$firstname,$lastname);
					if($lastname=='')
						$namesql="(ordName LIKE '%".$firstname."%' OR ordLastName LIKE '%".$firstname."%')";
					else
						$namesql="(ordName LIKE '%".$firstname."%' AND ordLastName LIKE '%".$lastname."%')";
				}else
					$namesql="ordName LIKE '%".$searchtext."%'";
			}
			if($ordersearchfield=='ordid'||$ordersearchfield=='')
				$whereSQL.=" AND (ordEmail LIKE '%" . $searchtext . "%' OR ".$namesql.')';
			elseif($ordersearchfield=='email')
				$whereSQL.=" AND ordEmail LIKE '%" . $searchtext . "%'";
			elseif($ordersearchfield=='authcode')
				$whereSQL.=" AND (ordAuthNumber LIKE '%" . $searchtext . "%' OR ordTransID LIKE '%" . $searchtext . "%')";
			elseif($ordersearchfield=='name')
				$whereSQL.=" AND " . $namesql;
			elseif($ordersearchfield=='product')
				$whereSQL.=" AND (cartProdID LIKE '%" . $searchtext . "%' OR cartProdName LIKE '%" . $searchtext . "%')";
			elseif($ordersearchfield=='address')
				$whereSQL.=" AND (ordAddress LIKE '%" . $searchtext . "%' OR ordAddress2 LIKE '%" . $searchtext . "%' OR ordCity LIKE '%" . $searchtext . "%' OR ordState LIKE '%" . $searchtext . "%' OR ordShipAddress LIKE '%" . $searchtext . "%' OR ordShipAddress2 LIKE '%" . $searchtext . "%' OR ordShipCity LIKE '%" . $searchtext . "%' OR ordShipState LIKE '%" . $searchtext . "%')";
			elseif($ordersearchfield=='phone')
				$whereSQL.=" AND ordPhone LIKE '%" . $searchtext . "%'";
			elseif($ordersearchfield=='zip')
				$whereSQL.=" AND ordZip LIKE '%" . $searchtext . "%'";
			elseif($ordersearchfield=='invoice')
				$whereSQL.=" AND ordInvoice LIKE '%" . $searchtext . "%'";
			elseif($ordersearchfield=='tracknum')
				$whereSQL.=" AND ordTrackNum LIKE '%" . $searchtext . "%'";
			elseif($ordersearchfield=='affiliate')
				$whereSQL.=" AND ordAffiliate='" . $searchtext . "'";
			elseif($ordersearchfield=='extra1')
				$whereSQL.=" AND ordExtra1 LIKE '%" . $searchtext . "%'";
			elseif($ordersearchfield=='extra2')
				$whereSQL.=" AND ordExtra2 LIKE '%" . $searchtext . "%'";
			elseif($ordersearchfield=='checkout1')
				$whereSQL.=" AND ordCheckoutExtra1 LIKE '%" . $searchtext . "%'";
			elseif($ordersearchfield=='checkout2')
				$whereSQL.=" AND ordCheckoutExtra2 LIKE '%" . $searchtext . "%'";
		}
	}
	if($dropshipper!='') $whereSQL.=' AND pDropShip=' . @$_SESSION['dropshipper'];
}
if(@$htmlemails==TRUE) $emlNl='<br>'; else $emlNl="\n";

if(getget("id")==''){
	$sSQL="SELECT payProvID FROM payprovider WHERE payProvEnabled<>0 AND payProvID IN (1,18,19,22)";
	$result=ect_query($sSQL) or ect_error();
	$oldpaypalversions=ect_num_rows($result)>0;
	if($oldpaypalversions){
?>
<div style="border:1px solid #F00;text-align:center;padding:10px"><p>PayPal Standard, PayPal Direct Payments and PayPal Express are now no longer supported by PayPal.</p>
<button type="button" onclick="document.location='adminpayprov.php'">Click here to Update to PayPal Checkout.</button>
</div>
<?php
	}
}

$success=TRUE;
$alreadygotadmin=getadminsettings();
$homecountrytaxrate=$countryTaxRate;
if(getpost('updatestatus')=='1' || getpost('act')=='status'){
	$sSQL='SELECT orderstatussubject,orderstatussubject2,orderstatussubject3,orderstatusemail,orderstatusemail2,orderstatusemail3 FROM emailmessages WHERE emailID=1';
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		$ordstatussubject[1]=$rs['orderstatussubject'];
		$ordstatusemail[1]=$rs['orderstatusemail'];
		$ordstatussubject[2]=$rs['orderstatussubject2'];
		$ordstatusemail[2]=$rs['orderstatusemail2'];
		$ordstatussubject[3]=$rs['orderstatussubject3'];
		$ordstatusemail[3]=$rs['orderstatusemail3'];
	}
	ect_free_result($result);
}
if(getpost('act')=='abandoned' || getpost('act')=='oneabandoned'){
	if((getpost('act')=='abandoned' && is_array(@$_POST['ids'])) || (getpost('act')=='oneabandoned' && getpost('id')!='')){
		$replaceone=FALSE;
		$sSQL='SELECT abandonedcartsubject,abandonedcartsubject2,abandonedcartsubject3,abandonedcartemail,abandonedcartemail2,abandonedcartemail3 FROM emailmessages WHERE emailID=1';
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			$abandonedcartsubject[1]=$rs['abandonedcartsubject'];
			$abandonedcartemail[1]=$rs['abandonedcartemail'];
			$abandonedcartsubject[2]=$rs['abandonedcartsubject2'];
			$abandonedcartemail[2]=$rs['abandonedcartemail2'];
			$abandonedcartsubject[3]=$rs['abandonedcartsubject3'];
			$abandonedcartemail[3]=$rs['abandonedcartemail3'];
		}
		ect_free_result($result);
		if(getpost('act')=='abandoned') $idlist=@$_POST['ids']; else $idlist=array(getpost('id'));
		foreach($idlist as $theid){
			$ordername='';
			$sSQL='SELECT COUNT(*) AS tcount FROM abandonedcartemail WHERE aceOrderID=' . $theid;
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)) $tcount=$rs['tcount']+1; else $tcount=1;
			ect_free_result($result);
			$result=ect_query('SELECT ordStatus,ordAuthNumber,ordEmail,ordDate,ordName,ordLastName,ordLang FROM orders WHERE ordID='.$theid) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				$languageid=$rs['ordLang']+1;
				$ordername=trim_($rs['ordName'].' '.$rs['ordLastName']);
				$ordemail=$rs['ordEmail'];
				$orddate=strtotime($rs['ordDate']);
			}
			ect_free_result($result);
			if(($adminlangsettings & 4096)==0) $languageid=1;
			if($abandonedcartsubject[$languageid]!='') $emailsubject=$abandonedcartsubject[$languageid];
			$ose=$abandonedcartemail[$languageid];
			for($uoindex=1; $uoindex<=3; $uoindex++){
				$ose=replaceemailtxt($ose,'%email' . $uoindex . '%',$uoindex==$tcount?'%ectpreserve%':'',$replaceone);
				$emailsubject=replaceemailtxt($emailsubject,'%email' . $uoindex . '%',$uoindex==$tcount?'%ectpreserve%':'',$replaceone);
			}
			$ose=str_replace('%ordername%', $ordername, $ose);
			$ose=str_replace('%orderdate%', date($dateformatstr, $orddate) . ' ' . date('H:i', $orddate), $ose);
			$acekey=md5('ECT Abandoned Cart'.trim_($theid).':'.$ordemail.':'.$adminSecret);
			$abandonedcartid=$storeurl.'cart'.$GLOBALS['extension'].'?acartid='.trim_($theid).'&acarthash='.$acekey;
			$ose=str_replace('%abandonedcartid%', $abandonedcartid, $ose);
			$ose=str_replace('%nl%', $emlNl, $ose);
			$ose=str_replace(array('<br>','<br />','<br/>'), $emlNl, $ose);
			if($emailsubject!='' && $ose!=''){
				$sSQL='INSERT INTO abandonedcartemail (aceOrderID,aceDateSent,aceKey) VALUES (' . $theid . ",'" . date('Y-m-d') . "','" . escape_string($acekey) . "')";
				ect_query($sSQL) or ect_error();
				dosendemail($ordemail,$emailAddr,'',$emailsubject,$ose);
			}else
				print 'BLANK EMAIL: NOT SENT<br>';
		}
	}
	$yyUpdSuc='Sending Emails...';
}elseif(getpost('updatestatus')=='1' && is_numeric(getpost("orderid")) && is_numeric(getpost("currStatus"))){
	$sSQL="UPDATE orders SET ordStatusInfo='' WHERE ordStatusInfo IS NULL AND ordID='" . escape_string(getpost("orderid")) . "'";
	ect_query($sSQL) or ect_error();
	$sSQL="UPDATE orders SET ordPrivateStatus='' WHERE ordPrivateStatus IS NULL AND ordID='" . escape_string(getpost("orderid")) . "'";
	ect_query($sSQL) or ect_error();
	$sSQL="SELECT ordID FROM orders WHERE ordStatus='" . escape_string(getpost("currStatus")) . "' AND ordID='" . escape_string(getpost("orderid")) . "'";
	$result=ect_query($sSQL) or ect_error();
	$haschangedonotherdevice=ect_num_rows($result)<1;
	if($haschangedonotherdevice){
		$sSQL="SELECT ordID,ordStatus,ordStatusInfo,ordPrivateStatus FROM orders WHERE ordID='" . escape_string(getpost("orderid")) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)){
			if((string)$rs['ordStatus']==getpost("currStatus") && trim(str_replace("\r",'',$rs['ordStatusInfo']))==str_replace("\r",'',getpost("currStatusInfo")) AND trim(str_replace("\r",'',$rs['ordPrivateStatus']))==str_replace("\r",'',getpost("currPrivateStatus")))
				$haschangedonotherdevice=FALSE;
		}
		ect_free_result($result);
	}
	if(! $haschangedonotherdevice){
		ect_query("UPDATE orders SET ordStatusInfo='" . escape_string(getpost('ordStatusInfo')) . "',ordPrivateStatus='" . escape_string(getpost('ordPrivateStatus')) . "' WHERE ordID='" . escape_string(getpost('orderid')) . "'") or ect_error();
		ect_query("UPDATE orders set ordAuthNumber='" . escape_string(getpost('authcode')!='' ? getpost('authcode') : $yyManAut) . "' WHERE ordStatus>=3 AND ordAuthNumber='' AND ordID='" . escape_string(getpost('orderid')) . "'") or ect_error();
		ect_query("UPDATE cart SET cartCompleted=1 WHERE cartOrderID='" . escape_string(getpost('orderid')) . "'") or ect_error();
		updateorderstatus(getpost('orderid'), (int)getpost('ordStatus'), getpost('emailstat')=='1');
	}
}elseif(is_numeric(getget('id')) && getget('id')!='multi' && getget('id')!='new'){
	if(getpost('delccdets')!='')
		ect_query("UPDATE orders SET ordCNum='' WHERE ordID=" . getget('id')) or ect_error();
}else{
	$delccafter=0;
	if($delccafter!=0) ect_query("UPDATE orders SET ordCNum='' WHERE ordDate<'" . date("Y-m-d H:i:s", time()-($delccafter*60*60*24)) . "'") or ect_error();
	if(@$persistentcart=='') $persistentcart=3;
	if(@$_SESSION['hasdeletedoldcart']!='1'){ trimoldcartitems(time()-($persistentcart*60*60*24)); $_SESSION['hasdeletedoldcart']='1'; }
}
$numstatus=0;
$sSQL="SELECT statID,statPrivate FROM orderstatus WHERE statPrivate<>'' ORDER BY statID";
$result=ect_query($sSQL) or ect_error();
while($rs=ect_fetch_assoc($result)){
	$allstatus[$numstatus++]=$rs;
}
ect_free_result($result);
print '<div id="preloaderdiv" class="ectopaque" style="display:none;text-align:center" onclick="if(event.target==this)this.style.display=\'none\'"><img src="adminimages/preloader.gif" alt="" class="ectpreloader"></div>';
if(getpost("act")=="delnotification"){
	$sSQL="DELETE FROM devicenotifications WHERE dnID='" . escape_string(getpost("dnid")) . "'";
	ect_query($sSQL) or ect_error();
	print '<div style="text-align:center;padding:50px">Device Notification Deleted</div>';
	print '<meta http-equiv="refresh" content="2; URL=adminorders.php">';
}elseif(getget("act")=="dnotif"){
	// Device Notifications
	$sSQL="SELECT dnID FROM devicenotifications ORDER BY dnID";
	$result=ect_query($sSQL) or ect_error();
	if(ect_num_rows($result)>0){
?>
<script>
function removenotification(dnid){
	if(confirm("Are you sure you want to remove this device notification?")){
		document.getElementById('dnid').value=dnid;
		document.getElementById('dnform').submit();
	}
}
</script>
<form method="post" action="adminorders.php" id="dnform">
<input type="hidden" name="act" value="delnotification">
<input type="hidden" name="dnid" id="dnid" value="">
<h3 class="round_top half_top"><?php print "Device Notifications"?></h3>
<table class="admin-table-b keeptable">
	<tr>
		<th colspan="2">The following devices are registered to receive notifications for store sales</th>
	</tr>
<?php	while($rs=ect_fetch_assoc($result)){ ?>
	<tr>
		<td><?php print substr($rs['dnID'],0,20).'...'?></td>
		<td><input type="button" value="Remove Device Registration" onclick="removenotification('<?php print jsescape($rs['dnID'])?>')"></td>
	</tr>
<?php
		} ?>
</table>
</form>
<?php
	}
	ect_free_result($result);
}elseif(getpost('updatestatus')=='1' || getpost('act')=='abandoned' || getpost('act')=='oneabandoned'){
?>
		<form id="searchparamsform" method="post" action="adminorders.php">
<?php		writesearchparams(); ?>
<?php
	if($haschangedonotherdevice){
		$yyClkHer="Please click here to view orders";
?>
	<div style="text-align:center;padding:30px;font-weight:bold"><span class="ectred">WARNING:</span> The status updates were not saved as this order has just been updated on another device.</div>
	<div style="text-align:center;padding:30px">To view the updated status of this order please <a href="adminorders.php?id=<?php print getpost("orderid")?>">click here</a>.</div>
<?php	}else{ ?>
			<div style="text-align:center;padding:30px;font-weight:bold"><?php print $yyUpdSuc?></div>
			<div style="text-align:center;padding:30px"><?php print $yyNowFrd?></div>
            <div style="text-align:center;padding:30px"><?php print $yyNoAuto?></div>
<?php	} ?>
			<div style="text-align:center;padding-bottom:30px"><input type="submit" value="<?php print $yyClkHer?>"></div>
		</form>
<?php
	if(! $haschangedonotherdevice){ ?>
<script>
setTimeout('document.getElementById("searchparamsform").submit()', 500);
</script>
<?php
	}
}elseif(getpost('doedit')=='true'){
	$OWSP='';
	$orderid=getpost('orderid');
	$ordstatus=(int)getpost('ordStatus');
	$ordShipping=getNumericField("ordShipping");
	$ordHandling=getNumericField("ordHandling");
	$ordDiscount=getNumericField("ordDiscount");
	$ordStateTax=getNumericField("ordStateTax");
	$ordCountryTax=getNumericField("ordCountryTax");
	$oldordstatus=0;
	$oldordtotal=0;
	$oldstatetax=0;
	$oldshipping=0;
	$oldhandling=0;
	$olddiscount=0;
	$oldordzip="";
	$oldordshipzip="";
	$avalaraentityuse="";
	$clientactions=0;
	$sSQL="SELECT clID,clUserName,clActions,clLoginLevel,clPercentDiscount,avalaraentityuse FROM customerlogin WHERE clEmail='" . escape_string(getpost("email")) . "'";
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		$clientactions=$rs['clActions'];
		$avalaraentityuse=$rs['avalaraentityuse'];
	}
	ect_free_result($result);
	$ordComLoc=0;
	$thecustomerid=0;
	if($orderid!='new'){
		$sSQL="SELECT ordSessionID,ordClientID,ordAuthStatus,ordShipType,loyaltyPoints,ordStatus,ordTotal,ordZip,ordShipZip,ordShipping,ordHandling,ordDiscount,ordStateTax,ordDate FROM orders WHERE ordID='" . $orderid . "'";
		$result=ect_query($sSQL) or ect_error();
		$rs=ect_fetch_assoc($result);
		$thesessionid=$rs['ordSessionID'];
		$thecustomerid=$rs['ordClientID'];
		$loyaltypointtotal=$rs['loyaltyPoints'];
		$oldordstatus=$rs['ordStatus'];
		$oldordtotal=$rs['ordTotal'];
		$oldstatetax=$rs['ordStateTax'];
		$oldshipping=$rs['ordShipping'];
		$oldhandling=$rs['ordHandling'];
		$olddiscount=$rs['ordDiscount'];
		$oldordzip=$rs['ordZip'];
		$oldordshipzip=$rs['ordShipZip'];
		$orddate=$rs['ordDate'];
		ect_free_result($result);
		if($oldordstatus>=2&&getpost('updatestock')=='ON') release_stock($orderid);
		if($thecustomerid!=0 && @$loyaltypoints!='' && $loyaltypointtotal!=0 && $oldordstatus>=3) ect_query('UPDATE customerlogin SET loyaltyPoints=loyaltyPoints-' . $loyaltypointtotal . ' WHERE clID=' . $thecustomerid) or ect_error();
		if($rs['ordAuthStatus']=='MODWARNOPEN' || is_null($rs['ordAuthStatus'])) ect_query("UPDATE orders SET ordAuthStatus='' WHERE ordID='" . $orderid . "'") or ect_error();
		if($rs['ordShipType']=='MODWARNOPEN' || is_null($rs['ordShipType'])) ect_query("UPDATE orders SET ordShipType='' WHERE ordID='" . $orderid . "'") or ect_error();
	}else
		$orddate=date('Y-m-d H:i:s', time() + ($GLOBALS['dateadjust']*60*60));
	if(getpost('commercialloc')=='Y') $ordComLoc=1;
	if(getpost('wantinsurance')=='Y') $ordComLoc+=2;
	if(getpost('saturdaydelivery')=='Y') $ordComLoc+=4;
	if(getpost('signaturerelease')=='Y') $ordComLoc+=8;
	if(getpost('insidedelivery')=='Y') $ordComLoc+=16;
	if(getpost('custid')!='' && is_numeric(getpost('custid')))
		$thecustomerid=getpost('custid');
	if(getpost('doeditdate')=='1'){
		$orddate=date('Y-m-d',parsedate(getpost('editorddate'))) . ' ' . getpost('editordtime');
	}
	$ordcountry=$ordshipcountry='';
	if(is_numeric(getpost('country'))){
		$sSQL="SELECT countryName FROM countries WHERE countryID='" . escape_string(getpost('country')) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)) $ordcountry=$rs['countryName'];
		ect_free_result($result);
	}
	if(is_numeric(getpost('scountry'))){
		$sSQL="SELECT countryName FROM countries WHERE countryID='" . escape_string(getpost('scountry')) . "'";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)) $ordshipcountry=$rs['countryName'];
		ect_free_result($result);
	}
	if(@$GLOBALS['avalarastate']!=0){
		if(($clientactions & 1)==1)
			$ordStateTax=0;
		else
			$ordStateTax=$oldstatetax;
	}
	if($orderid=='new'){
		$thesessionid='A1';
		$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,ordTransID,ordShipping,ordStateTax,ordCountryTax,ordHSTTax,ordLang,ordHandling,ordShipType,ordShipCarrier,loyaltyPoints,ordTotal,ordDate,ordStatusInfo,ordPrivateStatus,ordStatus,ordAuthStatus,ordStatusDate,ordComLoc,ordIP,ordAffiliate,ordExtra1,ordExtra2,ordShipExtra1,ordShipExtra2,ordCheckoutExtra1,ordCheckoutExtra2,ordDiscount,ordDiscountText,ordInvoice,ordAddInfo) VALUES (';
		$sSQL.="'".$thesessionid."',";
		$sSQL.="'".$thecustomerid."',";
		$sSQL.="'" . escape_string(getpost('name')) . "',";
		$sSQL.="'" . escape_string(getpost('lastname')) . "',";
		$sSQL.="'" . escape_string(getpost('address')) . "',";
		$sSQL.="'" . escape_string(getpost('address2')) . "',";
		$sSQL.="'" . escape_string(getpost('city')) . "',";
		$sSQL.="'" . escape_string(getpost('state')) . "',";
		$sSQL.="'" . escape_string(getpost('zip')) . "',";
		$sSQL.="'" . escape_string($ordcountry) . "',";
		$sSQL.="'" . escape_string(getpost('email')) . "',";
		$sSQL.="'" . escape_string(getpost('phone')) . "',";
		$sSQL.="'" . escape_string(getpost('sname')) . "',";
		$sSQL.="'" . escape_string(getpost('slastname')) . "',";
		$sSQL.="'" . escape_string(getpost('saddress')) . "',";
		$sSQL.="'" . escape_string(getpost('saddress2')) . "',";
		$sSQL.="'" . escape_string(getpost('scity')) . "',";
		$sSQL.="'" . escape_string(getpost('sstate')) . "',";
		$sSQL.="'" . escape_string(getpost('szip')) . "',";
		$sSQL.="'" . escape_string($ordshipcountry) . "',";
		$sSQL.="'" . escape_string(getpost('sphone')) . "',";
		$sSQL.="'4',"; // ordPayProvider
		$sSQL.="'" . escape_string(getpost('ordAuthNumber')) . "',";
		$sSQL.="'" . escape_string(getpost('ordTransID')) . "',";
		$sSQL.="'" . escape_string(getpost('ordShipping')) . "',";
		$sSQL.="'" . escape_string($ordStateTax) . "',";
		$sSQL.="'" . escape_string($ordCountryTax) . "',";
		if($origCountryID==2) $sSQL.="'" . escape_string(getpost('ordHSTTax')) . "',"; else $sSQL.="'0',";
		$sSQL.="'" . (is_numeric(getpost('ordlang'))?getpost('ordlang'):0) . "',";
		$sSQL.="'" . escape_string(getpost('ordHandling')) . "',";
		$sSQL.="'" . escape_string(getpost('shipmethod')) . "',";
		$sSQL.="'" . escape_string(getpost('shipcarrier')) . "',";
		$sSQL.="'" . getNumericField('loyaltyPoints') . "',";
		$sSQL.="'" . escape_string(getpost('ordtotal')) . "',";
		$sSQL.="'" . escape_string($orddate) . "',";
		$sSQL.="'" . escape_string(getpost('ordStatusInfo')) . "',";
		$sSQL.="'" . escape_string(getpost('ordPrivateStatus')) . "',";
		$sSQL.="'" . escape_string($ordstatus) . "',";
		$sSQL.="'',"; // ordAuthStatus
		$sSQL.="'" . date("Y-m-d H:i:s", time() + ($GLOBALS['dateadjust']*60*60)) . "',";
		$sSQL.="'" . $ordComLoc . "',";
		$sSQL.="'" . escape_string(getpost('ipaddress')) . "',";
		$sSQL.="'" . getpost('PARTNER') . "',";
		$sSQL.="'" . escape_string(getpost('extra1')) . "',";
		$sSQL.="'" . escape_string(getpost('extra2')) . "',";
		$sSQL.="'" . escape_string(getpost('shipextra1')) . "',";
		$sSQL.="'" . escape_string(getpost('shipextra2')) . "',";
		$sSQL.="'" . escape_string(getpost('checkoutextra1')) . "',";
		$sSQL.="'" . escape_string(getpost('checkoutextra2')) . "',";
		$sSQL.="'" . escape_string(getpost('ordDiscount')) . "',";
		$sSQL.="'" . escape_string(str_replace(array("\n","\r"),array('<br>',''),getpost('discounttext'))) . "',";
		$sSQL.="'" . escape_string(getpost('ordInvoice')) . "',";
		$sSQL.="'" . escape_string(getpost('ordAddInfo')) . "')";
		ect_query($sSQL) or ect_error();
		$orderid=ect_insert_id();
	}else{
		$sSQL="UPDATE orders SET ";
		$sSQL.="ordName='" . escape_string(getpost('name')) . "',";
		$sSQL.="ordLastName='" . escape_string(getpost('lastname')) . "',";
		$sSQL.="ordAddress='" . escape_string(getpost('address')) . "',";
		$sSQL.="ordAddress2='" . escape_string(getpost('address2')) . "',";
		$sSQL.="ordCity='" . escape_string(getpost('city')) . "',";
		$sSQL.="ordState='" . escape_string(getpost('state')) . "',";
		$sSQL.="ordZip='" . escape_string(getpost('zip')) . "',";
		$sSQL.="ordCountry='" . escape_string($ordcountry) . "',";
		$sSQL.="ordEmail='" . escape_string(getpost('email')) . "',";
		$sSQL.="ordPhone='" . escape_string(getpost('phone')) . "',";
		$sSQL.="ordShipName='" . escape_string(getpost('sname')) . "',";
		$sSQL.="ordShipLastName='" . escape_string(getpost('slastname')) . "',";
		$sSQL.="ordShipAddress='" . escape_string(getpost('saddress')) . "',";
		$sSQL.="ordShipAddress2='" . escape_string(getpost('saddress2')) . "',";
		$sSQL.="ordShipCity='" . escape_string(getpost('scity')) . "',";
		$sSQL.="ordShipState='" . escape_string(getpost('sstate')) . "',";
		$sSQL.="ordShipZip='" . escape_string(getpost('szip')) . "',";
		$sSQL.="ordShipCountry='" . escape_string($ordshipcountry) . "',";
		$sSQL.="ordShipPhone='" . escape_string(getpost('sphone')) . "',";
		$sSQL.="ordShipType='" . escape_string(getpost('shipmethod')) . "',";
		$sSQL.="ordShipCarrier='" . escape_string(getpost('shipcarrier')) . "',";
		$sSQL.="ordIP='" . escape_string(getpost('ipaddress')) . "',";
		$sSQL.="ordComLoc=" . $ordComLoc . ",";
		$sSQL.="ordAffiliate='" . getpost('PARTNER') . "',";
		$sSQL.="ordAddInfo='" . escape_string(getpost('ordAddInfo')) . "',";
		$sSQL.="ordStatusInfo='" . escape_string(getpost('ordStatusInfo')) . "',";
		$sSQL.="ordPrivateStatus='" . escape_string(getpost('ordPrivateStatus')) . "',";
		$sSQL.="ordStatus='" . escape_string($ordstatus) . "',";
		if(getpost('doeditdate')=='1') $sSQL.="ordDate='" . escape_string($orddate) . "',";
		$sSQL.="ordTrackNum='" . escape_string(getpost('ordTrackNum')) . "',";
		$sSQL.="ordDiscountText='" . escape_string(str_replace(array("\n","\r"),array('<br>',''),getpost('discounttext'))) . "',";
		$sSQL.="ordInvoice='" . escape_string(getpost('ordInvoice')) . "',";
		$sSQL.="ordExtra1='" . escape_string(getpost('extra1')) . "',";
		$sSQL.="ordExtra2='" . escape_string(getpost('extra2')) . "',";
		$sSQL.="ordShipExtra1='" . escape_string(getpost('shipextra1')) . "',";
		$sSQL.="ordShipExtra2='" . escape_string(getpost('shipextra2')) . "',";
		$sSQL.="ordCheckoutExtra1='" . escape_string(getpost('checkoutextra1')) . "',";
		$sSQL.="ordCheckoutExtra2='" . escape_string(getpost('checkoutextra2')) . "',";
		$sSQL.="ordShipping='" . escape_string(getpost('ordShipping')) . "',";
		$sSQL.="ordStateTax='" . escape_string($ordStateTax) . "',";
		$sSQL.="ordCountryTax='" . escape_string($ordCountryTax) . "',";
		if($origCountryID==2) $sSQL.="ordHSTTax='" . escape_string(getpost('ordHSTTax')) . "',";
		$sSQL.="ordDiscount='" . escape_string(getpost('ordDiscount')) . "',";
		$sSQL.="ordHandling='" . escape_string(getpost('ordHandling')) . "',";
		$ordauthnumber=getpost('ordAuthNumber');
		if((int)getpost('ordStatus')>2 && $ordauthnumber=='') $ordauthnumber='manual auth';
		$sSQL.="ordAuthNumber='" . escape_string($ordauthnumber) . "',";
		$sSQL.="ordTransID='" . escape_string(getpost('ordTransID')) . "',";
		$sSQL.="loyaltyPoints='" . getNumericField('loyaltyPoints') . "',";
		$sSQL.="ordTotal='" . escape_string(getpost('ordtotal')) . "'";
		$sSQL.=" WHERE ordID='" . getpost('orderid') . "'";
		ect_query($sSQL) or ect_error();
	}
	if($ordstatus>2) ect_query("UPDATE giftcertificate SET gcAuthorized=1 WHERE gcOrderID=" . $orderid) or ect_error();
	if($ordstatus<=2) ect_query("UPDATE giftcertificate SET gcAuthorized=0 WHERE gcOrderID=" . $orderid) or ect_error();
	if($thecustomerid!=0 && @$loyaltypoints!='' && $ordstatus>=3) ect_query('UPDATE customerlogin SET loyaltyPoints=loyaltyPoints+' . getNumericField('loyaltyPoints') . ' WHERE clID=' . $thecustomerid) or ect_error();
	foreach($_POST as $objItem => $objValue){
		if(substr($objItem,0,6)=='prodid'){
			$idno=(int)substr($objItem, 6);
			$cartid=getpost('cartid' . $idno);
			$prodid=getpost('prodid' . $idno);
			$quant=getpost('quant' . $idno);
			if(! is_numeric($quant)) $quant=1;
			$theprice=getpost('price' . $idno);
			if(! is_numeric($theprice)) $theprice=0;
			$prodname=getpost('prodname' . $idno);
			$delitem=getpost('del_' . $idno);
			$sSQL="SELECT pWeight FROM products WHERE pID='".escape_string($prodid)."'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)) $thepweight=$rs['pWeight']; else $thepweight=0;
			ect_free_result($result);
			if($delitem=='yes' || ($cartid!='' && trim_($prodid)=='')){
				ect_query("DELETE FROM cart WHERE cartID=" . $cartid) or ect_error();
				ect_query("DELETE FROM cartoptions WHERE coCartID=" . $cartid) or ect_error();
				$cartid='';
			}elseif($cartid!=''){
				$sSQL="UPDATE cart SET cartProdID='" . escape_string($prodid) . "',cartProdPrice=" . $theprice . ",cartProdName='" . escape_string($prodname) . "',cartQuantity=" . $quant . ",cartCompleted=0 WHERE cartID=" . $cartid;
				ect_query($sSQL) or ect_error();
				ect_query("DELETE FROM cartoptions WHERE coCartID=" . $cartid) or ect_error();
			}else{
				$sSQL='INSERT INTO cart (cartSessionID,cartClientID,cartProdID,cartQuantity,cartCompleted,cartProdName,cartProdPrice,cartOrderID,cartDateAdded) VALUES (';
				$sSQL.="'" . $thesessionid . "','" . $thecustomerid . "','" . escape_string($prodid) . "',";
				$sSQL.=$quant . ",0,'" . escape_string($prodname) . "','" . $theprice . "'," . $orderid . ",";
				$sSQL.="'" . escape_string($orddate) . "')";
				ect_query($sSQL) or ect_error();
				$cartid=ect_insert_id();
			}
			if($cartid!=''){
				if($ordstatus!=2) ect_query("UPDATE cart SET cartCompleted=1 WHERE cartID=".$cartid) or ect_error();
				$optprefix="optn" . $idno . '_';
				$prefixlen=strlen($optprefix);
				foreach($_POST as $kk => $kkval){
					if(substr($kk,0,$prefixlen)==$optprefix && trim_($kkval)!=''){
						$optidarr=explode('|', $kkval);
						$optid=$optidarr[0];
						if(@$_POST['v' . $kk]==""){
							$sSQL='SELECT optID,'.getlangid('optGrpName',16).','.getlangid('optName',32).',' . $OWSP . "optPriceDiff,optWeightDiff,optType,optFlags FROM options LEFT JOIN optiongroup ON options.optGroup=optiongroup.optGrpID WHERE optID='" . escape_string($kkval) . "'";
							$result=ect_query($sSQL) or ect_error();
							if($rs=ect_fetch_assoc($result)){
								if(abs($rs['optType'])!=3){
									$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)]) . "',";
									$sSQL.=$optidarr[1] . ',';
									if(($rs['optFlags']&2)==0) $sSQL.=$rs['optWeightDiff'] . ')'; else $sSQL.=(($thepweight*$rs['optWeightDiff'])/100.0) . ')';
								}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 FROM options LEFT JOIN optiongroup ON options.optGroup=optiongroup.optGrpID WHERE optID='" . escape_string($kkval) . "'";
							$result=ect_query($sSQL) or ect_error();
							if($rs=ect_fetch_assoc($result)){
								$theopttoadd=getpost('v' . $kk);
								$optPriceDiff=($rs['optTxtCharge']<0&&$theopttoadd!=''?abs($rs['optTxtCharge']):$rs['optTxtCharge']*strlen($theopttoadd));
								$optmultiply=0;
								if($rs['optMultiply']!=0){
									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(getpost('v' . $kk)) . "',".$optPriceDiff.',0,' . $rs['optMultiply'] . ')';
								ect_query($sSQL) or ect_error();
							}
							ect_free_result($result);
						}
					}
				}
			}
		}
	}
	if($ordstatus>=2&&getpost('updatestock')=='ON') stock_subtract($orderid); ?>
			<form id="searchparamsform" method="post" action="adminorders.php<?php if(getget('view')=='true') print '?id=' . getpost('orderid') ?>">
<?php		writesearchparams();
			if(getpost('orderid')!='new') writehiddenvar('ctrlmod', 2); ?>
			<div style="text-align:center;padding:30px;font-weight:bold"><?php print $yyUpdSuc?></div>
			<div style="text-align:center;padding:30px"><?php print $yyNowFrd?></div>
            <div style="text-align:center;padding:30px"><?php print $yyNoAuto?></div>
			<div style="text-align:center;padding-bottom:30px"><input type="submit" value="<?php print $yyClkHer?>"></div>
			</form>
<script>
setTimeout('document.getElementById("searchparamsform").submit()', 500);
</script>
<?php
	if(@$GLOBALS['avalarastate']!=0){
		$addcomma="";
		if(getpost("szip")!=''){
			$destaddress=getpost("saddress");
			$destcity=getpost("scity");
			$deststate=getpost("sstate");
			$shipcountry=$ordshipcountry;
			$destzip=getpost("szip");
		}else{
			$destaddress=getpost("address");
			$destcity=getpost("city");
			$deststate=getpost("state");
			$shipcountry=$ordcountry;
			$destzip=getpost("zip");
		}
		if(($clientactions & 1)!=1 && (($oldordtotal+$oldshipping+$oldhandling+$olddiscount)!=(getNumericField("ordtotal")+$ordShipping+$ordHandling+$ordDiscount) || $oldordzip!=getpost("zip") || $oldordshipzip!=getpost("szip"))){
			$numtaxableitems=0;
			$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'];
			}
			ect_free_result($result);
			$avalarajson='{"lines": [';
			$sSQL="SELECT cartProdId,cartOrigProdId,cartProdName,cartProdPrice,cartQuantity,cartID,cartGiftWrap,pSKU,pTaxCode,pExemptions FROM cart LEFT JOIN products ON cart.cartProdId=products.pID WHERE cartOrderID='" . escape_string($orderid) . "' ORDER BY cartID";
			$result=ect_query($sSQL) or ect_error();
			while($rs=ect_fetch_assoc($result)){
				if(($rs['cartProdId']==$giftcertificateid || $rs['cartProdId']==$donationid) && is_null($rs['pExemptions'])) $rs['pExemptions']=15;
				if(($rs['pExemptions']&1)!=1){
					$theoptionspricediff=0;
					$sSQL="SELECT coPriceDiff 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'];
					}
					$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){
				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",strtotime($orddate)) . '",
					"customerCode":' . json_encode(getpost("email")) . ',
					"code":' . json_encode($orderid) . ',
					"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) . '}
					},
					' . (trim_($avalaraentityuse)!=''?'"entityUseCode":' . json_encode($avalaraentityuse) . ',':'') . '
					"commit":true,
					"currencyCode":"' . $GLOBALS['countryCurrency'] . '"}';
				avalaraheaders();		
				$avalarajson='{"adjustmentReason":"Other","adjustmentDescription":"Order Edit","createTransactionModel":' . $avalarajson . '}';
				if(callcurlfunction('https://' . (abs(@$GLOBALS['avalarastate'])!=2?'sandbox-':'') . 'rest.avatax.com/api/v2/transactions/createoradjust',$avalarajson,$jres,'',$errormsg,FALSE)){
					$jsarray=json_decode($jres);
					$ordStateTax=@$jsarray->{'totalTax'};
					$sSQL="UPDATE orders SET ordStateTax=" . $ordStateTax . " WHERE ordID=" . $orderid;
					ect_query($sSQL);
				}
				//print $avalarajson . "<hr>" . $jres . "<br>";
			}
		}
	}
}elseif(getget('id')!=''){
	if(getget('id')!='multi' && getget('id')!='new' && is_numeric(getget('id'))){
		print '<form method="post" action="adminclientlog.php" id="custacctform" target="custacct">';
		print '<input type="hidden" name="posted" value="1">';
		print '<input type="hidden" name="act" value="viewacct">';
		print '<input type="hidden" name="id" id="acctid">';
		print "</form>\n";
		print '<form method="post" action="adminorders.php" id="researchform">';
		writehiddenvar("fromdate", getpost("fromdate"));
		writehiddenvar("todate", getpost("todate"));
		writehiddenvar("notstatus", getpost("notstatus"));
		writehiddenvar("notsearchfield", getpost("notsearchfield"));
		writehiddenvar("searchtext", getpost("searchtext"));
		if(is_array(@$_POST['ordStatus'])){
			foreach(@$_POST['ordStatus'] as $key => $val)
				writehiddenvar('ordStatus[]', $val);
		}
		if(is_array(@$_POST['ordstate'])){
			foreach(@$_POST['ordstate'] as $key => $val)
				writehiddenvar('ordstate[]', $val);
		}
		if(is_array(@$_POST['ordcountry'])){
			foreach(@$_POST['ordcountry'] as $key => $val)
				writehiddenvar('ordcountry[]', $val);
		}
		if(is_array(@$_POST['payprovider'])){
			foreach(@$_POST['payprovider'] as $key => $val)
				writehiddenvar('payprovider[]', $val);
		}
		if(is_array(@$_POST['orddiscount'])){
			foreach(@$_POST['orddiscount'] as $key => $val)
				writehiddenvar('orddiscount[]', $val);
		}
		$hastodate=$hasfromdate=FALSE;
		$todate=getrequest("todate"); $fromdate=getrequest("fromdate");
		getdates();
		$origsearchtext=htmlspecials(getrequest("searchtext"));
		$sSQL="SELECT ordID FROM (orders INNER JOIN payprovider ON payprovider.payProvID=orders.ordPayProvider)";
		if($dropshipper!='')
			$sSQL.=" INNER JOIN cart ON orders.ordID=cart.cartOrderID INNER JOIN products ON cart.cartProdID=products.pID";
		elseif(@$_REQUEST['orddiscount']!='')
			$sSQL.=" INNER JOIN couponsapplied ON orders.ordID=couponsapplied.cpaOrdID";
		$whereSQL=$namesql='';
		getordsearchwheresql();
		$sSQL.=$whereSQL.' AND ordID<'.getget("id").' ORDER BY ordID DESC LIMIT 0,1';
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)) $previousbysearch=$rs['ordID']; else $previousbysearch='';
		ect_free_result($result);
		$sSQL="SELECT ordID FROM (orders INNER JOIN payprovider ON payprovider.payProvID=orders.ordPayProvider)";
		if($dropshipper!='')
			$sSQL.=" INNER JOIN cart ON orders.ordID=cart.cartOrderID INNER JOIN products ON cart.cartProdID=products.pID";
		elseif(@$_REQUEST['orddiscount']!='')
			$sSQL.=" INNER JOIN couponsapplied ON orders.ordID=couponsapplied.cpaOrdID";
		$whereSQL=$namesql='';
		getordsearchwheresql();
		$sSQL.=$whereSQL.' AND ordID>'.getget("id").' ORDER BY ordID ASC LIMIT 0,1';
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)) $nextbysearch=$rs['ordID']; else $nextbysearch='';
		ect_free_result($result);
		print '</form>';
	}
	if(getget('id')=='new')
		$idlist=array('0');
	elseif(getget('id')=='multi')
		$idlist=@$_POST['ids'];
	else
		$idlist=array(getget('id'));
	$numids=count($idlist);
	$numorders=0;
	if(! is_array($idlist)){
		print 'No id list specified<br>';
	}else foreach($idlist as $theid){
		$noloyaltypoints=$orderstatetaxexempt=$ordercountrytaxexempt=FALSE;
		$numids--;
		$allorders='';
		$statetaxrate=0;
		$countrytaxrate=0;
		$hsttaxrate=0;
		$countryorder=0;
		if(getget('id')=='new'){
			$alldata['ordStatus']=3; $alldata['ordAuthStatus']=''; $alldata['ordStatusDate']=time(); $alldata['ordID']=''; $alldata['ordName']=''; $alldata['ordLastName']=''; $alldata['ordAddress']=''; $alldata['ordAddress2']=''; $alldata['ordCity']=''; $alldata['ordState']=''; $alldata['ordZip']=''; $alldata['ordCountry']=''; $alldata['ordEmail']=''; $alldata['ordPhone']=''; $alldata['ordShipName']=''; $alldata['ordShipLastName']=''; $alldata['ordShipAddress']=''; $alldata['ordShipAddress2']=''; $alldata['ordShipCity']=''; $alldata['ordShipState']=''; $alldata['ordShipZip']=''; $alldata['ordShipCountry']=''; $alldata['ordShipPhone']=''; $alldata['ordPayProvider']=0; $alldata['ordAuthNumber']='manual auth'; $alldata['ordTransID']=''; $alldata['ordTotal']=0; $alldata['ordDate']=time(); $alldata['ordStateTax']=0; $alldata['ordCountryTax']=0; $alldata['ordShipping']=0; $alldata['ordShipType']=''; $alldata['ordShipCarrier']=0; $alldata['ordIP']=getipaddress(); $alldata['ordAffiliate']=''; $alldata['ordDiscount']=0; $alldata['ordDiscountText']=''; $alldata['ordHandling']=0; $alldata['ordComLoc']=0; $alldata['ordExtra1']=''; $alldata['ordExtra2']=''; $alldata['ordShipExtra1']=''; $alldata['ordShipExtra2']=''; $alldata['ordCheckoutExtra1']=''; $alldata['ordCheckoutExtra2']=''; $alldata['ordHSTTax']=0; $alldata['ordTrackNum']=''; $alldata['ordInvoice']=''; $alldata['ordClientID']=0; $alldata['ordReferer']=''; $alldata['ordUserAgent']=''; $alldata['loyaltyPoints']=''; $alldata['ordAddInfo']=''; $alldata['ordStatusInfo']=''; $alldata['ordPrivateStatus']='';
		}else{
			if(! is_numeric($theid)) $theid=-1;
			if(@$viewordersort=='') $viewordersort='cartID';
			if($isprinter && @$packingslipsort!='') $viewordersort=$packingslipsort;
			if($isinvoice && @$invoicesort!='') $viewordersort=$invoicesort;
			$sSQL="SELECT cartProdId,cartOrigProdID,cartProdName,cartProdPrice,cartQuantity,cartID,pStockByOpts,pExemptions,cartGiftWrap,cartGiftMessage,pWeight FROM cart LEFT JOIN products on cart.cartProdID=products.pId WHERE cartOrderID=" . $theid;
			if($dropshipper!='') $sSQL.=" AND pDropship=" . $dropshipper;
			$sSQL.=' ORDER BY ' . $viewordersort;
			$allorders=ect_query($sSQL) or ect_error();
			$numorders=ect_num_rows($allorders);
			$sSQL="SELECT ordID,ordStatus,ordAuthStatus,ordStatusDate,ordName,ordLastName,ordAddress,ordAddress2,ordCity,ordState,ordZip,ordCountry,ordEmail,ordPhone,ordShipName,ordShipLastName,ordShipAddress,ordShipAddress2,ordShipCity,ordShipState,ordShipZip,ordShipCountry,ordShipPhone,ordPayProvider,ordAuthNumber,ordTransID,ordTotal,ordDate,ordStateTax,ordCountryTax,ordHSTTax,ordShipping,ordShipType,ordShipCarrier,ordIP,ordAffiliate,ordDiscount,ordHandling,ordDiscountText,ordComLoc,ordExtra1,ordExtra2,ordShipExtra1,ordShipExtra2,ordCheckoutExtra1,ordCheckoutExtra2,ordAddInfo,ordTrackNum,ordInvoice,ordClientID,ordReferer,ordUserAgent,ordQuerystr,loyaltyPoints,ordLang,ordStatusInfo,ordPrivateStatus FROM orders LEFT JOIN payprovider ON payprovider.payProvID=orders.ordPayProvider WHERE ordID='" . escape_string($theid) . "'";
			$result=ect_query($sSQL) or ect_error();
			if($alldata=ect_fetch_assoc($result)){
				$alldata['ordDate']=strtotime($alldata['ordDate']);
				$alldata['ordStatusDate']=strtotime($alldata['ordStatusDate']);
			}else
				$alldata=array('ordID'=>0, 'ordStatus'=>0, 'ordAuthStatus'=>'', 'ordStatus'=>time(), 'ordName'=>'&nbsp;', 'ordLastName'=>'', 'ordAddress'=>'', 'ordAddress2'=>'', 'ordCity'=>'', 'ordState'=>'', 'ordZip'=>'', 'ordCountry'=>'', 'ordEmail'=>'', 'ordPhone'=>'', 'ordShipName'=>'', 'ordShipLastName'=>'', 'ordShipAddress'=>'', 'ordShipAddress2'=>'', 'ordShipCity'=>'', 'ordShipState'=>'', 'ordShipZip'=>'', 'ordShipCountry'=>'', 'ordShipPhone'=>'', 'ordPayProvider'=>0, 'ordAuthNumber'=>'', 'ordTransID'=>'', 'ordTotal'=>0, 'ordDate'=>0, 'ordStateTax'=>0, 'ordCountryTax'=>0, 'ordShipping'=>0, 'ordShipType'=>'', 'ordShipCarrier'=>0, 'ordIP'=>'', 'ordAffiliate'=>'', 'ordDiscount'=>0, 'ordDiscountText'=>'', 'ordHandling'=>0, 'ordComLoc'=>0, 'ordExtra1'=>'', 'ordExtra2'=>'', 'ordShipExtra1'=>'', 'ordShipExtra2'=>'', 'ordCheckoutExtra1'=>'', 'ordCheckoutExtra2'=>'', 'ordHSTTax'=>0, 'ordTrackNum'=>'', 'ordInvoice'=>'', 'ordClientID'=>0, 'ordReferer'=>'', 'ordUserAgent'=>'', 'ordQuerystr'=>'', 'loyaltyPoints'=>'', 'ordAddInfo'=>'', 'ordStatusInfo'=>'', 'ordPrivateStatus'=>'');
			ect_free_result($result);
			if($alldata['ordClientID']!=0){
				$sSQL="SELECT clActions FROM customerlogin WHERE clID=" . $alldata['ordClientID'];
				$result=ect_query($sSQL) or ect_error();
				if($rs=ect_fetch_assoc($result)){
					if(($rs['clActions'] & 1)==1) $orderstatetaxexempt=TRUE;
					if(($rs['clActions'] & 2)==2) $ordercountrytaxexempt=TRUE;
					if(@$GLOBALS['loyaltypointsnowholesale'] && ($rs['clActions'] & 8)==8) $noloyaltypoints=TRUE;
					if(@$GLOBALS['loyaltypointsnopercentdiscount'] && ($rs['clActions'] & 16)==16) $noloyaltypoints=TRUE;
				}
				ect_free_result($result);
			}
			if(getget('id')!='multi' && $dropshipper==''){ // previous and next id
				$sSQL="SELECT ordID FROM orders WHERE ordID<".$theid." ORDER BY ordID DESC LIMIT 0,1";
				$result2=ect_query($sSQL) or ect_error();
				if($rs=ect_fetch_assoc($result2)) $previousid=$rs['ordID'];
				ect_free_result($result2);
				$sSQL="SELECT ordID FROM orders WHERE ordID>".$theid." ORDER BY ordID LIMIT 0,1";
				$result2=ect_query($sSQL) or ect_error();
				if($rs=ect_fetch_assoc($result2)) $nextid=$rs['ordID'];
				ect_free_result($result2);
			}
		}
		if(getget("clone")=='true'){
			$ordDate=time();
			$ordAuthNumber='manual auth';
			$ordStatus=3;
			$ordStatusDate=time();
			$ordID='';
		}
		if($doedit){
			print '<form method="post" name="editform" id="editform" action="adminorders.php' . (getget('view')=='true'?'?view=true':'') . '" onsubmit="return confirmedit()"><input type="hidden" name="orderid" value="' . (getget("clone")=='true'?'new':getget('id')) . '"><input type="hidden" name="doedit" value="true">';
			$GLOBALS['currSymbolHTML']='';
			$GLOBALS['currPostAmount']=FALSE;
			$GLOBALS['currDecimalSep']=".";
			$GLOBALS['currThousandsSep']='';
		}
		if(! $isprinter){
?>
<script>
/* <![CDATA[ */
var newwin="";
var plinecnt=0;
var numcartitems=<?php print $numorders?>;
function popupaddress(isship){
	var tntry=document.getElementById('ord'+isship+'country').innerHTML;
	document.getElementById('addresstextarea').value='';
	if(document.getElementById('ord'+isship+'extra1')&&document.getElementById('ord'+isship+'extra1').innerHTML!='')document.getElementById('addresstextarea').value+=document.getElementById('ord'+isship+'extra1').innerHTML + "\r\n";
	document.getElementById('addresstextarea').value+=document.getElementById('ord'+isship+'name').innerHTML + "\r\n" +
				document.getElementById('ord'+isship+'address').innerHTML + "\r\n";
	if(document.getElementById('ord'+isship+'address2')&&document.getElementById('ord'+isship+'address2').innerHTML!='')document.getElementById('addresstextarea').value+=document.getElementById('ord'+isship+'address2').innerHTML + "\r\n";
	if(document.getElementById('ord'+isship+'city').innerHTML!='')document.getElementById('addresstextarea').value+=document.getElementById('ord'+isship+'city').innerHTML + ", ";
	document.getElementById('addresstextarea').value+=document.getElementById('ord'+isship+'state').innerHTML + " " + document.getElementById('ord'+isship+'zip').innerHTML + ((tntry!='USA'&&tntry!='United States of America'&&tntry!='United States')<?php if($origCountryID!=1)print '||true'?>?"\r\n" + tntry:'');
	document.getElementById('addressdiv').style.display='block';
	document.getElementById('addresstextarea').select();
}
var fuajaxobj;
function doneexecuteemail(){
	if(fuajaxobj.readyState==4){
		if(fuajaxobj.status==200){
			var restxt=fuajaxobj.responseText;
			document.getElementById('ectsoftwrapper').innerHTML=restxt;
		}
	}
}
function executeemailpopup(){
	var postdata='posted=1' +
		'&id=<?php print $alldata['ordID']?>' +
		'&customer=' + (document.getElementById('customer').checked?1:0) +
		'&affiliate=' + (document.getElementById('affiliate').checked?1:0) +
		'&manufacturer=' + (document.getElementById('manufacturer').checked?1:0) +
		'&store=' + (document.getElementById('store').checked?1:0);
	document.getElementById('ectsoftwrapper').innerHTML='<img src="adminimages/preloader.gif" alt="" style="margin:100px 0" class="ectpreloader">';
	fuajaxobj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
	fuajaxobj.onreadystatechange=doneexecuteemail;
	fuajaxobj.open("POST",'popupemail.php',true);
	fuajaxobj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	fuajaxobj.send(postdata);
}
function openemailpopup(id){
<?php if(trim_($alldata['ordEmail'])=='' || strpos(trim_($alldata['ordEmail']),'@')===FALSE){ ?>
	alert("There is no valid email set.");
<?php }else{ ?>
	var eajaxobj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
	document.getElementById('preloaderdiv').style.display='';
	eajaxobj.open("GET",'popupemail.php?id='+id,false);
	eajaxobj.send(null);
	document.getElementById('preloaderdiv').innerHTML=eajaxobj.responseText;
<?php } ?>
}
function uaajaxcallback(){
	if(ajaxobj.readyState==4){
		var restxt=ajaxobj.responseText;
		resarr=restxt.split('==LISTELM==');
		if(resarr.length>0){
			document.getElementById("custid").value=resarr[0];
			document.getElementById("name").value=resarr[1];
<?php	if(@$GLOBALS['usefirstlastname']) print 'document.getElementById("lastname").value=resarr[2];' . "\r\n" ?>
		}
		if(resarr.length>5){
			document.getElementById("address").value=resarr[3];
<?php	if(@$useaddressline2) print 'document.getElementById("address2").value=resarr[4];' . "\r\n" ?>
			document.getElementById("city").value=resarr[5];
			document.getElementById("state").value=resarr[6];
			document.getElementById("zip").value=resarr[7];
			cntry=document.getElementById("country");
			cntxt=resarr[8];
			for(index=0; index<cntry.length; index++){
				if(cntry.options[index].text==cntxt||cntry.options[index].value==cntxt){
					cntry.selectedIndex=index;
				}
			}
			document.getElementById("phone").value=resarr[9];
<?php
	if(trim_(@$extraorderfield1)!='') print 'document.getElementById("extra1").value=resarr[10];' . "\r\n";
	if(trim_(@$extraorderfield2)!='') print 'document.getElementById("extra2").value=resarr[11];' . "\r\n" ?>
			setstatetax();
			setcountrytax();
		}
	}
}
function updateaddress(id){
	document.getElementById('percdisc').value=(adiscnts[id][1]=='1'?adiscnts[id][2]:'');
	document.getElementById('wholesaledisc').checked=(adiscnts[id][0]=='1');
	ajaxobj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
	ajaxobj.onreadystatechange=uaajaxcallback;
	ajaxobj.open("POST", "ajaxservice.php?action=getlist&listtype=adddets", true);
	ajaxobj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	ajaxobj.send('listtext='+adds[id]);
}
function upajaxcallback(){
	if(ajaxobj.readyState==4){
		var restxt=ajaxobj.responseText.replace(/^\s+|\s+$/g,"");
		resarr=restxt.split('==LISTELM==');
		document.getElementById('optionsspan'+resarr[0]).innerHTML=resarr[1];
		try{eval(resarr[2]);}catch(err){document.getElementById('optionsspan'+resarr[0]).innerHTML='javascript error'}
	}
}
function updateoptions(id){
	prodid=document.getElementById('prodid'+id).value;
	if(prodid!=''){
		ajaxobj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
		ajaxobj.onreadystatechange=upajaxcallback;
		ajaxobj.open("POST", 'ajaxservice.php?action=updateoptions&index='+id+'&wsp='+(document.getElementById('wholesaledisc').checked?'1':'0')+'&perc='+document.getElementById('percdisc').value.replace(/[^0-9\.]/g, ''), true);
		ajaxobj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		ajaxobj.send('productid='+prodid);
	}
	return(false);
}
function extraproduct(plusminus){
	var thetable=document.getElementById('producttable');
if(plusminus=='+'){
	numcartitems++;
	var node=document.createElement("DIV");
	node.className='ectorderrow';
	thetable.appendChild(node);
	
	var subnode=document.createElement("DIV");
	subnode.innerHTML='<div class="smallscreenquant"><input id="smallquant'+(plinecnt+1000)+'" size="3" onkeyup="document.getElementById(\'quant'+(plinecnt+1000)+'\').value=this.value" onchange="dorecalc(true)" type="text"> x </div>' +
		'<input type="button" value="..." onclick="updateoptions('+(plinecnt+1000)+')">&nbsp;<input name="prodid'+(plinecnt+1000)+'" size="18" id="prodid'+(plinecnt+1000)+'" AUTOCOMPLETE="off" onkeydown="return combokey(this,event)" onkeyup="combochange(this,event)"><input type="hidden" id="stateexempt'+(plinecnt+1000)+'" value="false"><input type="hidden" id="countryexempt'+(plinecnt+1000)+'" value="false">' +
		'<?php print jsescapel(showgetoptionsselect('xxxx'))?>'.replace(/xxxx/,'selectprodid'+(plinecnt+1000));
	node.appendChild(subnode);
	
	var subnode=document.createElement("DIV");
	subnode.innerHTML='<input type="text" id="prodname'+(plinecnt+1000)+'" name="prodname'+(plinecnt+1000)+'" size="24" AUTOCOMPLETE="off" onkeydown="return combokey(this,event)" onkeyup="combochange(this,event)">' +
		'<?php print jsescapel(showgetoptionsselect('xxxx'))?>'.replace(/xxxx/,'selectprodname'+(plinecnt+1000));
	node.appendChild(subnode);

	var subnode=document.createElement("DIV");
	subnode.innerHTML='<div id="optionsspan'+(plinecnt+1000)+'"><div style="text-align:center">-</div></div>';
	node.appendChild(subnode);

	var subnode=document.createElement("DIV");
	subnode.innerHTML='<div class="largescreenquant"><input type="text" id="quant'+(plinecnt+1000)+'" name="quant'+(plinecnt+1000)+'" size="5" onkeyup=""document.getElementById(\'smallquant'+(plinecnt+1000)+'\').value=this.value"" value="1"></div>';
	node.appendChild(subnode);

	var subnode=document.createElement("DIV");
	subnode.innerHTML='<input type="text" class="orderprice" id="price'+(plinecnt+1000)+'" name="price'+(plinecnt+1000)+'" value="0" size="7"><br><input type="hidden" id="optdiffspan'+(plinecnt+1000)+'" value="0">';
	node.appendChild(subnode);

	var subnode=document.createElement("DIV");
	subnode.innerHTML='&nbsp;';
	node.appendChild(subnode);

	plinecnt++;
}else{
	if(plinecnt>0){
	thetable.removeChild(thetable.lastChild);
	plinecnt--;
	numcartitems--;
	}
}
}
function confirmedit(){
<?php
	if($GLOBALS['useStockManagement']){ ?>
var stockwarn="The following items do not have sufficient stock\n\n";
var outstock=false;
var oostock=new Array();
var oostockqnt=new Array();
var inputs=document.forms['editform'].getElementsByTagName("input");
for(ceindex=0;ceindex<inputs.length;ceindex++){
	var thename=inputs[ceindex].name;
	if(thename.substr(0,5)=="quant"){
		var theid=thename.substr(5);
		delbutton=document.getElementById("del_"+theid);
		if(delbutton==null)
			isdeleted=false;
		else
			isdeleted=delbutton.checked;
		if(! isdeleted){
			var pid=document.getElementById("prodid"+theid).value;
			var stocklevel=stock['pid_' + pid];
			var quant=document.getElementById("quant"+theid).value
			if(typeof(stocklevel)=="undefined"){
				// Do nothing, pid not defined.
			}else if(stocklevel=="bo"){ // By Options
				for(var ii in document.forms.editform){
					var opttext="optn"+theid+"_";
					if(ii.substr(0,opttext.length)==opttext){
						theitem=document.getElementById(ii);
						if(document.getElementById('v'+ii)==null){
							thevalue=theitem[theitem.selectedIndex].value.split('|')[0];
							stocklevel=stock['oid_'+thevalue];
							if(typeof(oostockqnt['oid_'+thevalue])=="undefined")
								oostockqnt['oid_'+thevalue]=parseInt(quant);
							else
								oostockqnt['oid_'+thevalue]+=parseInt(quant);
							if(parseInt(stocklevel)<oostockqnt['oid_'+thevalue]){
								oostock['oid_'+thevalue]=document.getElementById("prodname"+theid).value + " (" + theitem[theitem.selectedIndex].text + ") : Required " + oostockqnt['oid_'+thevalue] + " available ";
							}
						}
					}
				}
			}else{
				if(typeof(oostockqnt['pid_' + pid])=="undefined")
					oostockqnt['pid_' + pid]=parseInt(quant);
				else
					oostockqnt['pid_' + pid]+=parseInt(quant);
				if(parseInt(stocklevel)<oostockqnt['pid_' + pid]){
					oostock['pid_' + pid]=document.getElementById("prodname"+theid).value + ": Required " + oostockqnt['pid_' + pid] + " available ";
				}
			}
		}
	}
}
for(var i in oostock){
	outstock=true;
	stockwarn+=oostock[i] + stock[i] + "\n";
}
if(outstock){
	if(! confirm(stockwarn+"\nPress \"OK\" to submit changes or cancel to adjust quantities\n"))
		return(false);
}
<?php
	} ?>
if(confirm("<?php print jscheck($yyChkRec)?>"))
	return(true);
return(false);
}
function calcshipping(){
	var txturl='shipservice.php?';
	var editformelems=document.getElementById('editform').elements;
	for(var iix=0; iix<editformelems.length;iix++){
		var ii=editformelems[iix].name;
		if(ii.substr(0,6)=='prodid'){
			var theid=ii.substr(6);
			txturl+=ii+"="+editformelems[iix].value+"&";
			var thequant=parseInt(document.getElementById("quant"+theid).value);
			if(isNaN(thequant)) thequant=0;
			txturl+="quant"+theid+"="+thequant+"&";
			for(var iix2=0; iix2<editformelems.length;iix2++){
				var ii2=editformelems[iix2].name;
				var opttext="optn"+theid+"_";
				if(ii2.substr(0,opttext.length)==opttext){
					theitem=document.getElementById(ii2);
					if(document.getElementById('v'+ii2)==null){
						thevalue=theitem[theitem.selectedIndex].value;
						txturl+="optn"+theid+"_"+iix2+"="+thevalue.split('|')[0]+"&";
					}
				}
			}
		}
	}
	var isship=(document.getElementById('sstate').value!=''&&document.getElementById('szip').value!=''?'s':'');
	var shipstate=encodeURIComponent(document.getElementById(isship+'state').value);
	var shipzip=encodeURIComponent(document.getElementById(isship+'zip').value);
	var shipcountry=encodeURIComponent(document.getElementById(isship+'country').value);
	var comloc=document.getElementById('commercialloc')[document.getElementById('commercialloc').selectedIndex].value;
	var popupWin=window.open(txturl+"action=admincalc&destzip="+shipzip+"&sc="+shipcountry+"&sta="+shipstate+"&cl="+comloc,'calcshipping','menubar=no, scrollbars=yes, width=500, height=400, directories=no,location=no,resizable=yes,status=no,toolbar=no');
}
var opttxtcharge=[];
function dorecalc(onlytotal){
var thetotal=0,totoptdiff=0,statetaxabletotal=0,countrytaxabletotal=0;
for(var zz=0; zz < document.forms.editform.length; zz++){
var iq=document.forms.editform[zz].name;
if(iq.substr(0,5)=="quant"){
	theid=iq.substr(5);
	totopts=0;
	delbutton=document.getElementById("del_"+theid);
	if(delbutton==null)
		isdeleted=false;
	else
		isdeleted=delbutton.checked;
	if(! isdeleted){
		var editformelems=document.getElementById('editform').elements;
        for(var iix=0; iix<editformelems.length;iix++){
			var ii=editformelems[iix].name;
			var opttext="optn"+theid+"_";
			if(ii.substr(0,opttext.length)==opttext){
				theitem=document.getElementById(ii);
				if(document.getElementById('v'+ii)==null){
					thevalue=theitem[theitem.selectedIndex].value;
					if(thevalue.indexOf('|')>0){
						totopts+=parseFloat(thevalue.substr(thevalue.indexOf('|')+1));
					}
				}else{
					optid=parseInt(ii.substr(opttext.length));
					if(opttxtcharge[optid]){
						if(opttxtcharge[optid]>0){
							totopts+=opttxtcharge[optid]*document.getElementById('v'+ii).value.length;
						}else if(document.getElementById('v'+ii).value.length>0){
							totopts+=Math.abs(opttxtcharge[optid]);
						}
					}
				}
			}
		}
		thequant=parseInt(document.getElementById(iq).value);
		if(isNaN(thequant)) thequant=0;
		theprice=parseFloat(document.getElementById("price"+theid).value);
		if(isNaN(theprice)) theprice=0;
		document.getElementById("optdiffspan"+theid).value=totopts;
		optdiff=parseFloat(document.getElementById("optdiffspan"+theid).value);
		if(isNaN(optdiff)) optdiff=0;
		thetotal+=thequant * (theprice + optdiff);
		if(document.getElementById('orderstatetaxexempt').checked&&(!document.getElementById("stateexempt"+theid)||document.getElementById("stateexempt"+theid).value!='true'))
			statetaxabletotal+=thequant * (theprice + optdiff);
		if(document.getElementById('ordercountrytaxexempt').checked&&(!document.getElementById("countryexempt"+theid)||document.getElementById("countryexempt"+theid).value!='true'))
			countrytaxabletotal+=thequant * (theprice + optdiff);
		totoptdiff+=thequant * optdiff;
	}
}
}
document.getElementById("optdiffspan").innerHTML=totoptdiff.toFixed(2);
document.getElementById("ordtotal").value=thetotal.toFixed(2);
if(onlytotal==true) return;<?php
if($origCountryID==2) print "\r\nvar ssa=getshipstateabbrev();" ?>
statetaxrate=parseFloat(document.getElementById("staterate").value);
if(isNaN(statetaxrate)) statetaxrate=0;
var homecountrytaxrate=<?php print $homecountrytaxrate?>;
countrytaxrate=parseFloat(document.getElementById("countryrate").value);
if(isNaN(countrytaxrate)) countrytaxrate=0;
discount=parseFloat(document.getElementById("ordDiscount").value);
if(isNaN(discount)){
	discount=0;
	document.getElementById("ordDiscount").value=0;
}
statetaxtotal=(statetaxrate * Math.max(statetaxabletotal-discount,0)) / 100.0;
<?php if($showtaxinclusive==3){ ?>
countrytaxtotal=Math.round((countrytaxabletotal*100) / ((100+homecountrytaxrate)/homecountrytaxrate))/100.0;
thetotal-=countrytaxtotal;
document.getElementById("ordtotal").value=thetotal.toFixed(2);
if(countrytaxrate!=homecountrytaxrate&&homecountrytaxrate!=0)
	if(countrytaxrate!=0) countrytaxtotal=countrytaxtotal*(countrytaxrate/homecountrytaxrate); else countrytaxtotal=0;
<?php }else{ ?>
countrytaxtotal=(countrytaxrate * Math.max(countrytaxabletotal-discount,0)) / 100.0;
<?php } ?>
shipping=parseFloat(document.getElementById("ordShipping").value);
if(isNaN(shipping)){
	shipping=0;
	document.getElementById("ordShipping").value=0;
}
handling=parseFloat(document.getElementById("ordHandling").value);
if(isNaN(handling)){
	handling=0;
	document.getElementById("ordHandling").value=0;
}
<?php	if(@$taxShipping==2){ ?>
statetaxtotal+=(statetaxrate * shipping) / 100.0;
countrytaxtotal+=(countrytaxrate * shipping) / 100.0;
<?php	}
		if(@$taxHandling==2){ ?>
statetaxtotal+=(statetaxrate * handling) / 100.0;
countrytaxtotal+=(countrytaxrate * handling) / 100.0;
<?php	} ?>
var hsttax=0;
<?php	if($origCountryID==2){ ?>
	if(getshipcountry()=='canada'){
		if(ssa=="NB" || ssa=="NF" || ssa=="NS" || ssa=="ON" || ssa=="PE"){
			hsttax=statetaxtotal+countrytaxtotal;
			statetaxtotal=0;
			countrytaxtotal=0;
		}
	}
	document.getElementById("ordHSTTax").value=hsttax.toFixed(2);
<?php	} ?>
statetaxtotal=roundNumber(statetaxtotal,2);
countrytaxtotal=roundNumber(countrytaxtotal,2);
document.getElementById("ordStateTax").value=statetaxtotal.toFixed(2);
document.getElementById("ordCountryTax").value=countrytaxtotal.toFixed(2);
grandtotal=(thetotal + shipping + handling + statetaxtotal + countrytaxtotal + hsttax) - discount;
document.getElementById("grandtotalspan").innerHTML=grandtotal.toFixed(2);
<?php	if(@$loyaltypoints!=''){ ?>
	document.getElementById("loyaltyPoints").value=Math.round((thetotal.toFixed(2)-discount)*<?php print ($noloyaltypoints?0:$loyaltypoints)?>);
<?php	} ?>
}
function roundNumber(num, dec){
	var result=Math.round(Math.round(num * Math.pow(10, dec+1) ) / 10) / Math.pow(10,dec);
	return result;
}
function ppajaxcallback(){
	if(ajaxobj.readyState==4){
		document.getElementById("googleupdatespan").innerHTML=ajaxobj.responseText;
	}
}
function updategoogleorder(theprocessor,theact,ordid){
	if(theact=='settle') tmsg='Capture the amount of: '+document.getElementById("txamount").value; else tmsg='Inform '+theprocessor+' of change to order id '+ordid+'?';
	if(confirm(tmsg)){
		document.getElementById("googleupdatespan").innerHTML='';
		ajaxobj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
		ajaxobj.onreadystatechange=ppajaxcallback;
		extraparams='';
		if(theact=='ship'){
			shipcar=document.getElementById("shipcarrier");
			if(shipcar!= null){
				trackno=document.getElementById("ordTrackNum").value
				if(trackno!='' && confirm('Include tracking and carrier info?')){
					extraparams='&carrier='+(shipcar.options[shipcar.selectedIndex].value)+'&trackno='+document.getElementById("ordTrackNum").value;
				}
			}
		}
		if(document.getElementById("txamount")){
			extraparams+='&amount='+document.getElementById("txamount").value;
		}
		document.getElementById("googleupdatespan").innerHTML='Connecting...';
		ajaxobj.open("GET", "ajaxservice.php?processor="+theprocessor+"&gid="+ordid+"&act="+theact+extraparams, true);
		ajaxobj.send(null);
	}
}
function updatepaypalorder(theprocessor,ordid){
	if(confirm('Inform '+(theprocessor=='AuthNET'?'Authorize.net':'PayPal')+' of change to order id ' + ordid + "?")){
		document.getElementById("googleupdatespan").innerHTML='';
		ajaxobj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
		ajaxobj.onreadystatechange=ppajaxcallback;
		var additionalcapture=document.getElementById("additionalcapture")?document.getElementById("additionalcapture")[document.getElementById("additionalcapture").selectedIndex].value:0;
		var theact=document.getElementById("paypalaction")[document.getElementById("paypalaction").selectedIndex].value;
		document.getElementById("googleupdatespan").innerHTML='Connecting...';
		postdata="additionalcapture=" + additionalcapture + "&amount=" + encodeURIComponent(document.getElementById("captureamount").value) + (document.getElementById("buyernote")?"&comments=" + encodeURIComponent(document.getElementById("buyernote").value):'');
		if(document.getElementById('capstatus')) postdata+="&capstatus=" + document.getElementById('capstatus')[document.getElementById("capstatus").selectedIndex].value;
		ajaxobj.open("POST", "ajaxservice.php?processor="+theprocessor+"&gid="+ordid+"&act="+theact, true);
		ajaxobj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		ajaxobj.send(postdata);
	}
}
function squareajaxcallback(){
	if(ajaxobj.readyState==4){
		document.getElementById("googleupdatespan").innerHTML='<span style="color:#' + (ajaxobj.responseText=='Success' ? '0F0' : 'F00') + '">' + ajaxobj.responseText + '</span>';
	}
}
function updatesquareorder(ordid){
	if(confirm('Inform Square of change to order id ' + ordid + "?")){
		ajaxobj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
		ajaxobj.onreadystatechange=squareajaxcallback;
		document.getElementById("googleupdatespan").innerHTML='Connecting...';		
		postdata='amount='+document.getElementById("txamount").value;
		if(document.getElementById('capstatus')) postdata+="&capstatus=" + document.getElementById('capstatus')[document.getElementById("capstatus").selectedIndex].value;
		ajaxobj.open("POST", "ajaxservice.php?processor=squareup&gid="+ordid, true);
		ajaxobj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		ajaxobj.send(postdata);
	}
}
function setpaypalelements(){
	var theact=document.getElementById("paypalaction")[document.getElementById("paypalaction").selectedIndex].value;
	if(theact=='void'){
		if(document.getElementById("captureamounttxt"))
			document.getElementById("captureamounttxt").innerHTML='- :';
		document.getElementById("captureamount").disabled=true;
		document.getElementById("additionalcapture").disabled=true;
	}else if(theact=='reauth'){
		if(document.getElementById("captureamounttxt"))
			document.getElementById("captureamounttxt").innerHTML='Reauth Amount:';
		document.getElementById("captureamount").disabled=false;
		document.getElementById("additionalcapture").disabled=true;
	}else if(theact=='refund'){
		if(document.getElementById("captureamounttxt"))
			document.getElementById("captureamounttxt").innerHTML='Refund Amount:';
		document.getElementById("captureamount").disabled=false;
		document.getElementById("additionalcapture").disabled=true;
	}else{
		if(document.getElementById("captureamounttxt"))
			document.getElementById("captureamounttxt").innerHTML='Capture Amount:';
		document.getElementById("captureamount").disabled=false;
		document.getElementById("additionalcapture").disabled=false;
	}
}
function copybillingtoshipping(){
<?php	if(trim_(@$extraorderfield1)!='') print 'document.getElementById("shipextra1").value=document.getElementById("extra1").value;' ?>
	document.getElementById("sname").value=document.getElementById("name").value;
<?php	if(@$GLOBALS['usefirstlastname']) print 'document.getElementById("slastname").value=document.getElementById("lastname").value;' ?>
	document.getElementById("saddress").value=document.getElementById("address").value;
<?php	if(@$useaddressline2==TRUE) print 'document.getElementById("saddress2").value=document.getElementById("address2").value;' ?>
	document.getElementById("scity").value=document.getElementById("city").value;
	document.getElementById("sstate").value=document.getElementById("state").value;
	document.getElementById("szip").value=document.getElementById("zip").value;
	document.getElementById("scountry").selectedIndex=document.getElementById("country").selectedIndex;
	document.getElementById("sphone").value=document.getElementById("phone").value;
<?php	if(trim_(@$extraorderfield2)!='') print 'document.getElementById("shipextra2").value=document.getElementById("extra2").value;' ?>
}
<?php		if($doedit){ ?>
function setCookie(c_name,value,expiredays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
var adds=[];
var opensels=[];
var adiscnts=[];
document.getElementById('main').onclick=function(){
	for(var ii=0; ii<opensels.length; ii++)
		document.getElementById(opensels[ii]).style.display='none';
};
function addopensel(id){
	for(var ii=0; ii<opensels.length; ii++)
		if(id==opensels[ii]) return;
	opensels.push(id);
}
function plajaxcallback(){
	if(ajaxobj.readyState==4){
		var resarr=ajaxobj.responseText.replace(/^\s+|\s+$/g,"").split('==LISTOBJ==');
		var index,isname=false;
		oSelect=document.getElementById(resarr[0]);
		var act=resarr[0].replace(/\d/g,'');
		for(index=0; index<resarr.length-2; index++){
			var splitelem=resarr[index+1].split('==LISTELM==');
			var val1=splitelem[0];
			var val2=splitelem[1];
			var haswsdisc=0,hasperdisc=0,perdisc=0;
			if(splitelem.length>=2) adds[index]=splitelem[2];
			if(splitelem.length>=5) haswsdisc=splitelem[3];
			if(splitelem.length>=5) hasperdisc=splitelem[4];
			if(splitelem.length>=5) perdisc=splitelem[5];
			adiscnts[index]=new Array(haswsdisc,hasperdisc,perdisc);
			if(index<oSelect.length)
				var y=oSelect.options[index];
			else
				var y=document.createElement('option');
			if(act=='selectprodname'){
				y.text=val2;
				y.value=val1;
			}else if(act=='selectemail'){
				y.text=val2;
				y.title=val2;
				y.value=val1;
			}else{
				y.text=val1;
				y.value=val1;
			}
			if(y.text=='----------------') y.disabled=true; else y.disabled=false;
			if(index>=oSelect.length){
				try{oSelect.add(y, null);} // FF etc
				catch(ex){oSelect.add(y);} // IE
			}
		}
		if(oSelect){
			for(var ii=oSelect.length;ii>=index;ii--){
				oSelect.remove(ii);
			}
		}
	}
}
var gsid;
var gltyp;
var gtxt;
var tmrid;
function populatelist(){
	var objid=gsid;
	var listtype=gltyp;
	var stext=gtxt;
	ajaxobj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
	ajaxobj.onreadystatechange=plajaxcallback;
	ajaxobj.open("POST", "ajaxservice.php?action=getlist&objid="+objid+"&listtype="+listtype, true);
	ajaxobj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	ajaxobj.send('listtext='+stext);
}
function combochange(oText,e){
	if(document.getElementById("autocomplete").checked==false)
		return;
	keyCode=e.keyCode;
	if(keyCode<32&&keyCode!=8)return true;
	oSelect=document.getElementById('select'+oText.id);
	addopensel(oSelect.id);
	oSelect.style.display='';
	toFind=oText.value.toLowerCase();
	gsid=oSelect.id;
	gltyp=oText.id.replace(/\d/g,'');
	gtxt=toFind;
	clearTimeout(tmrid);
	tmrid=setTimeout("populatelist()",800);
}
function combokey(oText,e){
	if(document.getElementById("autocomplete").checked==false)
		return
	oSelect=document.getElementById('select'+oText.id);
	keyCode=e.keyCode;
	if(keyCode==40 || keyCode==38){ // Up / down arrows
		addopensel(oSelect.id);
		oSelect.style.display='';
		oSelect.focus();
		comboselect_onchange(oSelect);
	}
	else if(keyCode==13){
		oSelect.style.display='none';
		oText.focus();
		updateoptions(oText.id.replace(/prodid|prodname/,''));
		return getvalsfromserver(oSelect);
	}
	return true;
}
function getvalsfromserver(oSelect){
	var act=oSelect.id.replace(/\d/g,'');
	oText=document.getElementById(oSelect.id.replace('select',''));
	if(oSelect.selectedIndex!=-1){
		if(act=='selectprodname'){
			oText.value=oSelect.options[oSelect.selectedIndex].text;
			document.getElementById(oText.id.replace('prodname','prodid')).value=oSelect.options[oSelect.selectedIndex].value;
		}else
			oText.value=oSelect.options[oSelect.selectedIndex].value;
		oSelect.style.display='none';
		oText.focus();
		if(act=='selectemail')
			updateaddress(oSelect.selectedIndex);
		else
			updateoptions(oText.id.replace(/prodid|prodname/,''));
	}
	return false;
}
function comboselect_onclick(oSelect){
	return(getvalsfromserver(oSelect));
}
function comboselect_onchange(oSelect){
	oText=document.getElementById(oSelect.id.replace('select',''));
	if(oSelect.selectedIndex!=-1){
		if(oText.id.indexOf('prodname')!=-1)
			oText.value=oSelect.options[oSelect.selectedIndex].text;
		else
			oText.value=oSelect.options[oSelect.selectedIndex].value;
	}
}
function comboselect_onkeyup(keyCode,oSelect){
	if(keyCode==13){
		getvalsfromserver(oSelect);
	}
	return(false);
}
var countrytaxrates=[];
var statetaxrates=[];
var stateabbrevs=[];
<?php
	$sSQL="SELECT stateName,stateAbbrev,stateTax,stateCountryID FROM states WHERE stateTax<>0";
	$result=ect_query($sSQL) or ect_error();
	while($rs2=ect_fetch_assoc($result)){
		print 'statetaxrates["'.strtolower($rs2['stateName']).'"]='.$rs2['stateTax'].";\r\n";
		if($rs2['stateCountryID']==1 || $rs2['stateCountryID']==2){
			print 'statetaxrates["'.strtolower($rs2['stateAbbrev']).'"]='.$rs2['stateTax'].";\r\n";
			print 'stateabbrevs["'.strtolower($rs2['stateName']).'"]="'.$rs2['stateAbbrev']."\";\r\n";
		}
	}
	ect_free_result($result);
	$sSQL='SELECT countryID,countryName,countryTax FROM countries WHERE countryTax<>0';
	$result=ect_query($sSQL) or ect_error();
	while($rs2=ect_fetch_assoc($result)){
		print 'countrytaxrates['.strtolower($rs2['countryID']).']='.$rs2['countryTax'].";\r\n";
	}
	ect_free_result($result); ?>
function setstatetax(){
	var addans='';
	if(document.getElementById('saddress').value!='') addans='s';
	var rgnname=document.getElementById(addans+'state').value.toLowerCase();
	if(statetaxrates[rgnname]) statetaxrate=parseFloat(statetaxrates[rgnname]); else statetaxrate=0;
	document.getElementById("staterate").value=statetaxrate;
}
function setcountrytax(){
	var addans='';
	if(document.getElementById('saddress').value!='') addans='s';
	var tobj=document.getElementById(addans+'country');
	var rgnid=tobj.options[tobj.selectedIndex].value.toLowerCase();
	if(countrytaxrates[rgnid]) countrytaxrate=parseFloat(countrytaxrates[rgnid]); else countrytaxrate=0;
	document.getElementById("countryrate").value=countrytaxrate;
}
function getshipstateabbrev(){
	var addans='';
	if(document.getElementById('saddress').value!='') addans='s';
	var rgnname=document.getElementById(addans+'state').value.toLowerCase();
	if(stateabbrevs[rgnname]){
		document.getElementById('staterate').value=statetaxrates[rgnname];
		return(stateabbrevs[rgnname]);
	}else
		return document.getElementById(addans+'state').value;
}
function getshipcountry(){
	var addans='';
	if(document.getElementById('saddress').value!='') addans='s';
	var tobj=document.getElementById(addans+'country');
	return(tobj.options[tobj.selectedIndex].value.toLowerCase());
}
<?php		}else{ // ! $doedit ?>
function dosavefieldcb(){
	if(ajaxobj.readyState==4){
		if(ajaxobj.responseText.substr(0,7)=='SUCCESS'){
			document.getElementById(ajaxobj.responseText.substr(8)).style.borderColor='green';
		}else
			alert('Error updating');
	}
}
function dosavefield(tact,ordid,newval){
	ajaxobj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
	ajaxobj.onreadystatechange=dosavefieldcb;
	ajaxobj.open("GET","ajaxservice.php?action="+tact+"&ordid="+ordid+"&updfield="+encodeURIComponent(newval),true);
	ajaxobj.send(null);
}
var invisflashing=false,tnumisflashing=false;
var invintervalid=0,tnumintervalid=0;
var invflipflop=0,tnumflipflop=0;
function fliptext(tact){
	if(tact=='invoiceupdate'){
		document.getElementById(tact+'t').innerHTML=invflipflop==0?'Press Enter To Save:':'<?php print jscheck($yyInvNum)?>:';
		invflipflop=Math.abs(invflipflop-1);
	}else if(tact=='tracknumupdate'){
		document.getElementById(tact+'t').innerHTML=tnumflipflop==0?'Press Enter To Save:':'<?php print jscheck($yyTraNum)?>:';
		tnumflipflop=Math.abs(tnumflipflop-1);
	}
}
function startflash(tact){
	if(tact=='invoiceupdate'&&!invisflashing){
		fliptext('invoiceupdate');
		invisflashing=true;
		invintervalid=setInterval("fliptext('invoiceupdate')",2000);
	}else if(tact=='tracknumupdate'&&!tnumisflashing){
		fliptext('tracknumupdate');
		tnumisflashing=true;
		tnumintervalid=setInterval("fliptext('tracknumupdate')",2000);
	}
}
function stopflash(tact){
	if(tact=='invoiceupdate'){
		clearInterval(invintervalid);
		document.getElementById(tact+'t').innerHTML='<?php print jscheck($yyInvNum)?>:';
		invflipflop=0;
		invisflashing=false;
	}else if(tact=='tracknumupdate'){
		clearInterval(tnumintervalid);
		document.getElementById(tact+'t').innerHTML='<?php print jscheck($yyTraNum)?>:';
		tnumflipflop=0;
		tnumisflashing=false;
	}
}
function checksavefield(tact,evt,tobj,ordid){
	var code=(evt.keyCode ? evt.keyCode : evt.which);
	if(code==13){
		stopflash(tact);
		document.getElementById(tact+'t').className=document.getElementById(tact+'t').className.replace(/ ectred/g,'');
		dosavefield(tact,ordid,tobj.value);
	}else if(code==8||code==32||(code>=46&&code<=90)){
		tobj.style.borderColor='red';
		document.getElementById(tact+'t').className+=' ectred';
		tobj.title='Press Enter To Save';
		startflash(tact);
	}
}
function checkstatusupdfield(evt,tobj){
	var code = (evt.keyCode ? evt.keyCode : evt.which);
	if(code==8||code==13||code==32||(code>=46&&code<=90)){
		document.getElementById('statusupdcontainer').style.display=''
	}
}
<?php		} ?>
/* ]]> */
</script>
<?php		if(!$doedit){ ?>
<div id="addressdiv" onclick="this.style.display='none'" style="display:none;position:absolute;width:100%;height:2000px;background-image:url(adminimages/opaquepixel.png);top:0px;left:0px;text-align:center;z-index:10000;">
<br><br><br><br><br><br><br><br>
<textarea id="addresstextarea" rows="10" cols="40" onclick="return false"></textarea>
</div>
<?php		}
		} // ! $isprinter
		$sSQL="SELECT packingslipuseinvoice FROM admin WHERE adminID=1";
		$result=ect_query($sSQL) or ect_error();
		$rs=ect_fetch_assoc($result);
		$packingslipuseinvoice=$rs['packingslipuseinvoice'];
		ect_free_result($result);
		$sSQL="SELECT invoiceheader,invoiceaddress,invoicefooter".($packingslipuseinvoice==0?',packingslipheader,packingslipaddress,packingslipfooter':'')." FROM emailmessages WHERE emailID=1";
		$result=ect_query($sSQL) or ect_error();
		$rs=ect_fetch_assoc($result);
		$invoiceheader=$rs['invoiceheader'];
		$invoiceaddress=$rs['invoiceaddress'];
		$invoicefooter=$rs['invoicefooter'];
		if($packingslipuseinvoice){
			$packingslipheader=$invoiceheader;
			$packingslipaddress=$invoiceaddress;
			$packingslipfooter=$invoicefooter;
		}else{
			$packingslipheader=$rs['packingslipheader'];
			$packingslipaddress=$rs['packingslipaddress'];
			$packingslipfooter=$rs['packingslipfooter'];
		}
		ect_free_result($result); ?>
<script>
/* <![CDATA[ */
<?php
if(@$GLOBALS['adminorderstitle']!=''){
	print "document.title='" . str_replace('%orderid%',$theid,$GLOBALS['adminorderstitle']) . "';";
	$adminorderstitle='';
}
?>
function researchformgo(tid,switchinvoice){
	var currinvoice='<?php print (getget("printer")=="true"?"&printer=true":'').(getget("invoice")=="true"?"&invoice=true":'')?>';
	var newinvoice='';
	if(switchinvoice==0)
		newinvoice=currinvoice;
	else if(switchinvoice==1||switchinvoice==2)
		newinvoice=switchinvoice==2?'&printer=true':'&invoice=true';
	else if(switchinvoice==5)
		newinvoice='&doedit=true&view=true';
	document.getElementById('researchform').action='adminorders.php'+(switchinvoice!=3?'?id='+tid+newinvoice:'');
	document.getElementById('researchform').submit();
}
/* ]]> */
</script>
<script src="popcalendar.js"></script>
<div class="orderdetails"<?php if($numids>0) print ' style="page-break-after:always"'?>>
<?php	$extraclass='order';
		if(getget('invoice')=='true') $extraclass='invoice';
		if(getget('printer')=='true') $extraclass='packingslip';
		if($isprinter && ! @isset($packingslipheader)) $packingslipheader=@$invoiceheader;
		if($isinvoice && @$invoiceheader!=''){ ?>
		<div class="orderheader invoiceheader"><?php print $invoiceheader?></div>
<?php	}elseif($isprinter && @$packingslipheader!=''){ ?>
		<div class="orderheader packslipheader"><?php print $packingslipheader?></div>
<?php	} ?>
		<div class="buttons">
			<div class="buttonleft"><?php
		if($doedit)
			print '&nbsp;<input type="checkbox" value="ON" name="autocomplete" id="autocomplete" onclick="setCookie(\'ectautocomp\',this.checked?1:0,600)" '.(@$_COOKIE['ectautocomp']=="1"?'checked="checked" ':'').'/> '.$yyUsAuCo;
		elseif(getget('id')!='multi' && getget('id')!='new'){
			print '<input '.(@$previousid==''?'disabled="disabled" ':'').'class="no-print" style="width:110px;margin:2px" type="button" value="&laquo; '.$yyPrev.'" onclick="researchformgo(\''.@$previousid.'\',0)">';
			print '<input '.(@$previousbysearch==''?'disabled="disabled" ':'').'class="no-print" style="width:110px;margin:2px" type="button" value="'."Prev. By Search".'" onclick="researchformgo(\''.@$previousbysearch.'\',0)"><br>';
			print '<input '.(!(getget("printer")=="true" || getget("invoice")=="true")?'disabled="disabled" ':'').'class="no-print" style="width:110px;margin:2px" type="button" value="'.'Print'.'" onclick="window.print()">';
			print '<input class="no-print" style="width:110px;margin:2px" type="button" value="'.'Orders'.'" onclick="researchformgo(\''.$alldata['ordID'].'\',3)">';
		} ?></div><div class="idanddate"><?php
		if(!$doedit) print '<div class="no-print"><input type="button" style="width:130px;margin:2px" value="Edit Order: ' . $alldata['ordID'] . '" onclick="researchformgo(\''.$alldata['ordID'].'\',5)"></div>';
		print '<div class="orderid">' . $xxOrdNum . ' ' . (getget("clone")=='true'?'(Clone Order)':(getget('id')=='new'?'('.$yyNewOrd.')':$alldata['ordID']));
		if($doedit && $adminlanguages>0){
			print ' - Language ID: <select size="1" name="ordlang">';
			for($index=0;$index<=$adminlanguages;$index++){
				print '<option value="'.$index.'"'.($index==$alldata['ordLang']?' selected':'').'>'.($index+1).'</option>';
			}
			print '</select>';
		}
		print '</div><div class="orderdate">';
		if(@$fordertimeformatstr!=''){
			setlocale(LC_TIME, $adminLocale);
			$thedatetime=strftime($fordertimeformatstr, $alldata['ordDate']);
		}else
			$thedatetime=date($dateformatstr, $alldata['ordDate']) . ' ' . date('H:i', $alldata['ordDate']);
		if($doedit){
			print '<input type="button" value="' . $thedatetime . '" onclick="document.getElementById(\'doeditdate\').value=\'1\';this.style.display=\'none\';document.getElementById(\'editorddatediv\').style.display=\'inline\';popUpCalendar(this, document.getElementById(\'editorddate\'), \'' . $themask . '\', 0)">';
			print '<div id="editorddatediv"" style="position:relative;display:none">';
				print '<input type="text" style="width:120px" id="editorddate" name="editorddate" value="' . date($admindatestr, $alldata['ordDate']) . '" onfocus="popUpCalendar(this, document.getElementById(\'editorddate\'), \'' . $themask . '\', 0)">';
				print '<input type="text" style="width:60px" name="editordtime" value="' . date('H:i', $alldata['ordDate']) . '">';
				writehiddenidvar("doeditdate","");
			print '</div>';
		}else{
			if(@$fordertimeformatstr!=''){
				setlocale(LC_TIME, $adminLocale);
				print strftime($fordertimeformatstr, $alldata['ordDate']);
			}else
				print date($dateformatstr, $alldata['ordDate']) . ($isinvoice ? '' : ' ' . date('H:i', $alldata['ordDate']));
		}
		?></div></div><div class="buttonright">
<?php	if(getget('id')!='multi' && getget('id')!='new' && !$doedit){
			print '<input '.(@$nextbysearch==''?'disabled ':'').'class="no-print" style="width:110px;margin:2px" type="button" value="'.'Next By Search'.'" onclick="researchformgo(\''.@$nextbysearch.'\',0)">';
			print '<input '.(@$nextid==''?'disabled ':'').'class="no-print" style="width:110px;margin:2px" type="button" value="'.$yyNext.' &raquo;" onclick="researchformgo(\''.@$nextid.'\',0)"><br>';
			print '<input '.(@$dropshipper!=''?'disabled ':'').'class="no-print" style="width:110px;margin:2px" type="button" value="'.(getget("invoice")=="true"?"Details":"Invoice").'" onclick="researchformgo(\''.$alldata['ordID']."',".(getget("invoice")=="true"?4:1).')">';
			print '<input class="no-print" style="width:110px;margin:2px" type="button" value="'.(getget("printer")=="true"?"Details":"Packing Slip").'" onclick="researchformgo(\''.$alldata['ordID']."',".(getget("printer")=="true"?4:2).')">';
		}
?>			</div>
		</div>
<?php	if($isprinter && ! @isset($packingslipaddress)) $packingslipaddress=@$invoiceaddress;
		if($isinvoice && @$invoiceaddress!=''){ ?>
		<div class="orderaddress invoiceaddress"><?php print $invoiceaddress?></div>
<?php	}elseif($isprinter && @$packingslipaddress!=''){ ?>
		<div class="orderaddress packslipaddress"><?php print $packingslipaddress?></div>
<?php	} ?>
		<input type="hidden" name="custid" id="custid" value="">

			<div class="addresses">
				<div class="billing address">
					<div class="billing colheading"><h2><?php print $yyBilDet?>.</h2></div>
<?php	if(trim_(@$extraorderfield1)!='' && (! $isprinter || (trim_($alldata['ordExtra1'])!='' && !@$extraorderfield1noprint))){ ?>
					<div class="billing container container1">
					  <div class="extra1 left"><?php print $extraorderfield1 ?>:</div>
					  <div class="extra1 right" id="ordextra1"><?php print editfunc($alldata['ordExtra1'],'extra1',25)?></div>
					</div>
<?php	} ?>
					<div class="billing container container2">
					  <div class="ordname left"><?php print $yyName?>:</div>
					  <div class="ordname right" id="ordname"><?php if(@$GLOBALS['usefirstlastname'] || $alldata['ordLastName']!='') print editfunc($alldata['ordName'],'name',11).' '.editfunc($alldata['ordLastName'],'lastname',11); else print editfunc($alldata['ordName'],'name',25)?></div>
					</div>
					<div class="billing container container3">
					  <div class="ordaddress left"><?php print $xxAddress?>:</div>
					  <div class="ordaddress right" id="ordaddress"><?php print editfunc($alldata['ordAddress'],'address',25)?></div>
					</div>
<?php	if(($doedit && @$useaddressline2) || trim_($alldata['ordAddress2'])!=''){ ?>
					<div class="billing container container4">
					  <div class="ordaddress2 left"><?php print ($isprinter?'&nbsp;':$xxAddress2.':')?></div>
					  <div class="ordaddress2 right" id="ordaddress2"><?php print editfunc($alldata['ordAddress2'],'address2',25)?></div>
					</div>
<?php	}
		if($isprinter){ ?>
					<div class="billing container container5">
					  <div class="ordcity left">&nbsp;</div>
					  <div class="ordcity right"><?php print $alldata['ordCity'].(trim_($alldata['ordCity'])!='' && trim_($alldata['ordState'])!='' ? ', ' : '').$alldata['ordState']?></div>
					</div>
<?php	}else{ ?>
					<div class="billing container container6">
					  <div class="ordcity left"><?php print $xxCity?>:</div>
					  <div class="ordcity right" id="ordcity"><?php print editfunc($alldata['ordCity'],'city',25)?></div>
					</div>
					<div class="billing container container7">
					  <div class="ordstate left"><?php print $xxAllSta?>:</div>
					  <div class="ordstate right" id="ordstate"><?php print editspecial($alldata['ordState'],'state',25,'onblur="setstatetax()"')?></div>
					</div>
<?php	} ?>
					<div class="billing container container8">
					  <div class="ordzip left"><?php print ($isprinter?'&nbsp;':$xxZip.':')?></div>
					  <div class="ordzip right" id="ordzip"><?php print editfunc($alldata['ordZip'],'zip',15)?></div>
					</div>
					<div class="billing container container9">
					  <div class="ordcountry left"><?php print ($isprinter?'&nbsp;':$xxCountry.':')?></div>
					  <div class="ordcountry right" id="ordcountry"><?php
		if($doedit){
			$foundmatch=FALSE;
			$countryid=0;
			$loadstates=-1;
			print '<select name="country" id="country" size="1" onchange="setcountrytax()">';
			$sSQL="SELECT countryID,countryName,countryTax,loadStates FROM countries ORDER BY countryOrder DESC, countryName";
			$result=ect_query($sSQL) or ect_error();
			while($rs2=ect_fetch_assoc($result)){
				print '<option value="' . $rs2['countryID'] . '"';
				if($alldata['ordCountry']==$rs2['countryName'] || (getget('id')=='new' && ! $foundmatch)){
					print ' selected';
					$foundmatch=TRUE;
					$countryid=$rs2['countryID'];
					$countrytaxrate=$rs2['countryTax'];
					$loadstates=$rs2['loadStates'];
				}
				print '>' . $rs2['countryName'] . "</option>\r\n";
			}
			ect_free_result($result);
			if(! $foundmatch) print '<option value="' . htmlspecials($alldata['ordCountry']) . '" selected="selected">' . $alldata['ordCountry'] . "</option>\r\n";
			print '</select>';
			if($loadstates>0){
				$sSQL="SELECT stateTax FROM states WHERE stateCountryID=".$countryid." AND (stateName='" . escape_string($alldata['ordState']) . "' OR stateAbbrev='" . escape_string($alldata['ordState']) . "')";
				$result=ect_query($sSQL) or ect_error();
				if($rs2=ect_fetch_assoc($result))
					$statetaxrate=$rs2['stateTax'];
				ect_free_result($result);
			}
		}else{
			$shipcountrytext=($alldata['ordShipCountry']!='' ? $alldata['ordShipCountry'] : $alldata['ordCountry']);
			$sSQL="SELECT countryID,countryTax FROM countries WHERE countryEnabled<>0 AND (countryName='" . escape_string($shipcountrytext) . "' OR countryName2='" . escape_string($shipcountrytext) . "' OR countryName3='" . escape_string($shipcountrytext) . "')";
			$result=ect_query($sSQL) or ect_error();
			if($rs2=ect_fetch_assoc($result)) $countrytaxrate=$rs2['countryTax'];
			ect_free_result($result);
			print $alldata['ordCountry'];
		} ?></div>
					</div>
					<div class="billing container container10">
					  <div class="ordcountry left"><?php print $xxPhone?>:</div>
					  <div class="ordcountry right"><?php print editfunc($alldata['ordPhone'],'phone',25)?></div>
					</div>
<?php	if(trim_(@$extraorderfield2)!='' && (! $isprinter || (trim_($alldata['ordExtra2'])!='' && !@$extraorderfield2noprint))){ ?>
					<div class="billing container container11">
					  <div class="ordextra2 left"><?php print @$extraorderfield2 ?>:</div>
					  <div class="ordextra2 right" id="ordextra2"><?php print editfunc($alldata['ordExtra2'],'extra2',25)?></div>
					</div>
<?php	}
		if(! ($isprinter || $doedit)){ ?>
					<div class="billing container container12">
					  <div class="clipboard left"></div>
					  <div class="clipboard right"><input type="button" value="Copy to Clipboard" onclick="popupaddress('')"></div>
					</div>
<?php	} ?>
				</div><?php
				
	if(trim_($alldata['ordShipName'])!='' || trim_($alldata['ordShipAddress'])!='' || trim_($alldata['ordShipCity'])!='' || trim_($alldata['ordShipExtra1'])!='' || $doedit){
				?><div class="ship shipaddress">
					<div class="ship colheading"><h2><?php print $xxShpDet?>.
<?php		if($doedit) print ' &raquo; <a href="#" onclick="copybillingtoshipping();return(false);">'.$yyCopBil.'</a>'?></h2></div>
<?php		if(trim_(@$extraorderfield1)!='' && (! $isprinter || (trim_($alldata['ordShipExtra1'])!='' && !@$extraorderfield1noprint))){ ?>
					<div class="ship container container1">
					  <div class="ordshipextra1 left"><?php print @$extraorderfield1 ?>:</div>
					  <div class="ordshipextra1 right" id="ordsextra1"><?php print editfunc($alldata['ordShipExtra1'],'shipextra1',25)?></div>
					</div>
<?php		} ?>
					<div class="ship container container2">
					  <div class="ordshipname left"><?php print $yyName?>:</div>
					  <div class="ordshipname right" id="ordsname"><?php if(@$GLOBALS['usefirstlastname']) print editfunc($alldata['ordShipName'],'sname',11).' '.editfunc($alldata['ordShipLastName'],'slastname',11); else print editfunc($alldata['ordShipName'],'sname',25)?></div>
					</div>
					<div class="ship container container3">
					  <div class="ordshipaddress left"><?php print $xxAddress?>:</div>
					  <div class="ordshipaddress right" id="ordsaddress"><?php print editspecial($alldata['ordShipAddress'],'saddress',25,'onblur="setstatetax();setcountrytax();"')?></div>
					</div>
<?php		if(($doedit && @$useaddressline2) || trim_($alldata['ordShipAddress2'])!=''){ ?>
					<div class="ship container container4">
					  <div class="ordshipaddress2 left"><?php print ($isprinter?'&nbsp;':$xxAddress2.':')?></div>
					  <div class="ordshipaddress2 right" id="ordsaddress2"><?php print editfunc($alldata['ordShipAddress2'],'saddress2',25)?></div>
					</div>
<?php		}
			if($isprinter){ ?>
					<div class="ship container container5">
					  <div class="ordshipcity left">&nbsp;</div>
					  <div class="ordshipcity right"><?php print $alldata['ordShipCity'].(trim_($alldata['ordShipCity'])!='' && trim_($alldata['ordShipState'])!='' ? ', ' : '').$alldata['ordShipState']?></div>
					</div>
<?php		}else{ ?>
					<div class="ship container container6">
					  <div class="ordshipcity left"><?php print $xxCity?>:</div>
					  <div class="ordshipcity right" id="ordscity"><?php print editfunc($alldata['ordShipCity'],'scity',25)?></div>
					</div>
					<div class="ship container container7">
					  <div class="ordshipstate left"><?php print $xxAllSta?>:</div>
					  <div class="ordshipstate right" id="ordsstate"><?php print editspecial($alldata['ordShipState'],'sstate',25,'onblur="setstatetax()"')?></div>
					</div>
<?php		} ?>
					<div class="ship container container8">
					  <div class="ordshipzip left"><?php print ($isprinter?'&nbsp;':$xxZip.':')?></div>
					  <div class="ordshipzip right" id="ordszip"><?php print editfunc($alldata['ordShipZip'],'szip',15)?></div>
					</div>
					<div class="ship container container9">
					  <div class="ordscountry left"><?php print ($isprinter?'&nbsp;':$xxCountry.':')?></div>
					  <div class="ordscountry right" id="ordscountry"><?php
			if($doedit){
				if(trim_($alldata['ordShipName'])!='' || trim_($alldata['ordShipAddress'])!='') $usingshipcountry=TRUE; else $usingshipcountry=FALSE;
				$foundmatch=(getget('id')=='new');
				$countryid=0;
				$loadstates=-1;
				print '<select name="scountry" id="scountry" size="1" onchange="setcountrytax()">';
				$sSQL="SELECT countryID,countryName,countryTax,loadStates FROM countries ORDER BY countryOrder DESC, countryName";
				$result=ect_query($sSQL) or ect_error();
				while($rs2=ect_fetch_assoc($result)){
					print '<option value="' . $rs2['countryID'] . '"';
					if($alldata['ordShipCountry']==$rs2['countryName']){
						print ' selected';
						$foundmatch=TRUE;
						$countryid=$rs2['countryID'];
						if($usingshipcountry) $countrytaxrate=$rs2['countryTax'];
						$loadstates=$rs2['loadStates'];
					}
					print '>' . $rs2['countryName'] . "</option>\r\n";
				}
				ect_free_result($result);
				if(! $foundmatch) print '<option value="' . htmlspecials($alldata['ordShipCountry']) . '" selected="selected">' . $alldata['ordShipCountry'] . "</option>\r\n";
				print '</select>';
				if($loadstates>0 && $usingshipcountry){
					$sSQL="SELECT stateTax FROM states WHERE stateCountryID=".$countryid." AND (stateName='" . escape_string($alldata['ordShipState']) . "' OR stateAbbrev='" . escape_string($alldata['ordShipState']) . "')";
					$result=ect_query($sSQL) or ect_error();
					if($rs2=ect_fetch_assoc($result))
						$statetaxrate=$rs2['stateTax'];
					ect_free_result($result);
				}
			}else
				print $alldata['ordShipCountry']?></div>
					</div>
					<div class="ship container container10">
					  <div class="ordshipphone left"><?php print $xxPhone?>:</div>
					  <div class="ordshipphone right"><?php print editfunc($alldata['ordShipPhone'],'sphone',25)?></div>
					</div>
<?php		if(trim_(@$extraorderfield2)!='' && (! $isprinter || (trim_($alldata['ordShipExtra2'])!='' && !@$extraorderfield2noprint))){ ?>
					<div class="ship container container11">
					  <div class="ordshipextra2 left"><?php print $extraorderfield2 ?>:</div>
					  <div class="ordshipextra2 right" id="ordsextra2"><?php print editfunc($alldata['ordShipExtra2'],'shipextra2',25)?></div>
					</div>
<?php		}
			if(! ($isprinter || $doedit)){ ?>
					<div class="ship container container12">
					  <div class="clipboard left"></div>
					  <div class="clipboard right"><input type="button" value="Copy to Clipboard" onclick="popupaddress('s')"></div>
					</div>
<?php		} ?>
				</div>
<?php	} ?>
			</div><div class="adddetails <?php print $extraclass?>adddetails">
					<div class="colheading"><h2><?php print $yyAddDet?>.</h2></div>
					<div class="container container1">
					  <div class="ordemail left"><?php print $xxEmail?>:</div>
					  <div class="ordemail right"><?php
		if($isprinter || $doedit) print editspecial($alldata['ordEmail'],'email',35,'AUTOCOMPLETE="off" onkeydown="return combokey(this,event)" onkeyup="combochange(this,event)"'); else print '<a href="mailto:' . htmlspecials($alldata['ordEmail']) . '">' . htmlspecials($alldata['ordEmail']) . '</a>';
		if($doedit) print showgetoptionsselect('selectemail'); ?></div>
					</div>
<?php	if(trim_(@$extracheckoutfield1)!='' && !($isprinter && @$extracheckoutfield1noprint)){
			$checkoutfield1=$extracheckoutfield1;
			$checkoutfield2=editfunc($alldata['ordCheckoutExtra1'],'checkoutextra1',25)
?>					<div class="container container2">
					  <div class="ordcheckoutextra1 left"><?php if(@$extracheckoutfield1reverse) print $checkoutfield2; else print $checkoutfield1 . ':' ?></div>
					  <div class="ordcheckoutextra1 right"><?php if(@$extracheckoutfield1reverse) print $checkoutfield1; else print $checkoutfield2 ?></div>
					</div>
<?php	}
		if(trim_(@$extracheckoutfield2)!='' && !($isprinter && @$extracheckoutfield2noprint)){
			$checkoutfield1=$extracheckoutfield2;
			$checkoutfield2=editfunc($alldata['ordCheckoutExtra2'],'checkoutextra2',25)
?>					<div class="container container3">
					  <div class="ordcheckoutextra2 left"><?php if(@$extracheckoutfield2reverse) print $checkoutfield2; else print $checkoutfield1 . ':' ?></div>
					  <div class="ordcheckoutextra2 right"><?php if(@$extracheckoutfield2reverse) print $checkoutfield1; else print $checkoutfield2 ?></div>
					</div>
<?php	}
		$ordAddInfo=trim_($alldata['ordAddInfo']);
		if($ordAddInfo!='' || $doedit){ ?>
					<div class="container container4">
					  <div class="ordaddinfo left"><?php print str_replace('  ', '&nbsp;&nbsp;', $xxAddInf)?>:</div>
					  <div class="ordaddinfo right"><?php
			if($doedit)
				print '<textarea name="ordAddInfo" cols="50" rows="4">' . strip_tags($ordAddInfo) . '</textarea>';
			else
				print str_replace(array("\r\n","\n"),array('<br>','<br>'),strip_tags($ordAddInfo)); ?></div>
					</div>
<?php	}
		if(! $isprinter){ ?>
					<div class="container container5">
					  <div class="ordip left"><?php print $yyIPAdd?>:</div>
					  <div class="ordip right"><?php if($doedit) print editfunc($alldata['ordIP'],'ipaddress',15); else print '<a href="http://www.infosniper.net/index.php?lang=1&ip_address='.urlencode($alldata['ordIP']).'" target="_blank">'.htmlspecials($alldata['ordIP']).'</a>'?></div>
					</div>
					<div class="container container6">
					  <div class="ordaffiliate left"><?php print $yyAffili?>:</div>
					  <div class="ordaffiliate right"><?php print editfunc($alldata['ordAffiliate'],'PARTNER',15)?></div>
					</div>
<?php	}
		if((trim_($alldata['ordDiscountText'])!='' && (! $isprinter || $isinvoice)) || $doedit){ ?>
					<div class="container container7">
					  <div class="orddiscounttext left"><?php print $xxAppDs?>:</div>
					  <div class="orddiscounttext right"><?php if($doedit) print '<textarea name="discounttext" cols="50" rows="2">' . str_replace(array('<br>','<br>','<'), array("\r\n","\r\n",'&lt;'), $alldata['ordDiscountText']) . '</textarea>'; else print str_replace(array("\r","\n"),array('','<br>'),htmldisplay(str_replace(array('<br>','<br>'),"\n",$alldata['ordDiscountText']))); ?></div>
					</div>
<?php	}
		if(! $isprinter){
			$sSQL="SELECT gcaGCID,gcaAmount FROM giftcertsapplied WHERE gcaOrdID=".$theid;
			$result=ect_query($sSQL) or ect_error();
			while($rs=ect_fetch_assoc($result))
				print '<div class="container container8"><div class="left">' . $yyCerNum . '</div><div class="right">' . $rs['gcaGCID'] . ' ' . FormatEuroCurrency($rs['gcaAmount']) . ' ' . '<a href="admingiftcert.php?id=' . $rs['gcaGCID'] . '">' . $yyClkVw . '</a></div></div>';
			ect_free_result($result);
		}
		$ordAuthNumber=trim_($alldata['ordAuthNumber']);
		$ordTransID=trim_($alldata['ordTransID']);
		if(! $isprinter && ($ordAuthNumber!='' || $ordTransID!='' || $doedit)){ ?>
					<div class="container container9">
					  <div class="ordauthnumber left"><?php print $yyAutCod?>:</div>
					  <div class="ordauthnumber right"><?php print editfunc($ordAuthNumber,'ordAuthNumber',15) ?></div>
					</div>
					<div class="container container10">
					  <div class="ordtransid left"><?php print $yyTranID?>:</div>
					  <div class="ordtransid right"><?php print editfunc($ordTransID,'ordTransID',15) ?></div>
					</div>
<?php	}
		if(($isinvoice && $alldata['ordInvoice']!='') || ! $isprinter){
?>					<div class="container container11">
					  <div class="ordinvoice left" id="invoiceupdatet"><?php print $yyInvNum?>:</div>
					  <div class="ordinvoice right"><?php
						if($isinvoice)
							print editfunc($alldata['ordInvoice'],'ordInvoice',15);
						else{ ?>
	<input type="text" name="ordInvoice" id="ordInvoice" size="25" value="<?php print htmlspecials($alldata['ordInvoice'])?>" <?php print (! ($isprinter || $doedit)?'onkeyup="checksavefield(\'invoiceupdate\',event,this,'.getget('id').')" ':'')?>/>
<?php					} ?></div>
					</div>
<?php	}
		if(!$isprinter){
			if(@$loyaltypoints!=''){ ?>
					<div class="container container12">
					  <div class="loyaltypoints left"><?php print $xxLoyPoi?>:</div>
					  <div class="loyaltypoints right"><?php print editfunc($alldata['loyaltyPoints'],'loyaltyPoints',10) ?></div>
					</div>
<?php		}
			if($alldata['ordClientID']!=0 && !$doedit){
?>
					<div class="container container14">
					  <div class="reemail left"></div>
					  <div class="reemail right"><button type="button" onclick="document.getElementById('acctid').value=<?php print $alldata['ordClientID']?>;document.getElementById('custacctform').submit()">View Customer Account</button></div>
					</div>
<?php		}
			if($alldata['ordReferer']!=''){ ?>
					<div class="container container13">
					  <div class="ordreferer left">Referer:</div>
					  <div class="ordreferer right"><input type="text" name="ordreferer" value="<?php print str_replace('"', '&quot;', $alldata['ordReferer'] . ($alldata['ordQuerystr']!='' ? '?' . $alldata['ordQuerystr'] : ''))?>" size="80"></div>
					</div>
<?php		}
			if($alldata['ordUserAgent']!=''){ ?>
					<div class="container container15">
					  <div class="orduseragent left">User Agent:</div>
					  <div class="orduseragent right"><?php print htmlspecials($alldata['ordUserAgent'])?></div>
					</div><?php
			}
			if(trim_($alldata['ordAuthNumber'])!='' && !$doedit){ ?>
					<div class="container container14">
					  <div class="reemail left"></div>
					  <div class="reemail right"><input type="button" value="Resend Email" onclick="openemailpopup(<?php print $alldata['ordID']?>)"></div>
					</div>
<?php		} ?>
				</div><div class="orderstatus <?php print $extraclass?>orderstatus">
					<div class="colheading"><h2><?php print $yyOrdSta?>.</h2></div>
<?php		if(! $doedit) print '<form method="post" action="adminorders.php"><input type="hidden" name="updatestatus" value="1"><input type="hidden" name="orderid" value="' . getget('id') . '">';
				$isauthorized=TRUE;
				if($alldata['ordAuthStatus']=='MODWARNOPEN' || $alldata['ordShipType']=='MODWARNOPEN'){
					$isauthorized=FALSE; ?>
					<div class="container containerMW">
					  <div class="modwarning left ectred"><?php print $yyWarni?>:</div>
					  <div class="modwarning right"><?php print $yyMoWarn?></div>
					</div>
<?php				} ?>
					<div class="container container1">
					  <div class="updatestatus left"><?php print $yyOrdSta?>:</div>
					  <div class="updatestatus right"><select name="ordStatus" size="1" onchange="document.getElementById('statusupdcontainer').style.display=''" style="width:190px"><?php
				for($index=0; $index < $numstatus; $index++){
					if(! $isauthorized && $allstatus[$index]['statID']>2) break;
					print '<option value="' . $allstatus[$index]['statID'] . '"';
					if($alldata['ordStatus']==$allstatus[$index]['statID']) print ' selected="selected">' . $allstatus[$index]['statPrivate'] . ' ' . date($admindatestr, $alldata['ordStatusDate']) . ' ' . date('H:i', $alldata['ordStatusDate']) . '</option>'; else print '>' . $allstatus[$index]['statPrivate'] . '</option>';
				} ?></select></div>
					</div>
					<div class="container container2">
					  <div class="ordstatusinfo left"><?php print $yyStaInf?>:</div>
						<input type="hidden" name="currStatus" value="<?php print $alldata['ordStatus']?>">
						<input type="hidden" name="currStatusInfo" value="<?php print htmlspecials($alldata['ordStatusInfo'])?>">
						<input type="hidden" name="currPrivateStatus" value="<?php print htmlspecials($alldata['ordPrivateStatus'])?>">
					  <div class="ordstatusinfo right"><textarea name="ordStatusInfo" id="ordStatusInfo" cols="50" rows="4" onkeyup="checkstatusupdfield(event,this)"><?php print htmlspecials($alldata['ordStatusInfo'])?></textarea>
					  </div>
					</div>
					<div class="container container3">
					  <div class="ordprivatestatus left"><?php print $yyPriSta?>:</div>
					  <div class="ordprivatestatus right"><textarea name="ordPrivateStatus" cols="50" rows="4" onkeyup="checkstatusupdfield(event,this)"><?php print htmlspecials($alldata['ordPrivateStatus'])?></textarea></div>
					</div>
<?php		if(! $doedit){ ?>
					<div class="container container4">
					  <div class="emailstat left"><input type="checkbox" name="emailstat" value="1" <?php if(getpost('emailstat')=="1" || @$alwaysemailstatus==TRUE) print "checked"?>/></div>
					  <div class="emailstat right"><?php print $yyEStat?>
						<div style="padding-top:6px;display:none" id="statusupdcontainer"><input type="submit" value="<?php print $yyUpdate?>"></div>
					  </div>
					</div>
<?php			print '</form>';
			}
		} ?>
				</div><?php
			if($alldata['ordShipCarrier']!=0 || $alldata['ordShipType']!='' || $doedit){
				?><div class="shipping <?php print $extraclass?>shipping">
					<div class="colheading"><h2><?php print $yyShip?>.</h2></div>
					<div class="container container1">
					  <div class="ordshiptype left"><?php print $xxShpMet?>:</div>
					  <div class="ordshiptype right"><?php
				if($isprinter)
					print ($alldata['ordShipType']=='MODWARNOPEN'?$yyMoWarn:$alldata['ordShipType']);
				else{ ?>
							<select name="shipcarrier" id="shipcarrier" size="1" onchange="dosavefield('shipcarrierupdate',<?php print getget('id')?>,this[this.selectedIndex].value)">
							<option value="<?php print $alldata['ordShipCarrier']?>"><?php print $yyOther?></option>
							<option value="3"<?php if((int)$alldata['ordShipCarrier']==3) print ' selected'?>>USPS</option>
							<option value="4"<?php if((int)$alldata['ordShipCarrier']==4) print ' selected'?>>UPS</option>
							<option value="11"<?php if((int)$alldata['ordShipCarrier']==11) print ' selected'?>>UPS SurePost</option>
							<option value="6"<?php if((int)$alldata['ordShipCarrier']==6) print ' selected'?>>CanPos</option>
							<option value="7"<?php if((int)$alldata['ordShipCarrier']==7) print ' selected'?>>FedEx</option>
							<option value="8"<?php if((int)$alldata['ordShipCarrier']==8) print ' selected'?>>FedEx SmartPost</option>
							<option value="9"<?php if((int)$alldata['ordShipCarrier']==9) print ' selected'?>>DHL</option>
							<option value="10"<?php if((int)$alldata['ordShipCarrier']==10) print ' selected'?>>Australia Post</option>
							</select><?php
				}	?></div>
					</div>
<?php			$isauthorized=!($alldata['ordAuthStatus']=='MODWARNOPEN' || $alldata['ordShipType']=='MODWARNOPEN');
				if(($alldata['ordShipType']!='' || $doedit) && !$isprinter){ ?>
					<div class="container containerv2">
					  <div class="left<?php if(!$isauthorized) print ' ectred'?>"><?php if(!$isauthorized) print $yyWarni.':'; else print '&nbsp;'?></div>
					  <div class="right"><?php if($isauthorized) print editfunc($alldata['ordShipType'],'shipmethod',25); else print $yyMoWarn?></div>
					</div>
<?php			}
				if(! $isprinter){ ?>
					<div class="container container3">
					  <div class="ordtracknum left" id="tracknumupdatet"><?php print $yyTraNum?>:</div>
					  <div class="ordtracknum right"><input type="text" name="ordTrackNum" id="ordTrackNum" size="30" value="<?php print htmlspecials($alldata['ordTrackNum'])?>" <?php print (! ($isprinter || $doedit)?'onkeyup="checksavefield(\'tracknumupdate\',event,this,'.getget("id").')" ':'')?>/></div>
					</div>
<?php				$sSQL="SELECT cartID,cartProdName,cartTrackNum,cartDateAdded FROM cart WHERE cartOrderID='" . escape_string($theid) . "'";
					$sSQL.=" AND cartTrackNum<>'' AND cartTrackNum IS NOT NULL";
					$result=ect_query($sSQL) or ect_error();
					if(ect_num_rows($result)>0){
?>					<div class="container container3">
					  <div class="ordtracknum" style="flex-grow:1">
					    <div style="text-align:center;font-weight:bold">Order Line Track #'s</div>
						<div class="ecttable">
<?php					while($rs=ect_fetch_assoc($result))
							print '<div class="ecttablerow"><div>' . $rs['cartProdName'] . '</div><div>' . $rs['cartTrackNum'] . '</div><div>' . date($dateformatstr, strtotime($rs['cartDateAdded'])) . '</div></div>'; ?>
						</div>
					  </div>
					</div>
<?php				}
				} ?>
					<div class="container container4">
					  <div class="left"><?php if($doedit) print $xxCLoc . ':'?></div>
					  <div class="right"><?php	if($doedit){
													print '<select name="commercialloc" id="commercialloc" size="1">';
													print '<option value="N">' . $yyNo . '</option>';
													print '<option value="Y"' . (($alldata['ordComLoc']&1)==1 ? ' selected' : '') . '>' . $yyYes . '</option>';
													print '</select>';
												}?></div>
					</div>
<?php			if($doedit){ ?>
					<div class="container container5">
					  <div class="left"><?php print $xxShpIns?>:</div>
					  <div class="right"><?php	print '<select name="wantinsurance" size="1">';
												print '<option value="N">' . $yyNo . '</option>';
												print '<option value="Y"' . (($alldata['ordComLoc'] & 2)==2 ? ' selected' : '') . '>' . $yyYes . '</option>';
												print '</select>'; ?></div>
					</div>
					<div class="container container6">
					  <div class="left"><?php print $xxSatDe2?>:</div>
					  <div class="right"><?php	print '<select name="saturdaydelivery" size="1">';
												print '<option value="N">' . $yyNo . '</option>';
												print '<option value="Y"' . (($alldata['ordComLoc'] & 4)==4 ? ' selected' : '') . '>' . $yyYes . '</option>';
												print '</select>' ?></div>
					</div>
					<div class="container container7">
					  <div class="left"><?php print $xxSigRe2?>:</div>
					  <div class="right"><?php	print '<select name="signaturerelease" size="1">';
												print '<option value="N">' . $yyNo . '</option>';
												print '<option value="Y"' . (($alldata['ordComLoc'] & 8)==8 ? ' selected' : '') . '>' . $yyYes . '</option>';
												print '</select>' ?></div>
					</div>
					<div class="container container8">
					  <div class="left"><?php print $xxInsDe2?>:</div>
					  <div class="right"><?php	print '<select name="insidedelivery" size="1">';
												print '<option value="N">' . $yyNo . '</option>';
												print '<option value="Y"' . (($alldata['ordComLoc'] & 16)==16 ? ' selected' : '') . '>' . $yyYes . '</option>';
												print '</select>' ?></div>
					</div>
<?php			}elseif($alldata['ordComLoc']>0 || @$forceinsuranceselection){
					if($isprinter) $thestyle=''; else $thestyle=' style="color:#FF0000"';
					$shipopts='Shipping options:';
					if(($alldata['ordComLoc'] & 1)==1){ print '<div class="container container9"><div class="left">' . $shipopts.'</div><div class="right"'.$thestyle.'>' . $xxCerCLo . '</div></div>'; $shipopts='';}
					if((($alldata['ordComLoc'] & 2)==2) || @$forceinsuranceselection){ print '<div class="container container10"><div class="left">' . $shipopts.'</div><div class="right"'.$thestyle.'>' . (($alldata['ordComLoc'] & 2)==2?$xxShiInI:$xxNoWtIn) . '</div></div>'; $shipopts='';}
					if(($alldata['ordComLoc'] & 4)==4){ print '<div class="container container11"><div class="left">' . $shipopts.'</div><div class="right"'.$thestyle.'>' . $xxSatDeR . '</div></div>'; $shipopts='';}
					if(($alldata['ordComLoc'] & 8)==8){ print '<div class="container container12"><div class="left">' . $shipopts.'</div><div class="right"'.$thestyle.'>' . $xxSigRe2 . '</div></div>'; $shipopts='';}
					if(($alldata['ordComLoc'] & 16)==16){ print '<div class="container container13"><div class="left">' . $shipopts.'</div><div class="right"'.$thestyle.'>' . $xxInsDe2 . '</div></div>'; $shipopts='';}
				} ?>
				</div><?php
			}
			if(!$isprinter && $alldata['ordAuthNumber']!='' && !$doedit){
				if($alldata['ordPayProvider']==28){
				?><div class="authcapture">
					<div class="colheading"><h2>Square Capture.</h2></div>
					<div class="container container1">
					  <div class="left">Status:</div>
					  <div class="right ectred" id="googleupdatespan"></div>
					</div>
					<div class="container container2">
					  <div class="left">Change Capture Amount:</div>
					  <div class="right"><input type="text" name="txamount" id="txamount" style="width:75px" value="" placeholder="No Change"> (<?php print number_format(($alldata['ordTotal']+$alldata['ordStateTax']+$alldata['ordCountryTax']+$alldata['ordHSTTax']+$alldata['ordShipping']+$alldata['ordHandling'])-$alldata['ordDiscount'],$GLOBALS['currDecimals'],'.','')?>)</div>
					</div>
					<div class="container container6">
					  <div class="left">Change Status To:</div>
					  <div class="right"><select id="capstatus" size="1" style="width:190px"><?php
					for($index=0; $index < $numstatus; $index++){
						if(! $isauthorized && $allstatus[$index]['statID']>2) break;
						print '<option value="' . $allstatus[$index]['statID'] . '"';
						if($alldata['ordStatus']==$allstatus[$index]['statID']) print ' selected>' . $allstatus[$index]['statPrivate'] . ' ' . date($admindatestr, $alldata['ordStatusDate']) . ' ' . date('H:i', $alldata['ordStatusDate']) . '</option>'; else print '>' . $allstatus[$index]['statPrivate'] . '</option>';
					} ?></select></div>
					</div>
					<div class="container container3">
					  <div class="left">&nbsp;</div>
					  <div class="right"><input type="button" value="Capture Order" onclick="updatesquareorder(<?php print $alldata['ordID']?>)"></div>
					</div>
				</div><?php
				}elseif($alldata['ordPayProvider']==21){
				?><div class="authcapture">
					<div class="colheading"><h2>Amazon Capture.</h2></div>
					<div class="container container1">
					  <div class="left">Status:</div>
					  <div class="right ectred" id="googleupdatespan"></div>
					</div>
					<div class="container container2">
					  <div class="left">Capture Amount:</div>
					  <div class="right"><input type="text" name="txamount" id="txamount" size="5" value="<?php print number_format(($alldata['ordTotal']+$alldata['ordStateTax']+$alldata['ordCountryTax']+$alldata['ordHSTTax']+$alldata['ordShipping']+$alldata['ordHandling'])-$alldata['ordDiscount'],$GLOBALS['currDecimals'],'.','')?>"></div>
					</div>
					<div class="container container3">
					  <div class="left">&nbsp;</div>
					  <div class="right"><input type="button" value="Capture Order" onclick="updategoogleorder('Amazon','settle',<?php print $alldata['ordID']?>)"></div>
					</div>
				</div><?php
				}elseif($alldata['ordPayProvider']==1 || $alldata['ordPayProvider']==18 || $alldata['ordPayProvider']==19){
				?><div class="authcapture">
					<div class="colheading"><h2>PayPal Authorization / Capture.</h2></div>
					<div class="container container4">
					  <div class="left">Status:</div>
					  <div class="right ectred" id="googleupdatespan"></div>
					</div>
					<div class="container container5">
					  <div class="left">Capture Amount:</div>
					  <div class="right"><input type="text" name="captureamount" id="captureamount" size="10" value="<?php print number_format(($alldata['ordTotal']+$alldata['ordStateTax']+$alldata['ordCountryTax']+$alldata['ordHSTTax']+$alldata['ordShipping']+$alldata['ordHandling'])-$alldata['ordDiscount'],$GLOBALS['currDecimals'],'.','')?>">
						<select name="additionalcapture" id="additionalcapture" size="1"><option value="0">Close Authorization</option><option value="1">Leave Open for Additional Capture</option></select>
					  </div>
					</div>
					<div class="container container6">
					  <div class="left">Note to buyer:</div>
					  <div class="right"><textarea name="buyernote" id="buyernote" cols="50" rows="4"></textarea></div>
					</div>
					<div class="container container7">
					  <div class="left">Action:</div>
					  <div class="right">
						<select name="paypalaction" id="paypalaction" size="1" onchange="setpaypalelements()"><option value="charge">Capture</option><option value="void">Void</option><option value="reauth">Reauthorization</option></select>
					  </div>
					</div>
					<div class="container container8">
					  <div class="left">&nbsp;</div>
					  <div class="right"><input type="button" value="Inform PayPal" onclick="updatepaypalorder('PayPal',<?php print $alldata['ordID']?>)"></div>
					</div>
				</div><?php
				}elseif($alldata['ordPayProvider']==3 || $alldata['ordPayProvider']==13 || $alldata['ordPayProvider']==27){
					$isauthnet=$alldata['ordPayProvider']!=27;
					$theamount=number_format(($alldata['ordTotal']+$alldata['ordStateTax']+$alldata['ordCountryTax']+$alldata['ordHSTTax']+$alldata['ordShipping']+$alldata['ordHandling'])-$alldata['ordDiscount'],$GLOBALS['currDecimals'],'.','');
				?><div class="authcapture">
					<div class="colheading"><h2><?php print ($isauthnet?'Authorize.net':'PayPal Checkout')?> Authorization / Capture.</h2></div>
					<div class="container container4">
					  <div class="left">Status:</div>
					  <div class="right ectred" id="googleupdatespan"></div>
					</div>
					<div class="container container5">
					  <div class="left" id="captureamounttxt">Capture Amount:</div>
					  <div class="right"><input type="text" name="captureamount" id="captureamount" size="10" value="<?php print $theamount?>" placeholder="<?php print $theamount?>">
<?php				if(!$isauthnet){ ?>
						<select name="additionalcapture" id="additionalcapture" size="1" style="max-width:160px"><option value="0">Close Authorization</option><option value="1">Leave Open for Additional Capture</option></select>
<?php				} ?>
					  </div>
					</div>
					<div class="container container6">
					  <div class="left">Change Status To:</div>
					  <div class="right"><select id="capstatus" size="1" style="width:190px"><?php
					for($index=0; $index < $numstatus; $index++){
						if(! $isauthorized && $allstatus[$index]['statID']>2) break;
						print '<option value="' . $allstatus[$index]['statID'] . '"';
						if($alldata['ordStatus']==$allstatus[$index]['statID']) print ' selected="selected">' . $allstatus[$index]['statPrivate'] . ' ' . date($admindatestr, $alldata['ordStatusDate']) . ' ' . date('H:i', $alldata['ordStatusDate']) . '</option>'; else print '>' . $allstatus[$index]['statPrivate'] . '</option>';
					} ?></select></div>
					</div>
					<div class="container container7">
					  <div class="left">Action:</div>
					  <div class="right">
						<select name="paypalaction" id="paypalaction" size="1" onchange="setpaypalelements()" style="width:190px">
							<option value="charge">Capture</option>
<?php				if(!$isauthnet){ ?>
							<option value="reauth">Reauthorization</option>
<?php				} ?>
							<option value="void">Void</option>
<?php				if($alldata['ordPayProvider']==27){ ?>
							<option value="refund">Refund</option>
<?php				} ?>
						</select>
					  </div>
					</div>
					<div class="container container8">
					  <div class="left">&nbsp;</div>
					  <div class="right"><input type="button" value="Inform <?php print ($isauthnet?'Authorize.net':'PayPal')?>" onclick="updatepaypalorder('<?php print ($isauthnet?'AuthNET':'PayPalCO')?>',<?php print $alldata['ordID']?>)"></div>
					</div>
				</div><?php
				}
				$sSQL="SELECT upID,upComments,upFilename FROM imageuploads WHERE upOrderID='" . escape_string($alldata['ordID']) . "'";
				$result=ect_query($sSQL) or ect_error();
				if(ect_num_rows($result)>0){
				?><div class="authcapture">
<script language="javascript">
    function getuploadedimage(tid,ispreview){
        ajaxobj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
        ajaxobj.open("GET", "ajaxservice.php?action=imageget"+(ispreview?"&preview=true":"")+"&id="+tid,true); // Make sure file is in same server
        ajaxobj.send(null);
		ajaxobj.onreadystatechange=function(){
			if(ajaxobj.readyState==4){
				var image=document.getElementById("previewimupload");
				image.src="data:image/"+ajaxobj.responseText.substr(0,3)+";base64," + ajaxobj.responseText.substr(4);
				document.getElementById("uploadpreviewdiv").style.display='';
				document.getElementById("closeprevimg").style.display='';
			}
		};
    }
</script>
					<div class="colheading">
						<h2>Image Uploads.</h2>
						<div id="uploadpreviewdiv" style="text-align:center;display:none"><img style="max-width:90%" src="" id="previewimupload"></div>
						<div id="uploadedimagestable" class="ecttable">
							<div class="ecttablerow"><div>Filename</div><div>Comments</div><div>&nbsp;</div><div>&nbsp;</div></div>
<?php
					while($rs=ect_fetch_assoc($result)){
						print '<div class="ecttablerow"><div>'. htmldisplay($rs['upFilename']) . '</div><div>'. htmldisplay($rs['upComments']) . '</div><div><input type="button" value="Preview" onclick="getuploadedimage(' . $rs['upID'] . ',true)"></div><div><input type="button" value="Download" onclick="document.location=\'ajaxservice.php?action=imageget&id=' . $rs['upID'] . '\'"></div></div>';
					}
					ect_free_result($result);
?>						</div>
						<button id="closeprevimg" title="Close Preview" style="margin:auto;display:none" onclick="document.getElementById('uploadpreviewdiv').style.display='none';this.style.display='none'">Close Preview</button>
					</div>
				</div><?php
				}
			}
			//if((int)$alldata["ordPayProvider"]==10){
			if(FALSE){			?>
					<tr>
					  <td align="center" colspan="4"><hr width="50%">
					  </td>
					</tr>
<?php			if(@$_SERVER["HTTPS"]!="on" && (@$_SERVER["SERVER_PORT"]!="443") && @$nochecksslserver!=TRUE){ ?>
					<tr>
					  <td align="center" colspan="4"><span style="color:#FF0000;font-weight:bold">You do not appear to be viewing this page on a secure (https) connection. Credit card information cannot be shown.</span></td>
					</tr>
<?php			}else{
					$ordCNum=$alldata["ordCNum"];
					if($ordCNum!=''){
						$cnumarr="";
						$encryptmethod=strtolower(@$encryptmethod);
						if($encryptmethod=="none"){
							$cnumarr=explode("&",$ordCNum);
						}elseif($encryptmethod=="mcrypt"){
							if(@$mcryptalg=="") $mcryptalg=MCRYPT_BLOWFISH;
							$td=mcrypt_module_open($mcryptalg, '', 'cbc', '');
							$thekey=@$ccencryptkey;
							$thekey=substr($thekey, 0, mcrypt_enc_get_key_size($td));
							$cnumarr=explode(" ", $ordCNum);
							$iv=@$cnumarr[0];
							$iv=@pack("H" . strlen($iv), $iv);
							$ordCNum=@pack("H" . strlen(@$cnumarr[1]), @$cnumarr[1]);
							mcrypt_generic_init($td, $thekey, $iv);
							$cnumarr=explode("&", mdecrypt_generic($td, $ordCNum));
							mcrypt_generic_deinit($td);
							mcrypt_module_close($td);
						}elseif($encryptmethod=="publickey"){
						}else{
							print '<tr><td colspan="4">WARNING: $encryptmethod is not set. Please see https://www.ecommercetemplates.com/phphelp/ecommplus/parameters.asp#encryption</td></tr>';
						}
					}
					if($encryptmethod=="publickey"){ ?>
					<tr>
					  <td align="center" colspan="4">
				  <table>
					<tr>
					  <td align="right" colspan="2"><?php print "Encrypted Data"?>:</td>
					  <td align="left" colspan="2"><textarea cols="70" rows="4" id="ordcnumenctxt"><?php
							print $ordCNum ?></textarea></td>
					</tr>
				  </table>
<script>
document.getElementById('ordcnumenctxt').select();
</script>
					  </td>
					</tr>
<?php				}else{ ?>
					<tr>
					  <td width="50%" align="right" colspan="2"><?php print $xxCCName?>:</td>
					  <td width="50%" align="left" colspan="2"><?php
							if(@$encryptmethod!=""){
									if(is_array(@$cnumarr)) print trim_(htmlspecials(URLDecode(@$cnumarr[4])));
							} ?></td>
					</tr>
					<tr>
					  <td align="right" colspan="2"><?php print $yyCarNum?>:</td>
					  <td align="left" colspan="2"><?php
							if($ordCNum!=''){
								if(is_array($cnumarr)) print htmlspecials($cnumarr[0]);
							}else{
								print "(no data)";
							} ?></td>
					</tr>
					<tr>
					  <td align="right" colspan="2"><?php print $yyExpDat?>:</td>
					  <td align="left" colspan="2"><?php
							if(@$encryptmethod!=""){
									if(is_array(@$cnumarr)) print htmlspecials(@$cnumarr[1]);
							} ?></td>
					</tr>
					<tr>
					  <td align="right" colspan="2">CVV Code:</td>
					  <td align="left" colspan="2"><?php
							if(@$encryptmethod!=""){
									if(is_array(@$cnumarr)) print htmlspecials(@$cnumarr[2]);
							} ?></td>
					</tr>
					<tr>
					  <td align="right" colspan="2">Issue Number:</td>
					  <td align="left" colspan="2"><?php
							if(@$encryptmethod!=""){
									if(is_array(@$cnumarr)) print htmlspecials(@$cnumarr[3]);
							} ?></td>
					</tr>
<?php				}
					if($ordCNum!='' && !$doedit){ ?>
				  <form method="post" action="adminorders.php?id=<?php print getget('id')?>">
					<input type="hidden" name="delccdets" value="<?php print getget('id')?>">
					<tr>
					  <td width="100%" align="center" colspan="4"><input type="submit" value="<?php print $yyDelCC?>"></td>
					</tr>
				  </form>
<?php				}
				}
			}
@include './inc/customppplugin.php'; ?>

<?php	$WSP=''; $OWSP=''; $percdisc=''; $wholesaledisc=FALSE;
		if($alldata['ordClientID']!=0){
			$sSQL="SELECT clActions,clPercentDiscount FROM customerlogin WHERE clID='".$alldata['ordClientID']."'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				if(($rs['clActions'] & 8)==8){
					$WSP='pWholesalePrice AS ';
					$wholesaledisc=TRUE;
					if(@$wholesaleoptionpricediff==TRUE) $OWSP='optWholesalePriceDiff AS ';
				}
				if(($rs['clActions'] & 16)==16){
					$WSP=((100.0-(float)$rs['clPercentDiscount'])/100.0) . '*'.(($rs['clActions'] & 8)==8?'pWholesalePrice':'pPrice').' AS ';
					$percdisc=$rs['clPercentDiscount'];
					$OWSP=((100.0-$rs['clPercentDiscount'])/100.0) . '*'.(($rs['clActions'] & 8)==8 && @$wholesaleoptionpricediff?'optWholesalePriceDiff':'optPriceDiff').' AS ';
				}
			}
			ect_free_result($result);
		}
		$displayimagecolumn=($isinvoice&&(@$imgonorderdetails&4)==4)||(!$isinvoice&&$isprinter&&(@$imgonorderdetails&2)==2)||(!$isprinter&&(@$imgonorderdetails&1)==1)
		?><div id="producttable" class="producttable">
			<div class="ectorderrow ectorderhead">
			  <div class="ordrowprodidcol"><?php print $xxPrId?></div>
			  <div class="ordrowprodnamecol"><?php print $xxPrNm?></div>
			  <div class="ordrowoptionscol"><?php print $xxPrOpts?></div>
<?php	if($isinvoice) print '<div class="ordrowunitpricecol">' . $xxUnitPr . '</div>';
		if(! ($isprinter || $doedit)) print '<div class="ordrowweightcol"><div class="largescreenquant ordsmallheader">Weight</div></div>' ?>
			  <div class="ordrowquantcol"><div class="largescreenquant"><?php print $xxQuant?></div></div>
<?php	if(! $isprinter || $isinvoice) print '<div class="' . ($doedit?'ordroweditpricecol ':'ordrowpricecol ') . 'ordsmallheader">' . ($doedit?$xxUnitPr:$xxPrice) . '</div>';
		if($doedit) print '<div class="ordrowdeletecol ordsmallheader">DEL</div>' ?>
			</div>
<?php	$totoptpricediff=0;
		$stockjs='';
		if(@$initialpackweight!='' && $alldata['ordShipCarrier']!=5) $totweight=$initialpackweight; else $totweight=0;
		if($allorders!='' && ect_num_rows($allorders)>0){
			$totoptpricediff=0;
			$rowcounter=0;
			$ordrowclass='orderevenrow';
			while($rsOrders=ect_fetch_assoc($allorders)){
				if($ordrowclass=='orderoddrow') $ordrowclass='orderevenrow'; else $ordrowclass='orderoddrow';
				$optpricediff=$optweightdiff=0;
				$cartGiftMessage=trim_($rsOrders['cartGiftMessage']);
				if($rsOrders['pStockByOpts']==0 && $alldata['ordAuthStatus']!='MODWARNOPEN') $stockjs.="stock['pid_" . $rsOrders['cartProdId'] . "']+=" . $rsOrders['cartQuantity'] . ";\r\n";
?>
			<div class="ectorderrow<?php if($rsOrders['cartGiftWrap']!=0 && ! $isinvoice) print ' ectgiftwraprow'; print ' '.$ordrowclass?>">
			  <div class="ordrowprodidcol"><?php
				$orddetailsimage='';
				if($displayimagecolumn){
					$sSQL="SELECT imageSrc FROM productimages WHERE imageProduct='" . escape_string($rsOrders['cartProdId']) . "' AND (imageType=0 OR imageType=1) ORDER BY imageType,imageNumber";
					$result=ect_query($sSQL) or ect_error();
					if($rs=ect_fetch_assoc($result))
						$orddetailsimage=$rs['imageSrc'];
					else
						$orddetailsimage=@$defaultorddetailsimage;
					if($orddetailsimage!=''){
						$orddetailsimage=(strtolower(substr($orddetailsimage,0,5))!='http:' && strtolower(substr($orddetailsimage,0,6))!='https:' && substr($orddetailsimage,0,1)!='/'?'../':'').$orddetailsimage;
						print '<div class="orddetailsimg"><img class="orddetailsimg" src="' . $orddetailsimage . '" alt=""><div>';
					}
				} ?>
			  <div class="smallscreenquant"><?php print editspecial($rsOrders['cartQuantity'],'smallquant'.$rowcounter,3,'onkeyup="document.getElementById(\'quant'.$rowcounter.'\').value=this.value" onchange="dorecalc(true)"')?> x </div><?php
				if($doedit) print '<input type="button" value="..." onclick="updateoptions(' . $rowcounter . ')">&nbsp;<input type="hidden" id="stateexempt' . $rowcounter . '" value="' . (($rsOrders['pExemptions'] & 1)==1?'true':'false') . '"><input type="hidden" id="countryexempt' . $rowcounter . '" value="' . (($rsOrders['pExemptions'] & 2)==2?'true':'false') . '">';
				if($doedit && getget('clone')!='true') print '<input type="hidden" name="cartid' . $rowcounter . '" value="' . htmlspecials($rsOrders['cartID']) . '">';
				$thelink='';
				if(trim_($rsOrders['cartOrigProdID'])!='') $cartprodid=$rsOrders['cartOrigProdID']; else $cartprodid=$rsOrders['cartProdId'];
				$sSQL="SELECT pID,".getlangid('pName',1).",pStaticPage,pStaticURL,pDisplay FROM products WHERE pDisplay<>0 AND pID='".escape_string($cartprodid)."'";
				$result=ect_query($sSQL) or ect_error();
				if($rs=ect_fetch_assoc($result)){
					$thelink=(@$GLOBALS['seodetailurls'] ? stripUrlPath($storeurl) : $storeurl) . getdetailsurl($rs['pID'],$rs['pStaticPage'],$rs[getlangid('pName',1)],$rs['pStaticURL'],'','');
				}
				ect_free_result($result);
				if($doedit || $isprinter) print editspecial($rsOrders['cartProdId'],'prodid' . $rowcounter,18,'AUTOCOMPLETE="off" onkeydown="return combokey(this,event)" onkeyup="combochange(this,event)"'); else print ($rsOrders['cartProdId']!=$giftwrappingid?'<a href="' . $thelink . '" target="_blank">':'') . htmlspecials($rsOrders['cartProdId']) . ($rsOrders['cartProdId']!=$giftwrappingid?'</a>':'');
				if($rsOrders['cartProdId']==$giftcertificateid){
					$sSQL="SELECT gcID FROM giftcertificate WHERE gcCartID=" . $rsOrders['cartID'];
					$result=ect_query($sSQL) or ect_error();
					if($rs=ect_fetch_assoc($result)){
						print '<input type="button" value="'.$yyView.'" onclick="document.location=\'admingiftcert.php?id='.$rs['gcID'].'\'" style="margin-left:4px">';
					}
					ect_free_result($result);
				}
				if($doedit) print showgetoptionsselect('selectprodid'.$rowcounter);
				if($orddetailsimage!='') print '</div></div>';
				?></div>
			  <div class="ordrowprodnamecol"><?php
				print str_replace('&amp;','&',editspecial(decodehtmlentities($rsOrders['cartProdName']),'prodname' . $rowcounter,24,'AUTOCOMPLETE="off" onkeydown="return combokey(this,event)" onkeyup="combochange(this,event)"'));
				if($doedit){
					print showgetoptionsselect('selectprodname'.$rowcounter);
				}else{
					$sSQL="SELECT productpackages.pID,quantity,pName,quantity FROM productpackages INNER JOIN products on productpackages.pID=products.pID WHERE packageID='" . $rsOrders['cartProdId'] . "'";
					$result=ect_query($sSQL) or ect_error();
					if(ect_num_rows($result)>0){
						print '<div class="ordpackage">';
						while($rs=ect_fetch_assoc($result))
							print '<div class="ordpackagerow"><div>&nbsp;&gt;&nbsp;' . $rs['pID'] . ':</div><div>' . $rs['pName'] . '</div><div>' . $rs['quantity'] . '</div></div>';
						print '</div>';
					}
					ect_free_result($result);
				}
			?></div>
			  <div class="ordrowoptionscol"><?php
				if($doedit) print '<div id="optionsspan' . $rowcounter . '">';
				$sSQL="SELECT coOptGroup,coCartOption,coPriceDiff,coWeightDiff,coOptID,optGroup FROM cartoptions LEFT JOIN options ON cartoptions.coOptID=options.optID WHERE coCartID=" . $rsOrders["cartID"] . " ORDER BY coID";
				$result=ect_query($sSQL) or ect_error();
				if(ect_num_rows($result) > 0 || ($rsOrders['cartGiftWrap']!=0 && $cartGiftMessage!='' && ! $isinvoice)){
					$rs2=ect_fetch_assoc($result);
					if($rsOrders['pStockByOpts']!=0 && $alldata['ordAuthStatus']!='MODWARNOPEN') $stockjs.="stock['oid_" . $rs2['coOptID'] . "']+=" . $rsOrders['cartQuantity'] . ";\r\n";
					if($doedit) print '<div class="optionstable">';
					if(ect_num_rows($result) > 0) do{
						if($doedit){
							print '<div class="optionstablerow"><div class="optionstableleft">' . $rs2['coOptGroup'] . ':</div><div>';
							if(is_null($rs2["optGroup"])){
								print 'xxxxxx';
							}else{
								$sSQL="SELECT optID," . getlangid('optName',32) . ','.$OWSP."optPriceDiff,optType,optFlags,optStock,optTxtCharge,optWeightDiff FROM options INNER JOIN optiongroup ON options.optGroup=optiongroup.optGrpID WHERE optGroup=" . $rs2["optGroup"] . ' ORDER BY optID';
								$result2=ect_query($sSQL) or ect_error();
								if($rsl=ect_fetch_assoc($result2)){
									if(abs($rsl['optType'])==1 || abs($rsl['optType'])==2 || abs($rsl['optType'])==4){
										print '<select onchange="dorecalc(true)" name="optn' . $rowcounter . '_' . $rs2["coOptID"] . '" id="optn' . $rowcounter . '_' . $rs2["coOptID"] . '" size="1">';
										do {
											print '<option value="' . $rsl["optID"] . "|" . (($rsl["optFlags"] & 1)==1 ? ($rsOrders["cartProdPrice"]*$rsl["optPriceDiff"])/100.0 : $rsl["optPriceDiff"]) . '"';
											if($rsl["optID"]==$rs2["coOptID"]) print ' selected';
											print '>' . $rsl[getlangid("optName",32)];
											if((float)$rsl["optPriceDiff"]!=0){
												print ' ';
												if((float)$rsl["optPriceDiff"] > 0) print '+';
												if(($rsl["optFlags"] & 1)==1)
													print number_format(($rsOrders["cartProdPrice"]*$rsl["optPriceDiff"])/100.0,2,'.','');
												else
													print number_format($rsl["optPriceDiff"],2,'.','');
											}
											print '</option>';
										} while($rsl=ect_fetch_assoc($result2));
										print '</select>';
									}else{
										if($rsl['optTxtCharge']!=0) print '<script>opttxtcharge[' . $rsl['optID'] . ']=' . $rsl['optTxtCharge'] . ';</script>';
										print "<input type='hidden' name='optn" . $rowcounter . '_' . $rs2["coOptID"] . "' value='" . $rsl["optID"] . "'><textarea name='voptn" . $rowcounter . '_' . $rs2["coOptID"] . "' id='voptn". $rowcounter. '_' . $rs2["coOptID"] . "' cols='30' rows='3'>";
										print htmlspecials($rs2['coCartOption']) . '</textarea>';
									}
								}
								ect_free_result($result2);
							}
							print '</div></div>';
						}else{
							print '<div class="orderoptline optid' . $rs2['coOptID'] . '"><div class="orderoptgrp">' . $rs2['coOptGroup'] . '</div><div class="orderoption">' . str_replace(array('  ',"\r\n","\n"),array('&nbsp;&nbsp;','<br>','<br>'),htmlspecials($rs2['coCartOption'])) . '</div></div>';
						}
						if($doedit)
							$optpricediff+=$rs2["coPriceDiff"];
						else{
							$rsOrders['cartProdPrice']+=$rs2['coPriceDiff'];
							$optweightdiff+=$rs2['coWeightDiff'];
						}
					}while($rs2=ect_fetch_assoc($result));
					if($rsOrders['cartGiftWrap']!=0 && $cartGiftMessage!='' && ! $isinvoice){
						print ($doedit?'<div class="optionstablerow"><div class="optionstableleft ordgiftwrapmessaget">':'') . 'Gift Wrap Message:' . ' ' . ($doedit?'</div><div>':'') . $cartGiftMessage . ($doedit?'</div></div>':'<br>');
					}
					if($doedit) print '</div>';
				}else{
					print '<div>-</div>';
				}
				ect_free_result($result);
				if($doedit) print '</div>' ?></div>
<?php			if($isinvoice) print '<div class="ordrowunitpricecol">' . FormatEuroCurrency($rsOrders['cartProdPrice']) . '</div>';
				$prodweight=($rsOrders['pWeight']+$optweightdiff)*$rsOrders['cartQuantity'];
				$totweight+=$prodweight;
				if(! ($isprinter || $doedit)) print '<div class="ordrowweightcol"><div class="largescreenquant">' . round($prodweight,3) . '</div></div>'; ?>
			  <div class="ordrowquantcol<?php print ($rsOrders['cartQuantity']>1?' ordmultiquantcol':'')?>"><div class="largescreenquant"><?php print editspecial($rsOrders['cartQuantity'],'quant' . $rowcounter,5,'onkeyup="document.getElementById(\'smallquant'.$rowcounter.'\').value=this.value" onchange="dorecalc(true)"')?></div></div>
<?php			if(! $isprinter || $isinvoice){ ?>
			  <div class="<?php print ($doedit?'ordroweditpricecol':'ordrowpricecol') ?>"><?php if($doedit) print editnumeric($rsOrders['cartProdPrice'],'price' . $rowcounter,7,'class="orderprice" onchange="dorecalc(true)" '); else print FormatEuroCurrency($rsOrders["cartProdPrice"]*$rsOrders["cartQuantity"])?>
<?php					if($doedit){
							print '<input type="hidden" id="optdiffspan' . $rowcounter . '" value="' . $optpricediff . '">';
							$totoptpricediff+=($optpricediff*$rsOrders["cartQuantity"]);
						}
			?></div>
<?php			}
				if($doedit) print '<div class="ordrowdeletecol"><input type="checkbox" name="del_' . $rowcounter . '" id="del_' . $rowcounter . '" value="yes"></div>' ?>
			</div>
<?php				$rowcounter++;
			}
		}
		if($allorders!='') ect_free_result($allorders);
?>
		</div>
<?php	if(! $isprinter || $isinvoice){ ?>
		<div>
			<div class="ectorderfunctions">
<?php		if($doedit){ ?>
				<div style="padding:20px;text-align:center">
<?php			print '<input style="width:30px;" type="button" value="-" onclick="extraproduct(\'-\')"> ' . $yyMoProd . ' <input style="width:30px;" type="button" value="+" onclick="extraproduct(\'+\')">'?>
				</div>
				<div style="display:table;width:100%">
<?php			if($GLOBALS['useStockManagement']) print '<div class="ectorderrow"><div style="width:40%;text-align:right"><input type="checkbox" name="updatestock" value="ON" checked="checked"></div><div>' . $yyUpStLv . '</div></div>' ?>
					<div class="ectorderrow">
				<div style="text-align:right"><input type="checkbox" id="wholesaledisc" value="ON"<?php print ($wholesaledisc?' checked="checked"':'')?>></div><div><?php print $yyWholPr?></div>
					</div>
					<div class="ectorderrow">
				<div style="text-align:right"><input type="text" id="percdisc" size="3" value="<?php print $percdisc?>"></div><div><?php print $yyPerDis?></div>
					</div>
				</div>
				<div style="padding:20px;text-align:center">
					<input type="button" value="<?php print $yyRecal?>" onclick="dorecalc(false)">
				</div>
<?php		}else
				print '&nbsp;';
?>
			</div><div class="ecttotalcolumn">
				<hr class="ordertotals">
			<div class="ecttotaltable">
<?php		if($doedit){ ?>
				<div class="ecttotalrow">
					<div><?php print str_replace(' ', '&nbsp;', $yyOptTot)?></div>
					<div><span id="optdiffspan"><?php print number_format($totoptpricediff, 2, '.', '')?></span><script>
			var stock=new Array();
<?php			$optgroups='';
				$addcomma='';
				if($theid!='0'){
					$sSQL="SELECT DISTINCT cartID,pID,pInStock,pStockByOpts FROM cart INNER JOIN products ON cart.cartProdId=products.pID WHERE cartOrderID=".$theid;
					$result=ect_query($sSQL) or ect_error();
					while($rs=ect_fetch_assoc($result)){
						print "stock['pid_".$rs['pID']."']=";
						if($rs['pStockByOpts']==0)
							print $rs['pInStock'].";\r\n";
						else{
							print "'bo';\r\n";
							$sSQL="SELECT coID,optStock,coOptID,optGrpID 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=".$rs['cartID'];
							$result2=ect_query($sSQL) or ect_error();
							while($rs2=ect_fetch_assoc($result2)){
								$optgroups.=$addcomma . $rs2['optGrpID'];
								$addcomma=',';
							}
							ect_free_result($result2);
						}
					}
					ect_free_result($result);
				}
				if($optgroups!=''){
					$sSQL="SELECT optID,optStock FROM options WHERE optGroup IN (" . $optgroups . ")";
					$result=ect_query($sSQL) or ect_error();
					while($rs=ect_fetch_assoc($result)){
						print "stock['oid_" . $rs['optID']."']=" . $rs['optStock'] . ";\r\n";
					}
					ect_free_result($result);
				}
				print $stockjs;
				if(getget('id')=='new') print "extraproduct('+');\r\n";
?></script></div>
				</div>
<?php		}
			if(!$isprinter&&!$doedit){ ?>
				<div class="ecttotalrow">
					<div><?php print 'Total Weight'?>:</div>
					<div><?php print round($totweight,3)?></div>
				</div>
<?php		} ?>
				<div class="ecttotalrow">
					<div><?php print str_replace(' ','&nbsp;',$xxOrdTot)?>:</div>
					<div><?php print editnumeric($alldata['ordTotal'],'ordtotal',7,'')?></div>
				</div>
<?php		if($isprinter && @$combineshippinghandling==TRUE){ ?>
				<div class="ecttotalrow">
					<div><?php print $xxShipHa?>:</div>
					<div><?php print FormatEuroCurrency($alldata['ordShipping']+$alldata['ordHandling'])?></div>
				</div>
<?php		}else{
				if((float)$alldata['ordShipping']!=0.0 || $doedit){ ?>
				<div class="ecttotalrow">
					<div><?php print $xxShippg?>:</div>
					<div><?php print editnumeric($alldata['ordShipping'],'ordShipping',7,'')?></div>
<?php			if($doedit) print '<div><input type="button" value="'.'Calculate'.'" onclick="calcshipping()"></div>' ?>
				</div>
<?php			}
				if((float)$alldata['ordHandling']!=0.0 || $doedit){ ?>
				<div class="ecttotalrow">
					<div><?php print $xxHndlg?>:</div>
					<div><?php print editnumeric($alldata['ordHandling'],'ordHandling',7,'')?></div>
				</div>
<?php			}
			}
			if((float)$alldata['ordDiscount']!=0.0 || $doedit){ ?>
				<div class="ecttotalrow">
					<div><?php print $xxDscnts?>:</div>
					<div><span style="color:#FF0000"><?php print editnumeric($alldata['ordDiscount'],'ordDiscount',7,'')?></span></div>
				</div>
<?php		}
			if((float)$alldata['ordStateTax']!=0.0 || $doedit){ ?>
				<div class="ecttotalrow">
					<div><?php print $xxStaTax?>:</div>
					<div><?php print editnumeric($alldata['ordStateTax'],'ordStateTax',7,'')?></div>
<?php			if($doedit) print '<div><input type="checkbox" id="orderstatetaxexempt"' . (! $orderstatetaxexempt?' checked="checked"':'') . ' title="Liable / Exempt" onchange="document.getElementById(\'staterate\').disabled=!this.checked"><input type="text" style="text-align:right;width:24px" name="staterate" id="staterate" size="2" value="' . $statetaxrate . '"' . ($orderstatetaxexempt?' disabled="disabled"':'') . '>%</div>' ?>
				</div>
<?php		}
			if((float)$alldata['ordCountryTax']!=0.0 || $doedit){ ?>
				<div class="ecttotalrow">
					<div><?php print $xxCntTax . (!$doedit && $countrytaxrate!=0 ? ' - '.$countrytaxrate.'%' : '') ?>:</div>
					<div><?php print editnumeric($alldata['ordCountryTax'],'ordCountryTax',7,'')?></div>
<?php			if($doedit) print '<div><input type="checkbox" id="ordercountrytaxexempt"' . (! $ordercountrytaxexempt?' checked="checked"':'') . ' title="Liable / Exempt" onchange="document.getElementById(\'countryrate\').disabled=!this.checked"><input type="text" style="text-align:right;width:24px" name="countryrate" id="countryrate" size="2" value="' . $countrytaxrate . '"' . ($ordercountrytaxexempt?' disabled="disabled"':'') . '>%</div>' ?>
				</div>
<?php		}
			if((float)$alldata['ordHSTTax']!=0.0 || ($doedit && $origCountryID==2)){ ?>
				<div class="ecttotalrow">
					<div><?php print $xxHST?>:</div>
					<div><?php print editnumeric($alldata['ordHSTTax'],'ordHSTTax',7,'')?></div>
<?php			if($doedit) print '<div><input type="text" style="text-align:right;width:10px" name="hstrate" id="hstrate" size="2" value="' . $hsttaxrate . '">%</div>' ?>
				</div>
<?php		} ?>
				<div class="ecttotalrow">
					<div><?php print $xxGndTot?>:</div>
					<div class="ordergrandtotal" id="grandtotalspan"><?php print FormatEuroCurrency(($alldata['ordTotal']+$alldata['ordStateTax']+$alldata['ordCountryTax']+$alldata['ordHSTTax']+$alldata['ordShipping']+$alldata['ordHandling'])-$alldata['ordDiscount'])?></div>
				</div>
			</div>
			</div>
		</div>
<?php	} // ! $isprinter || $isinvoice

		if($isprinter && ! @isset($packingslipfooter)) $packingslipfooter=@$invoicefooter;
		if($isinvoice && @$invoicefooter!=''){ ?>
		<div class="orderfooter invoicefooter"><?php print $invoicefooter?></div>
<?php	}elseif($isprinter && @$packingslipfooter!=''){ ?>
		<div class="orderfooter packslipfooter"><?php print $packingslipfooter?></div>
<?php	}elseif($doedit){ ?>
		<div style="padding:30px;text-align:center"><input type="submit" value="<?php print $yyUpdate?>"></div>
<?php	}
		if(getget('id')!='multi' && getget('id')!='new' && !$doedit){ ?>
		<div class="bottombuttons">
			<div class="bottombuttonleft"><?php
			print '<div class="bottombuttongroup">';
			print '<input '.(@$previousid==''?'disabled="disabled" ':'').'class="no-print" style="width:110px;margin:2px" type="button" value="&laquo; '.$yyPrev.'" onclick="researchformgo(\''.@$previousid.'\',0)">';
			print '<input '.(@$previousbysearch==''?'disabled="disabled" ':'').'class="no-print" style="width:110px;margin:2px" type="button" value="'."Prev. By Search".'" onclick="researchformgo(\''.@$previousbysearch.'\',0)"><br>';
			print '</div><div class="bottombuttongroup">';
			print '<input '.(!(getget("printer")=="true" || getget("invoice")=="true")?'disabled="disabled" ':'').'class="no-print" style="width:110px;margin:2px" type="button" value="'.'Print'.'" onclick="window.print()">';
			print '<input class="no-print" style="width:110px;margin:2px" type="button" value="'.'Orders'.'" onclick="researchformgo(\''.$alldata['ordID'].'\',3)">';
			print '</div>';
			?></div><div class="bottombuttonright">
<?php		print '<div class="bottombuttongroup">';
			print '<input '.(@$nextbysearch==''?'disabled="disabled" ':'').'class="no-print" style="width:110px;margin:2px" type="button" value="'.'Next By Search'.'" onclick="researchformgo(\''.@$nextbysearch.'\',0)">';
			print '<input '.(@$nextid==''?'disabled="disabled" ':'').'class="no-print" style="width:110px;margin:2px" type="button" value="'.$yyNext.' &raquo;" onclick="researchformgo(\''.@$nextid.'\',0)"><br>';
			print '</div><div class="bottombuttongroup">';
			print '<input '.(@$dropshipper!=''?'disabled ':'').'class="no-print" style="width:110px;margin:2px" type="button" value="'.(getget("invoice")=="true"?"Details":"Invoice").'" onclick="researchformgo(\''.$alldata['ordID']."',".(getget("invoice")=="true"?4:1).')">';
			print '<input class="no-print" style="width:110px;margin:2px" type="button" value="'.(getget("printer")=="true"?"Details":"Packing Slip").'" onclick="researchformgo(\''.$alldata['ordID']."',".(getget("printer")=="true"?4:2).')">';
			print '</div>';
?>			</div>
		</div>
<?php	} ?>		
		
		
	  </div>
<?php
		if($doedit) print '</form>';
	} // foreach($idlist as $theid)
}else{
	$hasshiptheory=FALSE;
	$sSQL='SELECT shipTheoryUser,shipTheoryPass FROM adminshipping WHERE adminShipID=1';
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)){
		$hasshiptheory=trim($rs['shipTheoryUser'])!=''&&trim($rs['shipTheoryPass'])!='';
	}
	ect_free_result($result);
	$sSQL="SELECT ordID FROM orders WHERE ordStatus=1";
	if(getpost('act')!="purge") $sSQL.=" AND ordStatusDate<'" . date("Y-m-d H:i:s", time()-(3*60*60*24)) . "'";
	$result=ect_query($sSQL) or ect_error();
	while($rs=ect_fetch_assoc($result)){
		$theid=$rs["ordID"];
		$delOptions="";
		$addcomma="";
		$result2=ect_query("SELECT cartID FROM cart WHERE cartOrderID=" . $theid) or ect_error();
		while($rs2=ect_fetch_assoc($result2)){
			$delOptions.=$addcomma . $rs2["cartID"];
			$addcomma=",";
		}
		ect_free_result($result2);
		if($delOptions!=''){
			$sSQL="DELETE FROM cartoptions WHERE coCartID IN (" . $delOptions . ")";
			ect_query($sSQL) or ect_error();
		}
		ect_query("DELETE FROM cart WHERE cartOrderID=" . $theid) or ect_error();
		ect_query("DELETE FROM giftcertificate WHERE gcOrderID=" . $theid) or ect_error();
		ect_query("DELETE FROM giftcertsapplied WHERE gcaOrdID=" . $theid) or ect_error();
		ect_query("DELETE FROM orders WHERE ordID=" . $theid) or ect_error();
		ect_query("DELETE FROM couponsapplied WHERE cpaOrdID=" . $theid) or ect_error();
	}
	ect_free_result($result);
	if(getpost('act')=='authorize'){
		ect_query("UPDATE orders set ordAuthNumber='" . escape_string(getpost('authcode')!='' ? getpost('authcode') : $yyManAut) . "' WHERE ordID=" . getpost('id')) or ect_error();
		ect_query('UPDATE cart SET cartCompleted=1 WHERE cartOrderID=' . getpost('id')) or ect_error();
		updateorderstatus(getpost('id'), 3, getpost('emailstat')=='1');
	}elseif(getpost('act')=='unpending'){
		ect_query("UPDATE orders set ordAuthStatus='' WHERE ordID=" . getpost('id')) or ect_error();
		ect_query("UPDATE orders set ordShipType='" . escape_string($yyMoWarn) . "' WHERE ordShipType='MODWARNOPEN' AND ordID=" . getpost('id')) or ect_error();
		ect_query("UPDATE orders set ordAuthNumber='" . escape_string($yyManAut) . "' WHERE ordAuthNumber='' AND ordID=" . getpost('id')) or ect_error();
		ect_query("UPDATE cart SET cartCompleted=1 WHERE cartOrderID=" . getpost('id')) or ect_error();
		$sSQL="SELECT ordStatus FROM orders WHERE ordID=" . getpost('id');
		$result=ect_query($sSQL) or ect_error();
		$rs=ect_fetch_assoc($result);
		$oldordstatus=$rs['ordStatus'];
		ect_free_result($result);
		if($oldordstatus<3) updateorderstatus(getpost('id'), $oldordstatus<3 ? 3 : $oldordstatus, getpost('emailstat')=='1');
	}elseif(getpost('act')=='editablefield'){
		setcookie('editablefield', getpost('id'), time()+31536000, '/', '', @$_SERVER['HTTPS']=='on');
	}elseif(getpost('act')=='searchfield'){
		setcookie('searchfield', getpost('id'), time()+31536000, '/', '', @$_SERVER['HTTPS']=='on');
	}elseif(getpost('act')=='status' && getpost('theeditablefield')!='' && getpost('theeditablefield')!='status' && getpost('theeditablefield')!='shippedstatus'){
		$maxitems=(int)getpost('maxitems');
		$editfield=getpost('theeditablefield');
		if($editfield=='orderlines'){
			if(getpost('emailstat')=='1'){
				$replaceone=FALSE;
				$sSQL='SELECT shiplineitemsubject,shiplineitemsubject2,shiplineitemsubject3,shiplineitememail,shiplineitememail2,shiplineitememail3 FROM emailmessages WHERE emailID=1';
				$result=ect_query($sSQL) or ect_error();
				if($rs=ect_fetch_assoc($result)){
					$shiplineitemsubject[1]=$rs['shiplineitemsubject'];
					$shiplineitememail[1]=$rs['shiplineitememail'];
					$shiplineitemsubject[2]=$rs['shiplineitemsubject2'];
					$shiplineitememail[2]=$rs['shiplineitememail2'];
					$shiplineitemsubject[3]=$rs['shiplineitemsubject3'];
					$shiplineitememail[3]=$rs['shiplineitememail3'];
				}
				ect_free_result($result);
			}
			foreach($_POST as $objItem => $objValue){
				if(substr($objItem,0,8)=='lineitem'){
					$replaceone=FALSE;
					$cartid=(int)substr($objItem,8);
					$isshipped=(getpost('isshipped'.$cartid)=='1'?1:0);
					$linetrackno=trim_(getpost('linetrackno'.$cartid));
					if(is_numeric($cartid)){
						if(getpost('emailstat')=='1' && $isshipped==1){
							$emailsubject='';
							$ose='';
							$ordemail='';
							$result=ect_query("SELECT ordID,ordStatus,ordAuthNumber,ordEmail,ordDate,ordName,ordLastName,ordLang,cartProdID,cartProdName,cartTrackNum,cartItemShipped FROM cart INNER JOIN orders ON cart.cartOrderID=orders.ordID WHERE cartID=".$cartid) or ect_error();
							if($rs=ect_fetch_assoc($result)){
								if($rs['cartItemShipped']==0){
									$languageid=$rs['ordLang']+1;
									if(($adminlangsettings & 4096)==0) $languageid=1;
									if($shiplineitemsubject[$languageid]!='') $emailsubject=$shiplineitemsubject[$languageid];
									$ose=$shiplineitememail[$languageid];
									$ordemail=$rs['ordEmail'];
									$orddate=strtotime($rs['ordDate']);
									if(@$fordertimeformatstr!=''){
										setlocale(LC_TIME, $adminLocale);
										$orddate=strftime($fordertimeformatstr, $orddate);
									}else
										$orddate=date($dateformatstr, $orddate) . ' ' . date('H:i', $orddate);
									
									$thecarrier=getcarrierfromtrack($rs['cartTrackNum'],$thelink);

									$emailsubject=replaceemailtxt($emailsubject, '%dropshipper'.$dropshipper.'%', '%ectpreserve%', $replaceone);
									$ose=replaceemailtxt($ose, '%dropshipper'.$dropshipper.'%', '%ectpreserve%', $replaceone);

									$emailsubject=preg_replace('/{\%dropshipper[^}]+}/i','',$emailsubject);
									$ose=preg_replace('/{\%dropshipper[^}]+}/i','',$ose);
									
									$emailsubject=str_replace('%orderid%', $rs['ordID'], $emailsubject);
									$ose=str_replace('%orderid%', $rs['ordID'], $ose);
									
									$emailsubject=str_replace('%pid%', $rs['cartProdID'], $emailsubject);
									$ose=str_replace('%pid%', $rs['cartProdID'], $ose);
									
									$emailsubject=str_replace('%pname%', $rs['cartProdName'], $emailsubject);
									$ose=str_replace('%pname%', $rs['cartProdName'], $ose);
									
									$emailsubject=str_replace('%ordername%', trim_($rs['ordName'].' '.$rs['ordLastName']), $emailsubject);
									$ose=str_replace('%ordername%', trim_($rs['ordName'].' '.$rs['ordLastName']), $ose);
									
									$emailsubject=str_replace('%orderdate%', $orddate, $emailsubject);
									$ose=str_replace('%orderdate%', $orddate, $ose);
									
									$emailsubject=str_replace('%shipcarrier%', strtoupper($thecarrier), $emailsubject);
									$ose=str_replace('%shipcarrier%', strtoupper($thecarrier), $ose);
									
									$ose=str_replace('%shipcarrierlink%', $thelink . $rs['cartTrackNum'], $ose);
									
									$emailsubject=str_replace('%trackingnum%', $rs['cartTrackNum'], $emailsubject);
									$ose=replaceemailtxt($ose, '%trackingnum%', $rs['cartTrackNum'], $replaceone);
									$ose=replaceemailtxt($ose, '%hastrackingnum%', $rs['cartTrackNum']!=''?'%ectpreserve%':'', $replaceone);

									$ose=str_replace('%nl%', $emlNl, $ose);
								}
							}
							ect_free_result($result);
							if($emailsubject!='' && $ose!='')
								dosendemail($ordemail,$emailAddr,'',$emailsubject,$ose);
						}
						$sSQL="UPDATE cart SET cartDateAdded='" . date('Y-m-d', time() + ($GLOBALS['dateadjust']*60*60)) . "' WHERE cartID=" . $cartid . " AND (cartItemShipped<>" . $isshipped . " OR cartTrackNum<>'" . escape_string($linetrackno) . "')";
						ect_query($sSQL) or ect_error();
						$sSQL="UPDATE cart SET cartItemShipped=" . $isshipped . ",cartTrackNum='" . escape_string($linetrackno) . "' WHERE cartID=" . $cartid;
						ect_query($sSQL) or ect_error();
					}
				}
			}
		}else{
			for($mindex=0; $mindex < $maxitems; $mindex++){
				$iordid=getpost('ordid' . $mindex);
				ect_query("UPDATE orders SET ord" . getpost('theeditablefield') . "='" . escape_string(@$_POST[$editfield . $mindex]) . "' WHERE ordID=" . $iordid);
			}
		}
	}elseif(getpost('act')=='status'){
		$maxitems=(int)getpost('maxitems');
		for($mindex=0; $mindex < $maxitems; $mindex++){
			if(getpost('ordStatus' . $mindex)!='')
				updateorderstatus(getpost('ordid' . $mindex), (int)getpost('ordStatus' . $mindex), getpost('emailstat')=='1');
		}
	}
	getdates();
	$origsearchtext=getrequest('searchtext');
	$sSQL='SELECT DISTINCT ordID,ordName,ordLastName,payProvName,ordAuthNumber,ordDate,ordStatus,ordTotal-ordDiscount AS ordTot,ordTransID,ordTransSession,ordAVS,ordCVV,ordPayProvider,payProvDemo,ordAuthStatus,ordTrackNum,ordInvoice,ordShipType,ordEmail,ordAddInfo FROM orders INNER JOIN payprovider ON payprovider.payProvID=orders.ordPayProvider';
	if($dropshipper!='')
		$sSQL.=" INNER JOIN cart ON orders.ordID=cart.cartOrderID INNER JOIN products ON cart.cartProdID=products.pID";
	elseif(@$_REQUEST['orddiscount']!='')
		$sSQL.=" INNER JOIN couponsapplied ON orders.ordID=couponsapplied.cpaOrdID";
	elseif(getpost('abandonedstatus')!='' && getpost('abandonedstatus')!='1')
		$sSQL.=' INNER JOIN abandonedcartemail ON orders.ordID=abandonedcartemail.aceOrderID';
	$whereSQL='';
	getordsearchwheresql();
	$sSQL.=$whereSQL;
	$editablefield=@$_COOKIE['editablefield'];
	$sortorder=@$_COOKIE['ordersort'];
	if($sortorder=='oidd')
		$sSQL.=' ORDER BY ordID DESC';
	elseif($sortorder=='orna')
		$sSQL.=' ORDER BY ordName';
	elseif($sortorder=='ornd')
		$sSQL.=' ORDER BY ordName DESC';
	elseif($sortorder=='orda')
		$sSQL.=' ORDER BY ordDate';
	elseif($sortorder=='ordd')
		$sSQL.=' ORDER BY ordDate DESC';
	elseif($sortorder=='oraa')
		$sSQL.=' ORDER BY ordAuthNumber';
	elseif($sortorder=='orad')
		$sSQL.=' ORDER BY ordAuthNumber DESC';
	elseif($sortorder=='orpa')
		$sSQL.=' ORDER BY ordPayProvider';
	elseif($sortorder=='orpd')
		$sSQL.=' ORDER BY ordPayProvider DESC';
	elseif($sortorder=='orsa' || $sortorder=='orsd'){
		if($editablefield=='tracknum')
			$sSQL.=' ORDER BY ordTrackNum';
		elseif($editablefield=='tracknum')
			$sSQL.=' ORDER BY ordInvoice';
		elseif($editablefield=='email')
			$sSQL.=' ORDER BY ordEmail';
		else
			$sSQL.=' ORDER BY ordStatus';
		if($sortorder=='orsd') $sSQL.=' DESC';
	}else
		$sSQL.=' ORDER BY ordID';
	$alldata=ect_query('SELECT COUNT(*) AS bar FROM orders'.($dropshipper!=''?" INNER JOIN cart ON orders.ordID=cart.cartOrderID INNER JOIN products ON cart.cartProdID=products.pID":(@$_REQUEST['orddiscount']!=''?' INNER JOIN couponsapplied ON orders.ordID=couponsapplied.cpaOrdID':'')).$whereSQL) or ect_error();
	$rs=ect_fetch_assoc($alldata);
	$iNumOfPages=ceil($rs['bar']/$maxordersperpage);
	ect_free_result($alldata);
	$alldata=ect_query($sSQL.' LIMIT ' . ($maxordersperpage*($CurPage-1)).','.$maxordersperpage) or ect_error();
	$hasdeleted=FALSE;
	$sSQL='SELECT COUNT(*) AS NumDeleted FROM orders WHERE ordStatus=1';
	$result=ect_query($sSQL) or ect_error();
	$rs=ect_fetch_assoc($result);
	if($rs["NumDeleted"] > 0) $hasdeleted=TRUE;
	ect_free_result($result);
?>
<script src="popcalendar.js"></script>
<script>
/* <![CDATA[ */
try{languagetext('<?php print @$adminlang?>');}catch(err){}
function delrec(id){
if(confirm("<?php print jscheck($yyConDel)?>\n")){
	document.psearchform.id.value=id;
	document.psearchform.act.value="delete";
	document.psearchform.submit();
}
}
function authrec(id, currauth){
var aucode;
if(currauth=='')currauth='<?php print $yyManAut?>';
if((aucode=prompt("<?php print jscheck($yyEntAuth)?>",currauth))!=null){
	document.psearchform.id.value=id;
	document.psearchform.act.value="authorize";
	document.psearchform.authcode.value=aucode;
	document.psearchform.submit();
}
return false;
}
function unpendrec(id){
if(confirm("<?php print $yyWarni?>\n\nThis will not make any changes at your payment processor!\n\nRemove pending status of this order?")){
	document.psearchform.id.value=id;
	document.psearchform.act.value="unpending";
	document.psearchform.submit();
}
}
function unmodwarn(id){
<?php	if($GLOBALS['useStockManagement']){
			$yyModWar.='Please click "OK" to edit the order and check stock levels as stock has not yet been subtracted for this order.'; ?>
if(confirm("<?php print jscheck($yyWarni)?>\n\n<?php print jscheck($yyModWar)?>")){
	document.location='adminorders.php?doedit=true&id='+id;
}
<?php	}else{
			$yyModWar.='Please click "OK" to clear the warning status and authorize this order.'; ?>
if(confirm("<?php print jscheck($yyWarni)?>\n\n<?php print jscheck($yyModWar)?>")){
	document.psearchform.id.value=id;
	document.psearchform.act.value="unpending";
	document.psearchform.submit();
}
<?php	} ?>
}
var ctrlset=false;
function setmodstate(evt){
	if(!evt)evt=window.event;
	if(evt.detail&&evt.detail>0) ctrlset=evt.ctrlKey;
}
function checkcontrol(tt,evt){
	tt.name=tt.id;
	if(ctrlset){
		maxitems=document.psearchform.maxitems.value;
		for(index=0;index<maxitems;index++){
			var statusobj=document.getElementById('ordStatus'+index);
			isdisabled=statusobj.disabled;
			if(! isdisabled){
				if(statusobj.length>tt.selectedIndex){
					statusobj.name=statusobj.id;
					statusobj.selectedIndex=tt.selectedIndex;
					statusobj.options[tt.selectedIndex].selected=true;
				}
			}
		}
	}
}
function checkprinter(tt,evt){
var thref=tt.href;
<?php if(strstr(@$_SERVER['HTTP_USER_AGENT'], 'Gecko')){ ?>
if(evt.ctrlKey || evt.altKey || document.psearchform.ctrlmod[document.psearchform.ctrlmod.selectedIndex].value=="1")thref+="&printer=true";
<?php }else{ ?>
theevnt=window.event;
if(theevnt.ctrlKey || document.psearchform.ctrlmod[document.psearchform.ctrlmod.selectedIndex].value=="1")thref+="&printer=true";
<?php } ?>
if(document.psearchform.ctrlmod[document.psearchform.ctrlmod.selectedIndex].value=="3")thref+="&invoice=true";
if(document.psearchform.ctrlmod[document.psearchform.ctrlmod.selectedIndex].value=="2")thref+="&doedit=true";
if(document.psearchform.ctrlmod[document.psearchform.ctrlmod.selectedIndex].value=="4")thref+="&doedit=true&clone=true";
document.forms.psearchform.action=thref;
document.forms.psearchform.submit();
return(false);
}
function setdumpformat(fdump){
formatindex=fdump[fdump.selectedIndex].value;
if(formatindex==1)
	document.psearchform.act.value='dumporders';
else if(formatindex==2)
	document.psearchform.act.value='dumpdetails';
else if(formatindex==3)
	document.psearchform.act.value='quickbooks';
else if(formatindex==4)
	document.psearchform.act.value='ouresolutionsxmldump';
else if(formatindex==5){
	dodazzle();
	fdump.selectedIndex=0;
	return;
}
document.psearchform.action='dumporders.php';
document.psearchform.submit();
fdump.selectedIndex=0;
}
function docheckall(){
	allcbs=document.getElementsByName('ids[]');
	mainidchecked=document.getElementById('xdocheckall').checked;
	for(i=0;i<allcbs.length;i++){
		allcbs[i].checked=mainidchecked;
	}
	return(true);
}
function checkchecked(printorinvoice){
	allcbs=document.getElementsByName('ids[]');
	var onechecked=false;
	for(i=0;i<allcbs.length;i++){
		if(allcbs[i].checked)onechecked=true;
	}
	if(onechecked){
		document.forms.psearchform.action='adminorders.php?'+printorinvoice+'=true&id=multi';
		document.forms.psearchform.submit();
	}else{
		alert("<?php print jscheck($yyNoSelO)?>");
	}
}
function changeselectfield(whichfield){
	var editablefield=document.getElementById(whichfield);
	var editfieldval=editablefield[editablefield.selectedIndex].value;
		if(editfieldval=='orsa'||editfieldval=='orsd'){
		changesortorder(editfieldval)
	}else{
		document.psearchform.reset();
		document.psearchform.action='adminorders.php';
		document.psearchform.id.value=editfieldval;
		document.psearchform.act.value=whichfield;
		document.psearchform.submit();
	}
}
function setCookie(c_name,value,expiredays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
function changesortorder(ord){
	setCookie('ordersort',ord,600);
	document.forms.psearchform.submit();
}
var dazzleorightml='<br><br><span style="background:#FFFFFF;padding:5px"> Please copy your Dazzle / WorldShip file contents below </span><br><br><div style="text-align:center"><textarea id="dazzletextarea" rows="18" cols="120" style="white-space:nowrap;overflow:scroll;" wrap="off"></textarea></div><div style="text-align:center"><input type="button" value="Submit" onclick="processdazzle()"> <input type="button" value="Cancel" onclick="document.getElementById(\'dazzlediv\').style.display=\'none\'"></div>';
function dodazzle(){
	document.getElementById('dazzleinner').innerHTML=dazzleorightml;
	document.getElementById('dazzlediv').style.display='';
}
function dazupdajaxcallback(){
	if(ajaxobj.readyState==4){
		var restxt=ajaxobj.responseText;
		if(restxt.search('SUCCESS')!=-1){
			var rowid=restxt.split('|')[1];
			document.getElementById('dazdet'+rowid).style.visibility='hidden';
			document.getElementById('dazdet'+rowid).style.display='none';
			document.getElementById('dazrow'+rowid).style.visibility='hidden';
			document.getElementById('dazrow'+rowid).style.display='none';
			document.getElementById('dazhr'+rowid).style.visibility='hidden';
			document.getElementById('dazhr'+rowid).style.display='none';
		}else
			alert('Error updating');
		if(dazisprocall)dazprocall();
	}
}
function dazzleupd(tordid,ttrnum,rowid,hasduplicate){
	var statussel=document.getElementById('dazordstatus');
	ajaxobj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
	ajaxobj.onreadystatechange=dazupdajaxcallback;
	ajaxobj.open("GET", "ajaxservice.php?action=dazzleupd&rowid="+rowid+"&ordid="+tordid+"&trackno="+encodeURIComponent(ttrnum)+"&emstatus="+(document.getElementById('dazemstatus').checked==true?'1':'0')+"&ordstatus="+statussel[statussel.selectedIndex].value+(hasduplicate?"&noemail=true":''), true);
	ajaxobj.send(null);
}
function dazprocall(){
	dazisprocall=true;
	if(dazall.length>0){
		var tind=dazall.pop();
		if(document.getElementById('dazid'+tind)){
			var hasduplicate=false;
			var tordid=document.getElementById('dazid'+tind).value;
			for(var idind=0;idind<dazall.length;idind++){
				if(document.getElementById('dazid'+dazall[idind])){
					var mordid=document.getElementById('dazid'+dazall[idind]).value;
					if(mordid==tordid) hasduplicate=true;
				}
			}
			dazzleupd(tordid,document.getElementById('daztr'+tind).innerHTML,tind,hasduplicate);
		}else dazprocall();
	}
}
var dazisprocall=false;
var statarr=[];
var dazall=[];
function dazajaxcallback(){
	var allstatus='<select id="dazordstatus" size="1" onchange="setCookie(\'dazordstatus\',this[this.selectedIndex].value,600);"><option value="">No Change</option><?php
			$statarr='';
			for($index=0; $index < $numstatus; $index++){
				if(is_numeric(getget('dazordstatus'))) $wantstatus=(int)getget('dazordstatus'); else $wantstatus=0;
				if($allstatus[$index]['statID']>=3) print '<option value="' . $allstatus[$index]['statID'] . '"' . ($allstatus[$index]['statID']==$wantstatus?' selected':'') . '>' . jsescape($allstatus[$index]['statPrivate']) . '</option>';
				$statarr.='statarr['.$allstatus[$index]['statID'].']="'.$allstatus[$index]['statPrivate'].'";';
			} ?></select>';
	<?php print $statarr?>
	if(ajaxobj.readyState==4){
		var restxt=ajaxobj.responseText;
		if(restxt=='ERRORFILEFORMAT'){
			alert('Error in file format. Only Dazzle And WorldShip CSV file formats are supported.');
		}else{
			document.getElementById('dazzleinner').innerHTML='<br>&nbsp;<br><table style="margin:0 auto;" class="cobtbl" cellspacing="1" cellpadding="3" id="dazzletable"><tr><td class="cobhl" colspan="2">Change Status To:'+allstatus+' | Email Status Change: <input type="checkbox" id="dazemstatus" value="ON" onchange="setCookie(\'dazemstatus\',this.checked?1:0,600);" <?php if(@$_COOKIES['dazemstatus']=='1') print 'checked="checked" '?>/></td><td class="cobhl"><input type="button" value="Process All" onclick="dazprocall()"></td></tr></table><br><input type="button" value="Close Window" onclick="document.getElementById(\'dazzlediv\').style.display=\'none\'">';
			var thetable=document.getElementById('dazzletable');
			var tarr=restxt.split('==DAZZLELINE==');
			for(var tind=1;tind<tarr.length;tind++){
				var newrow=thetable.insertRow(-1);
				newrow.id="dazdet"+tind;
				newrow.className='cobhl';
				var tlin=tarr[tind].split('==MATCHLINE==');
				var origdets=tlin[0].split('==ORIGADD==');
				newcell=newrow.insertCell(0);
				newcell.innerHTML=origdets[1];

				newcell=newrow.insertCell(1);
				newcell.innerHTML='<div id="daztr'+tind+'">'+origdets[0]+'</div>';

				newcell=newrow.insertCell(2);
				if(tlin.length<2){
					newcell.innerHTML='No Match';
				}else{
					dazall.push(tind);
					newcell.innerHTML=' - ';
					var newrow=thetable.insertRow(-1);
					newrow.id="dazrow"+tind;
					var ordstatus=0;
					var ordid=0;
					newrow.className='cobll';
					newcell=newrow.insertCell(0);
					newcell.className='cobll';
					var seltxt=tlin.length>2?'<select id="dazsel'+tind+'" size="1" onchange="document.getElementById(\'dazid'+tind+'\').value=this[this.selectedIndex].value.split(\'|\')[0];document.getElementById(\'dazstat'+tind+'\').innerHTML=statarr[this[this.selectedIndex].value.split(\'|\')[1]]">':'';
					for(var tind2=1;tind2<tlin.length;tind2++){
						linspl=tlin[tind2].split('==FULLADD==');
						ordid=linspl[0].split('|')[0];
						seltxt+=(tlin.length>2?'<option value="'+linspl[0]+'">':'')+ordid+' - '+linspl[1]+(tlin.length>2?'</option>':'');
					}
					ordstatus=tlin[1].split('==FULLADD==')[0].split('|')[1];
					newcell.innerHTML=seltxt+(tlin.length>2?'</select>':'')+'<input type="hidden" id="dazid'+tind+'" value="'+tlin[1].split('==FULLADD==')[0].split('|')[0]+'">';

					newcell=newrow.insertCell(1);
					newcell.className='cobll';
					newcell.id='dazstat'+tind;
					newcell.innerHTML=statarr[ordstatus];

					newcell=newrow.insertCell(2);
					newcell.className='cobll';
					newcell.innerHTML='<input type="button" value="Update" onclick="dazisprocall=false;dazzleupd(document.getElementById(\'dazid'+tind+'\').value,\''+origdets[0]+'\','+tind+',false)">';
				}
				var newrow=thetable.insertRow(-1);
				newrow.id="dazhr"+tind;
				newrow.className='cobll';
				newcell=newrow.insertCell(0);
				newcell.colSpan=3;
				newcell.innerHTML='<hr width="80%">';
			}
		}
	}
}
function processdazzle(){
	var dazzletext=encodeURIComponent(document.getElementById('dazzletextarea').value);
	if(dazzletext==''){
		alert("No input specified.");
	}else{
		ajaxobj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
		ajaxobj.onreadystatechange=dazajaxcallback;
		ajaxobj.open("POST", "ajaxservice.php?action=dazzle", true);
		ajaxobj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		ajaxobj.send('dazzletext='+dazzletext);
	}
}
function shiptheorycallback(){
	if(ajaxobj.readyState==4){
		var restxt=ajaxobj.responseText;
		document.getElementById('preloaderdiv').style.display='none';
		if(restxt.substr(0,6)=='ERROR:'){
			alert(restxt.substr(6));
		}else{
			alert(restxt);
			document.psearchform.action='adminorders.php';
			document.psearchform.act.value='';
			document.psearchform.submit();
		}
	}
}
function doshiptheory(){
	var checkedids='',addcomma='';
	allcbs=document.getElementsByName('ids[]');
	for(i=0;i<allcbs.length;i++){
		if(allcbs[i].checked){
			checkedids+=addcomma+allcbs[i].value;
			addcomma=',';
		}
	}
	if(checkedids.length<1){
		alert('Please select the orders you wish to ship.');
	}else if(confirm('Ship these products with ShipTheory?')){
		document.getElementById('preloaderdiv').style.display='';
		ajaxobj=window.XMLHttpRequest?new XMLHttpRequest():new ActiveXObject("MSXML2.XMLHTTP");
		ajaxobj.onreadystatechange=shiptheorycallback;
		ajaxobj.open("POST", "ajaxservice.php?action=shiptheory", true);
		ajaxobj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		ajaxobj.send('shipids='+checkedids);
	}
}
function selectedordersact(tsel){
	var tact=tsel[tsel.selectedIndex].value;
	if(tact=="1")
		checkchecked('printer');
	else if(tact=="2")
		checkchecked('invoice');
	else if(tact=="3")
		dodazzle();
	else if(tact=="6")
		doshiptheory();
	tsel.selectedIndex=0;
}
function viewproduct(id){
    var form = document.createElement("form");
    var element1 = document.createElement("input");
    var element2 = document.createElement("input");
	var element3 = document.createElement("input");

    form.method = "POST";
    form.action = "adminprods.php";
	form.target = "_ect";

    element1.value=id;
    element1.name="id";
    form.appendChild(element1);  

    element2.value='1';
    element2.name="posted";
    form.appendChild(element2);
	
	element3.value='modify';
    element3.name="act";
    form.appendChild(element3);

    document.body.appendChild(form);
    form.submit();
	document.body.removeChild(form);
}
function dopurgeorders(){
	if(confirm('Delete orders permanently?')){
		document.psearchform.action='adminorders.php';
		document.psearchform.act.value='purge';
		return true;
	}else
		return false;
}
function focuslineitem(obj,id){
obj.style.width='230px';
document.getElementById('anchorvis'+id).style.display='none';
document.getElementById('anchorhid'+id).style.display='';
}
function blurlineitem(obj,id){
obj.style.width='50px';
document.getElementById('anchorhid'+id).style.display='none';
document.getElementById('anchorvis'+id).style.display='';
}
function invoicepatterndown(tval){
	var res=tval.match(/(.*?)(\d+)(\D*)$/);
	if(res)
		return res[1]+(parseInt(res[2])+1)+res[3];
	else
		return tval;
}
function invoicekeypress(tobj){
	var event = window.event ? window.event : e;
	const focusableElements = document.querySelectorAll('[tabindex]');
	var thistabind=parseInt(tobj.getAttribute('tabindex'));
	if(event.keyCode==38&&thistabind>1){
		if(focusableElements[thistabind-2]) focusableElements[thistabind-2].focus();
	}else if(event.keyCode==40){
		if(focusableElements[thistabind]){
			focusableElements[thistabind].focus();
			if(event.ctrlKey&&event.shiftKey){
				focusableElements[thistabind].value=invoicepatterndown(tobj.value);
			}
		}
	}
}
/* ]]> */
</script>
<div id="dazzlediv" style="display:none;position:absolute;width:100%;height:2000px;background-image:url(adminimages/opaquepixel.png);top:0px;left:0px;text-align:center;z-index:10000;"><br><br><br><br><br><br><div id="dazzleinner" style="margin:0 auto;background:#FFFFFF;width:800px;height:600px"></div></div>
<?php	if(! $success) print '<div style="text-align:center;color:#FF0000">' . $errmsg . '</div>';
		if(getpost('act')=='editablefield') $editablefield=getpost('id'); else $editablefield=@$_COOKIE['editablefield'];
		if($dropshipper!='' && $editablefield=='abandoned') $editablefield='';
		if(getpost('act')=='searchfield')
			$searchfield=getpost('id');
		elseif(getpost('thesearchfield')!=''){
			$searchfield=getpost('thesearchfield');
			setacookie('searchfield',$searchfield,0);
		}else
			$searchfield=@$_COOKIE['searchfield'];
		if(getpost('ordersearchfield')!='') $ordersearchfield=getpost('ordersearchfield'); else $ordersearchfield=@$_COOKIE['ordersearchfield'];
		$_SESSION['fromdate']=$fromdate;
		$_SESSION['todate']=$todate;
		$_SESSION['notstatus']=@$_REQUEST['notstatus'];
		$_SESSION['notsearchfield']=@$_REQUEST['notsearchfield'];
		$_SESSION['searchtext']=$origsearchtext;
		$_SESSION['ordStatus']=@$_REQUEST['ordStatus'];
		$_SESSION['ordstate']=@$_REQUEST['ordstate'];
		$_SESSION['ordcountry']=@$_REQUEST['ordcountry'];
		$_SESSION['orddiscount']=@$_REQUEST['orddiscount'];
		$_SESSION['payprovider']=@$_REQUEST['payprovider']; ?>
<h2><?php print $yyAdmOrd?></h2>
<form method="post" action="adminorders.php<?php if($CurPage!=1) print '?pg='.$CurPage?>" name="psearchform">
            <input type="hidden" name="act" value="">
			<input type="hidden" name="id" value="">
			<input type="hidden" name="authcode" value="">
            <input type="hidden" name="theeditablefield" value="<?php print $editablefield?>">
            <div class="orderssearch">
			  <div class="orderssearchrow">
				<div style="text-align:right"><input type="button" onclick="popUpCalendar(this, document.forms.psearchform.fromdate, '<?php print $themask?>', 0)" value="<?php print $yyOrdFro?>"></div>
				<div><div style="position:relative;display:inline"><input type="text" class="orddatesel" size="14" name="fromdate" value="<?php print $fromdate?>" style="vertical-align:middle"> <input type="button" onclick="document.forms.psearchform.fromdate.value='<?php print date($admindatestr, time() + ($GLOBALS['dateadjust']*60*60))?>'" value="<?php print $yyToday?>"></div></div>
				<div style="text-align:right"><input type="button" onclick="popUpCalendar(this, document.forms.psearchform.todate, '<?php print $themask?>', -205)" value="<?php print $yyOrdTil?>"></div>
				<div><div style="position:relative;display:inline"><input type="text" class="orddatesel" size="14" name="todate" value="<?php print $todate?>" style="vertical-align:middle"> <input type="button" onclick="document.forms.psearchform.todate.value='<?php print date($admindatestr, time() + ($GLOBALS['dateadjust']*60*60))?>'" value="<?php print $yyToday?>"></div></div>
			  </div>
			  <div class="orderssearchrow">
				<div style="text-align:center"><input type="checkbox" name="notstatus" title="<?php print $yyNot?>" value="ON" style="vertical-align:middle" <?php if(getrequest('notstatus')=='ON') print 'checked '?>/> <?php print $yyOrdSta?></div>
				<div style="text-align:center"><input type="checkbox" name="notsearchfield" title="<?php print $yyNot?>" value="ON" style="vertical-align:middle" <?php if(getrequest('notsearchfield')=='ON') print "checked "?>/>
					<select name="searchfield" id="searchfield" size="1" onchange="changeselectfield('searchfield')">
					<option value="state"<?php if($searchfield=='state') print ' selected'?>><?php print $yyState?></option>
					<option value="country"<?php if($searchfield=='country') print ' selected'?>><?php print $yyCountry?></option>
					<option value="payprovider"<?php if($searchfield=='payprovider' || $searchfield=='') print ' selected'?>><?php print $yyPayMet?></option>
					<option value="discount"<?php if($searchfield=='discount' || $searchfield=='') print ' selected'?>><?php print $yyDisco?></option>
					</select></div>
				<div style="text-align:right"><select name="ordersearchfield" size="1">
					<option value="ordid"<?php if($ordersearchfield=='ordid') print ' selected'?>><?php print $yySearch.' '.$xxOrdId?></option>
					<option value="email"<?php if($ordersearchfield=='email') print ' selected'?>><?php print $yySearch.' '.$yyEmail?></option>
					<option value="authcode"<?php if($ordersearchfield=='authcode') print ' selected'?>><?php print $yySearch.' '.$yyAutCod?></option>
					<option value="name"<?php if($ordersearchfield=='name') print ' selected'?>><?php print $yySearch.' '.$yyName?></option>
					<option value="product"<?php if($ordersearchfield=='product') print ' selected'?>><?php print $yySearch.' '.$yyPrName?>/ID</option>
					<option value="address"<?php if($ordersearchfield=='address') print ' selected'?>><?php print $yySearch.' '.$yyAddress?></option>
					<option value="zip"<?php if($ordersearchfield=='zip') print ' selected'?>><?php print $yySearch.' '.$yyZip?></option>
					<option value="phone"<?php if($ordersearchfield=='phone') print ' selected'?>><?php print $yySearch.' '.$yyTelep?></option>
					<option value="invoice"<?php if($ordersearchfield=='invoice') print ' selected'?>><?php print $yySearch.' '.$yyInvNum?></option>
					<option value="tracknum"<?php if($ordersearchfield=='tracknum') print ' selected'?>><?php print $yySearch.' '.$yyTraNum?></option>
					<option value="affiliate"<?php if($ordersearchfield=='affiliate') print ' selected'?>><?php print $yySearch.' '.$yyAffili?></option>
<?php				if(@$extraorderfield1!='') print '<option value="extra1"' . ($ordersearchfield=='extra1' ? ' selected' : '') . '>' . htmlspecials(substr(strip_tags($extraorderfield1), 0, 16)) . '</option>';
					if(@$extraorderfield2!='') print '<option value="extra2"' . ($ordersearchfield=='extra2' ? ' selected' : '') . '>' . htmlspecials(substr(strip_tags($extraorderfield2), 0, 16)) . '</option>';
					if(@$extracheckoutfield1!='') print '<option value="checkout1"' . ($ordersearchfield=='checkout1' ? ' selected' : '') . '>' . htmlspecials(substr(strip_tags($extracheckoutfield1), 0, 16)) . '</option>';
					if(@$extracheckoutfield2!='') print '<option value="checkout2"' . ($ordersearchfield=='checkout2' ? ' selected' : '') . '>' . htmlspecials(substr(strip_tags($extracheckoutfield2), 0, 16)) . '</option>';
?>					</select></div>
				<div><input class="ordsearchtext" type="text" size="24" name="searchtext" value="<?php print $origsearchtext?>"> 
					<button type="button" onclick="this.form.searchtext.value=''" style="padding-bottom:6px;padding-top:4px;vertical-align:bottom"><i style="font-size:12px" class="fa">&#xf014;</i></button> 
					<button type="button" onclick="this.form.fromdate.value=this.form.todate.value=this.form.searchtext.value=''"><i style="font-size:14px" class="fa">&#xf014;</i></button></div>
			  </div>
			  <div class="orderssearchrow">
				<div style="text-align:center;vertical-align:middle">
<?php
	if($editablefield=="abandoned"){ ?>
		<select name="abandonedstatus" size="1">
		<option value="">All Abandoned Carts</option>
		<option value="1"<?php if(getpost('abandonedstatus')=='1') print ' selected'?>>Abandoned Carts - No Emails Sent</option>
		<option value="2"<?php if(getpost('abandonedstatus')=='2') print ' selected'?>>Abandoned Carts - One Email Sent</option>
		<option value="3"<?php if(getpost('abandonedstatus')=='3') print ' selected'?>>Abandoned Carts - Two Emails Sent</option>
		<option value="4"<?php if(getpost('abandonedstatus')=='4') print ' selected'?>>Abandoned Carts - Three Emails Sent</option>
		<option value="recovered"<?php if(getpost('abandonedstatus')=='recovered') print ' selected'?>>Recovered Carts</option>
		</select>
<?php
	}else{ ?>
		<select name="ordStatus[]" size="5" multiple="multiple" class="ordstatus"><?php
		$ordstatus=$addcomma='';
		if(is_array(@$_REQUEST['ordStatus'])){
			foreach($_REQUEST['ordStatus'] as $objValue){
				if(is_array($objValue))$objValue=$objValue[0];
				$ordstatus.=$addcomma . $objValue;
				$addcomma=',';
			}
		}else
			$ordstatus=getrequest('ordStatus');
		$ordstatusarr=explode(',',$ordstatus);
		for($index=0; $index < $numstatus; $index++){
			print '<option value="' . $allstatus[$index]['statID'] . '"';
			if(is_array($ordstatusarr)){
				foreach($ordstatusarr as $objValue)
					if($objValue==$allstatus[$index]['statID']) print ' selected';
			}
			print '>' . $allstatus[$index]['statPrivate'] . '</option>';
		} ?></select>
<?php
	} ?>
				</div>
				<div style="text-align:center;vertical-align:middle">
<?php
	if(@$searchfield=='discount'){ ?>
		<select name="orddiscount[]" size="5" multiple="multiple"><?php
		$orddiscount=@$_REQUEST['orddiscount'];
		$sSQL="SELECT cpnID,cpnWorkingName FROM coupons ORDER BY cpnWorkingName";
		$result=ect_query($sSQL) or ect_error();
		while($rs=ect_fetch_assoc($result)){
			print '<option value="' . $rs['cpnID'] . '"';
			if(is_array($orddiscount)){
				foreach($orddiscount as $objValue){
					if($objValue==$rs['cpnID']) print ' selected';
				}
			}
			print '>' . $rs['cpnWorkingName'] . '</option>';
		}
		ect_free_result($result); ?></select><?php
	}elseif(@$searchfield=='state'){ ?>
		<select name="ordstate[]" size="5" multiple="multiple"><?php
		$ordstate=@$_REQUEST['ordstate'];
		$sSQL='SELECT stateID,stateName,stateAbbrev FROM states WHERE stateCountryID=' . $origCountryID . ' AND stateEnabled=1 ORDER BY stateName';
		$result=ect_query($sSQL) or ect_error();
		while($rs=ect_fetch_assoc($result)){
			print '<option value="' . htmlspecials(@$usestateabbrev==TRUE?$rs['stateAbbrev']:$rs['stateName']) . '"';
			if(is_array($ordstate)){
				foreach($ordstate as $objValue){
					if($objValue==(@$usestateabbrev==TRUE?$rs['stateAbbrev']:$rs['stateName'])) print ' selected';
				}
			}
			print '>' . $rs['stateName'] . "</option>\n";
		}
		ect_free_result($result); ?></select><?php
	}elseif(@$searchfield=='country'){ ?>
		<select name="ordcountry[]" size="5" multiple="multiple"><?php
		$ordcountry=@$_REQUEST['ordcountry'];
		$sSQL="SELECT countryID,countryName FROM countries WHERE countryEnabled=1 ORDER BY countryOrder DESC, countryName";
		$result=ect_query($sSQL) or ect_error();
		while($rs=ect_fetch_assoc($result)){
			print '<option value="' . htmlspecials($rs['countryName']) . '"';
			if(is_array($ordcountry)){
				foreach($ordcountry as $objValue){
					if($objValue==$rs['countryName']) print ' selected';
				}
			}
			print '>' . $rs['countryName'] . "</option>\n";
		}
		ect_free_result($result); ?></select><?php
	}else{ ?>
		<select name="payprovider[]" size="5" multiple="multiple"><?php
		$payprovider=@$_REQUEST['payprovider'];
		$sSQL="SELECT payProvID,payProvName FROM payprovider WHERE payProvEnabled=1 ORDER BY payProvOrder";
		$result=ect_query($sSQL) or ect_error();
		while($rs=ect_fetch_assoc($result)){
			print '<option value="' . $rs['payProvID'] . '"';
			if(is_array($payprovider)){
				foreach($payprovider as $objValue){
					if($objValue==$rs['payProvID']) print ' selected';
				}
			}
			print '>' . $rs['payProvName'] . '</option>';
		}
		ect_free_result($result); ?></select>
<?php
	} ?>
				</div>
				<div style="text-align:center;vertical-align:middle">
					<select size="1" style="vertical-align:middle;max-width:164px" onchange="setdumpformat(this)">
					<option value=""><?php print $yySelect?></option>
					<option value="1"><?php print $yyDmpOrd?></option>
					<option value="2"><?php print $yyDmpDet?></option>
<?php	if(@$ouresolutionsxml!='') print '<option value="4">OurESolutions XML format</option>'; ?>
					<option value="5">WorldShip</option>
<?php	if($origCountryID==1) print '<option value="5">Dazzle</option>' ?>
					</select>
				</div>
				<div style="text-align:center;vertical-align:middle">
					<input style="margin:2px" type="submit" value="<?php print $yySearch?>" onclick="document.forms.psearchform.action='adminorders.php';">
<?php	if($hasdeleted){ ?><input style="margin:2px" type="submit" value="<?php print $yyPurDel?>" onclick="return dopurgeorders()"><?php } ?>
					<input style="margin:2px" type="button" value="<?php print $yyNewOrd?>" onclick="document.forms.psearchform.action='adminorders.php?id=new';document.forms.psearchform.submit();">
				</div>
			  </div>
			</div>

			<div class="orderslist<?php if($editablefield=='abandoned') print ' greenheader'?>">
			  <div class="ordersheadrow">
				<div class="acenter" style="width:3%"><input type="checkbox" id="xdocheckall" value="1" onclick="docheckall()"></div>
                <div class="acenter"><a href="javascript:changesortorder('<?php print ($sortorder=='oida'?'oidd':'oida')?>')"><?php print $yyOrdId?></a></div>
				<div class="aleft"><a href="javascript:changesortorder('<?php print ($sortorder=='orna'?'ornd':'orna')?>')"><?php print $yyName?></a></div>
				<div class="acenter"><a href="javascript:changesortorder('<?php print ($sortorder=='orpa'?'orpd':'orpa')?>')"><?php print $yyMethod?></a></div>
				<div class="acenter" style="width:3%"><?php if($editablefield=='abandoned') print 'Emails Sent'; else print 'AVS'?></div>
				<div class="acenter" style="width:3%"><?php if($editablefield!='abandoned') print 'CVV'?></div>
				<div class="acenter"><a href="javascript:changesortorder('<?php print ($sortorder=='oraa'?'orad':'oraa')?>')"><?php if($editablefield=='abandoned') print 'Amount'; else print $yyAutCod?></a></div>
				<div class="acenter"><a href="javascript:changesortorder('<?php print ($sortorder=='orda'?'ordd':'orda')?>')"><?php print $yyDate?></a></div>
				<div class="acenter">
					<select class="ordstatus" name="editablefield" id="editablefield" size="1" onchange="changeselectfield('editablefield')">
					<option value="status"><?php print $yyStatus?></option>
					<option value="shippedstatus"<?php if($editablefield=='shippedstatus') print ' selected'?>><?php print 'Shipped Status'?></option>
					<option value="tracknum"<?php if($editablefield=='tracknum') print ' selected'?>><?php print $yyTraNum?></option>
					<option value="invoice"<?php if($editablefield=='invoice') print ' selected'?>><?php print $yyInvNum?></option>
					<option value="email"<?php if($editablefield=='email') print ' selected'?>><?php print $yyEmail?></option>
<?php	if($dropshipper==''){ ?>
					<option value="abandoned"<?php if($editablefield=='abandoned') print ' selected'?>>Abandoned Carts</option>
<?php	} ?>
					<option value="orderlines"<?php if($editablefield=='orderlines') print ' selected'?>>Order Lines</option>
					<option value="amount"<?php if($editablefield=='amount') print ' selected'?>><?php print $yyAmount?></option>
					<option value="transid"<?php if($editablefield=='transid') print ' selected'?>><?php print "Transaction ID"?></option>
					<option value="addinfo"<?php if($editablefield=='addinfo') print ' selected'?>><?php print "Additional Info"?></option>
					<option value="" disabled="disabled">---------------</option>
					<option value="<?php print ($sortorder=='orsa'?'orsd':'orsa')?>">Sort On Column<?php print ($sortorder=='orsa'?' DESC':'')?></option>
					</select>
				</div>
			  </div>
<?php
	if(ect_num_rows($alldata) > 0){
		$rowcounter=0;
		$ordTot=0;
		$lineitemnum=0;
		while($rs=ect_fetch_assoc($alldata)){
			$warningclass='';
			if(trim_($rs['ordAuthNumber'])=='') $warningclass=" ectred";
			$abandonedcartcount=0;
			if($editablefield=='abandoned'){
				$sSQL="SELECT COUNT(*) AS tcount FROM abandonedcartemail WHERE aceOrderID=" . $rs['ordID'];
				$result2=ect_query($sSQL) or ect_error();
				if($rs2=ect_fetch_assoc($result2)) $abandonedcartcount=$rs2['tcount'];
				ect_free_result($result2);
				if(getpost('abandonedstatus')=='1' && $abandonedcartcount!=0) $abandonedcartcount=-1;
				if(getpost('abandonedstatus')=='2' && $abandonedcartcount!=1) $abandonedcartcount=-1;
				if(getpost('abandonedstatus')=='3' && $abandonedcartcount!=2) $abandonedcartcount=-1;
				if(getpost('abandonedstatus')=='4' && $abandonedcartcount!=3) $abandonedcartcount=-1;
			}
			if($abandonedcartcount!=-1){
				if($rs['ordStatus']>=3||$editablefield=='abandoned') $ordTot+=$rs['ordTot'];
				if(@$bgcolor=='cobll') $bgcolor='cobhl'; else $bgcolor='cobll';
				if($rs['ordAuthStatus']=='MODWARNOPEN' || $rs['ordShipType']=='MODWARNOPEN') $bgcolor='cobwarn';
?>			  <div class="orderslistrow <?php print $bgcolor?>">
				<div class="acenter"><input type="checkbox" name="ids[]" value="<?php print $rs['ordID']?>"<?php if($editablefield=='abandoned' && ($abandonedcartcount>=3 || $rs['ordStatus']>2)) print ' disabled="disabled"'?>></div>
				<div class="acenter<?php print $warningclass?>"><a onclick="return(checkprinter(this,event));" href="adminorders.php?id=<?php print $rs['ordID']?>"><?php print $rs['ordID']?></a></div>
				<div class="<?php print trim_($warningclass)?>"><a onclick="return(checkprinter(this,event));" href="adminorders.php?id=<?php print $rs['ordID']?>"><?php print htmlspecialsucode(trim_($rs['ordName'].' '.$rs['ordLastName']))?></a></div>
				<div class="acenter<?php print $warningclass?>"><?php print htmlspecials($rs['payProvName']) . ($rs['payProvName']=='PayPal' && trim_($rs['ordTransID'])!='' ? ' CC' : '')?></div>
				<div class="acenter"><?php
				if($editablefield=='abandoned')
					print $abandonedcartcount;
				else{
					if($rs['ordPayProvider']==27){
						if($rs['ordAVS']=='E')
							print '&#9989;';
						elseif($rs['ordAVS']=='P')
							print '&#189;';
						elseif($rs['ordAVS']=='N')
							print '&#10060;';
						else
							print $rs['ordAVS'];
					}elseif($rs['ordPayProvider']==34){
						if($rs['ordAVS']=='1')
							print '&#9989;';
						else
							print '&#10060;';
					}else
						print (trim_($rs['ordAVS'])!=''?htmldisplay($rs['ordAVS']):'&nbsp;');
				} ?></div>
				<div class="acenter"><?php if($editablefield!='abandoned'){
					if($rs['ordPayProvider']==34){
						if($rs['ordCVV']=='1')
							print '&#9989;';
						else
							print '&#10060;';
					}else{
						if(trim_($rs['ordCVV'])!='')
							print htmldisplay($rs['ordCVV']);
						else
							print '&nbsp;';
					}
				} ?></div>
				<div class="acenter orderauthcode"><?php
				if($editablefield=='abandoned')
					print FormatEuroCurrency($rs['ordTot']);
				elseif($rs['ordAuthStatus']=='MODWARNOPEN' || $rs['ordShipType']=='MODWARNOPEN'){
					$isauthorized=FALSE;
					print '<input type="button" value="' . $yyMoWarn . '" onclick="unmodwarn(\'' . $rs['ordID'] . '\')"><br>';
				}else{
					if(trim_($rs['ordAuthStatus'])!='') print '<input type="button" value="' . $rs['ordAuthStatus'] . '" onclick="unpendrec(\'' . $rs['ordID'] . '\')"><br>';
					if(trim_($rs['ordAuthNumber'])==''){
						$isauthorized=FALSE;
						print '<input type="button" name="auth" value="' . $yyAuthor . ': ' . FormatEuroCurrency($rs['ordTot']) . '" onclick="authrec(\'' . $rs['ordID'] . '\',\'\')">';
					}elseif($rs['ordPayProvider']==1||$rs['ordPayProvider']==18||$rs['ordPayProvider']==19||$rs['ordPayProvider']==22||$rs['ordPayProvider']==27){
						print '<a href="https://www.' . ($rs['payProvDemo']==1?'sandbox.':'') . 'paypal.com/activity/payment/' . $rs['ordAuthNumber'] . '" title="' . FormatEuroCurrency($rs['ordTot']) . '" target="PayPal">' . $rs['ordAuthNumber'] . '</a>';
						$isauthorized=TRUE;
					}elseif($rs['ordPayProvider']==23){
						print '<a href="https://dashboard.stripe.com/payments/' . $rs['ordAuthNumber'] . '" title="' . FormatEuroCurrency($rs['ordTot']) . '" target="Stripe">' . $rs['ordAuthNumber'] . '</a>';
						$isauthorized=TRUE;
					}elseif($rs['ordPayProvider']==28){
						print '<a href="https://squareup.com/dashboard/sales/transactions/' . $rs['ordAuthNumber'] . '" title="' . FormatEuroCurrency($rs['ordTot']) . '" target="SquareUp">' . $rs['ordAuthNumber'] . '</a>';
						$isauthorized=TRUE;
					}else{
						print '<a href="#" title="' . FormatEuroCurrency($rs['ordTot']) . '" onclick="return(authrec(\'' . $rs['ordID'] . '\',\''.$rs['ordAuthNumber'].'\'))">' . $rs['ordAuthNumber'] . '</a>';
						$isauthorized=TRUE;
					}
				}
				?></div>
				<div class="acenter ordersdate<?php print $warningclass?>"><?php print date($admindatestr . "\<\\b\\r\>H:i:s", strtotime($rs["ordDate"]))?></div>
				<div class="<?php print ($editablefield=='amount'?'aright':'acenter')?>"><input type="hidden" name="ordid<?php print $rowcounter?>" value="<?php print $rs['ordID']?>">
<?php			$allshipped=TRUE;
				$alldropshipped=TRUE;
				$numlineitems=0;
				$alllineitems=[];
				if($editablefield=='orderlines'||$editablefield=='shippedstatus'){
					$sSQL="SELECT cartID,cartProdID,cartProdName,cartItemShipped,cartTrackNum,pDropship FROM cart LEFT JOIN products ON cart.cartProdID=products.pID WHERE cartOrderID=" . $rs['ordID'];
					$result2=ect_query($sSQL) or ect_error();
					while($rs2=ect_fetch_assoc($result2)){
						$alllineitems[$numlineitems++]=$rs2;
						if($rs2['cartItemShipped']==0) $allshipped=FALSE;
						if($dropshipper!='')
							if($rs2['cartItemShipped']==0 && $rs2['pDropship']==$dropshipper) $alldropshipped=FALSE;
					}
				}
				if($editablefield=='orderlines'){
					print '<div class="lineitems">';
					for($index=0;$index<$numlineitems;$index++){
						$cartID=$alllineitems[$index]['cartID'];
						$cartProdID=$alllineitems[$index]['cartProdID'];
						$cartProdName=substr($alllineitems[$index]['cartProdName'],0,50).(strlen($alllineitems[$index]['cartProdName'])>50?'...':'');
						$cartItemShipped=$alllineitems[$index]['cartItemShipped'];
						$cartTrackNum=$alllineitems[$index]['cartTrackNum'];
						$pDropship=(is_null($alllineitems[$index]['pDropship'])?0:$alllineitems[$index]['pDropship']);
						if($dropshipper=="" || $pDropship==$dropshipper){
							print '<div class="lineitem">';
								print '<a href="#" id="anchorvis' . $lineitemnum . '" onclick="viewproduct(\'' . jsspecials($cartProdID) . '\')">' . htmlspecials($cartProdName) . '</a>';
								print '<a href="#" id="anchorhid' . $lineitemnum . '" style="display:none">...</a>';
								print '<input type="hidden" name="lineitem' . $cartID . '" value="1">';
								print '<input type="text" name="linetrackno' . $cartID . '" style="width:50px" onfocus="focuslineitem(this,' . $lineitemnum . ')" onblur="blurlineitem(this,'.$lineitemnum.')" value="' . htmlspecials($cartTrackNum) . '" placeholder="' . placeholder("Tracking # - " . $cartProdName) . '" tabindex="' . ($lineitemnum*2+1) . '">';
								print '<input type="checkbox" name="isshipped' . $cartID . '"' . ($cartItemShipped!=0?" checked":'') . ' title="Shipped" value="1" tabindex="' . ($lineitemnum*2+2) . '">';
							print "</div>\n";
							$lineitemnum++;
						}
					}
					print '</div>';
				}elseif($editablefield=='tracknum')
					print '<input type="text" name="tracknum'.$rowcounter.'" size="24" value="' . $rs['ordTrackNum'] . '" tabindex="' . ($rowcounter+1) . '">';
				elseif($editablefield=='invoice')
					print '<input type="text" name="invoice'.$rowcounter.'" size="24" value="' . $rs['ordInvoice'] . '" tabindex="' . ($rowcounter+1) . '" onkeydown="invoicekeypress(this)">';
				elseif($editablefield=='email')
					print '<input type="text" name="email'.$rowcounter.'" size="34" value="' . $rs['ordEmail'] . '" tabindex="' . ($rowcounter+1) . '">';
				elseif($editablefield=='amount')
					print '<span style="margin-right:20%">' . FormatEuroCurrency($rs['ordTot']) . '</span>';
				elseif($editablefield=='transid')
					print $rs['ordTransID'];
				elseif($editablefield=='addinfo'){
					if(trim_($rs['ordAddInfo'])!='') print '<div class="addinfo">' . htmlspecials($rs['ordAddInfo']) . '</div>';
				}elseif($editablefield=='abandoned'){
					if($rs['ordStatus']>2)
						print '&nbsp;';
					elseif($abandonedcartcount<3)
						print '<input type="submit" value="Send Abandoned Email" onclick="document.psearchform.action=\'adminorders.php\';document.psearchform.act.value=\'oneabandoned\';document.psearchform.id.value=\''.$rs['ordID'].'\'">';
					else
						print 'All Sent';
				}else{ ?>
					<select class="ordstatus" id="ordStatus<?php print $rowcounter?>" size="1" onmousedown="setmodstate(event)" onchange="checkcontrol(this,event)" tabindex="<?php print ($rowcounter+1)?>"<?php print ($dropshipper!='' && !$allshipped?' disabled':'')?>><?php
					$gotitem=FALSE;
					for($index=0; $index<$numstatus; $index++){
						if(! $isauthorized && $allstatus[$index]['statID']>2) break;
						if(! ($rs['ordStatus']!=2 && $allstatus[$index]['statID']==2)){
							print '<option value="' . $allstatus[$index]['statID'] . '"';
							if($rs['ordStatus']==$allstatus[$index]['statID']){
								print ' selected';
								$gotitem=TRUE;
							}
							print '>' . $allstatus[$index]['statPrivate'] . '</option>';
						}
					}
					if(! $gotitem) print '<option value="'.$allstatus[$index]['statID'].'" selected="selected">' . $yyUndef . '</option>' ?></select>
<?php				if($editablefield=='shippedstatus') print ($allshipped?' &#9989;':' &#10060;');
				} ?>
				</div>
			  </div>
<?php			$rowcounter++;
			}
		} ?>
			  <div class="orderslistrow">
				<div style="vertical-align:top">
					<select class="ordactionsel" size="1" style="position:absolute;margin-top:8px" onchange="selectedordersact(this)">
					<option>Action Select</option>
					<option value="1"><?php print $yyPakSps?></option>
					<option value="2"><?php print $yyInvces?></option>
					<option value="3">WorldShip</option>
					<?php
						if($origCountryID==1) print '<option value="3">Dazzle</option>';
						if($hasshiptheory) print '<option value="6">ShipTheory</option>';
					?>
					</select>
				</div>
				<div>&nbsp;</div>
				<div style="vertical-align:top"><select name="ctrlmod" size="1" style="position:absolute;margin-top:8px"><option value="0"><?php print $yyVieDet?></option><option value="1"><?php print $yyPPSlip?></option><option value="3"><?php print $yyPPInv?></option><option value="2"<?php if(getpost('ctrlmod')=='2') print ' selected'?>><?php print $yyEdOrd?></option><option value="4"<?php if(getpost('ctrlmod')=='4') print ' selected'?>><?php print 'Clone Order'?></option></select></div>
				<div>&nbsp;</div>
				<div>&nbsp;</div>
				<div>&nbsp;</div>
				<div style="text-align:center"><?php print FormatEuroCurrency($ordTot)?></div>
				<div>&nbsp;</div>
				<div style="text-align:center"><input type="hidden" name="maxitems" value="<?php print $rowcounter?>"><?php
		if($editablefield!='abandoned' && $editablefield!='addinfo'){ ?>
					<input type="checkbox" name="emailstat" value="1" title="<?php print $yyEStat?>" style="vertical-align:middle" <?php if(getpost('emailstat')=="1" || @$alwaysemailstatus==TRUE) print 'checked="checked" ' ?>/>
<?php	}
		if($editablefield=='abandoned'){ ?>
				<input type="submit" value="Abandoned Emails to Selected" onclick="document.forms.psearchform.action='adminorders.php';document.psearchform.act.value='abandoned';">
<?php	}elseif($editablefield!='addinfo'){ ?>
				<input type="submit" value="<?php print $yyUpdate?>" onclick="document.forms.psearchform.action='adminorders.php<?php if($CurPage!=1) print '?pg='.$CurPage?>';document.psearchform.act.value='status';"> <input type="reset" value="<?php print $yyReset?>">
<?php	} ?>
				</div>
			  </div>
			</div>
<?php
	}else{ ?>
			</div>
			  <div style="padding:40px 0px;text-align:center"><?php print $yyNoMat1?></div>
<?php	if($hasdeleted){ ?>
			  <div style="padding:20px 0px;text-align:center"><input type="submit" value="<?php print $yyPurDel?>" onclick="document.psearchform.action='adminorders.php';document.psearchform.act.value='purge';"></div>
<?php	}
	}
	ect_free_result($alldata);
	if($iNumOfPages>1){
		$pblink='<a class="ectlink" href="adminorders.php?';
		foreach(@$_REQUEST as $objQS => $objValue)
			if($objQS!='pg'&&$objValue!=''&&($objQS=='searchtext'||$objQS=='ordersearchfield'||$objQS=='notstatus'||$objQS=='notsearchfield'||$objQS=='fromdate'||$objQS=='todate')) $pblink.=urlencode($objQS) . '=' . urlencode($objValue) . '&amp;';
		if(is_array(@$_REQUEST['ordStatus'])){
			foreach($_REQUEST['ordStatus'] AS $objQS => $objValue)
				$pblink.='ordStatus[]='.$objValue.'&amp;';
		}elseif(@$_REQUEST['ordStatus']!='')
			$pblink.='ordStatus[]='.$_REQUEST['ordStatus'];
		if(is_array(@$_REQUEST['payprovider']))
			foreach($_REQUEST['payprovider'] AS $objQS => $objValue)
				$pblink.='payprovider[]='.$objValue.'&amp;';
		if(is_array(@$_REQUEST['orddiscount']))
			foreach($_REQUEST['orddiscount'] AS $objQS => $objValue)
				$pblink.='orddiscount[]='.$objValue.'&amp;';
		if(is_array(@$_REQUEST['ordstate']))
			foreach($_REQUEST['ordstate'] AS $objQS => $objValue)
				$pblink.='ordstate[]='.$objValue.'&amp;';
		if(is_array(@$_REQUEST['ordcountry']))
			foreach($_REQUEST['ordcountry'] AS $objQS => $objValue)
				$pblink.='ordcountry[]='.$objValue.'&amp;';
		$pblink.='pg=';
		print '<div class="orderpagebar">' . writepagebar($CurPage,$iNumOfPages,$GLOBALS['yyPrev'],$GLOBALS['yyNext'],$pblink,FALSE) . '</div>';
	} ?>
			<div class="ordernavigation">
				<a href="adminorders.php?fromdate=<?php print date($admindatestr,mktime(0,0,0,date("m",$thefromdate)-1,date("d",$thefromdate),date("Y",$thefromdate)))?>&amp;todate=<?php print date($admindatestr,mktime(0,0,0,date("m",$thetodate)-1,date("d",$thetodate),date("Y",$thetodate)))?>">- <?php print $yyMonth?></a> | 
				<a href="adminorders.php?fromdate=<?php print date($admindatestr,mktime(0,0,0,date("m",$thefromdate),date("d",$thefromdate)-7,date("Y",$thefromdate)))?>&amp;todate=<?php print date($admindatestr,mktime(0,0,0,date("m",$thetodate),date("d",$thetodate)-7,date("Y",$thetodate)))?>">- <?php print $yyWeek?></a> | 
				<a href="adminorders.php?fromdate=<?php print date($admindatestr,mktime(0,0,0,date("m",$thefromdate),date("d",$thefromdate)-1,date("Y",$thefromdate)))?>&amp;todate=<?php print date($admindatestr,mktime(0,0,0,date("m",$thetodate),date("d",$thetodate)-1,date("Y",$thetodate)))?>">- <?php print $yyDay?></a> | 
				<a href="adminorders.php"><?php print $yyToday?></a> | 
				<a href="adminorders.php?fromdate=<?php print date($admindatestr,mktime(0,0,0,date("m",$thefromdate),date("d",$thefromdate)+1,date("Y",$thefromdate)))?>&amp;todate=<?php print date($admindatestr,mktime(0,0,0,date("m",$thetodate),date("d",$thetodate)+1,date("Y",$thetodate)))?>"><?php print $yyDay?> +</a> | 
				<a href="adminorders.php?fromdate=<?php print date($admindatestr,mktime(0,0,0,date("m",$thefromdate),date("d",$thefromdate)+7,date("Y",$thefromdate)))?>&amp;todate=<?php print date($admindatestr,mktime(0,0,0,date("m",$thetodate),date("d",$thetodate)+7,date("Y",$thetodate)))?>"><?php print $yyWeek?> +</a> | 
				<a href="adminorders.php?fromdate=<?php print date($admindatestr,mktime(0,0,0,date("m",$thefromdate)+1,date("d",$thefromdate),date("Y",$thefromdate)))?>&amp;todate=<?php print date($admindatestr,mktime(0,0,0,date("m",$thetodate),date("d",$thetodate)+1,date("Y",$thetodate)))?>"><?php print $yyMonth?> +</a>
			</div>
		  </form>
<?php
	if(getpost('act')=='abandoned' || getpost('act')=='oneabandoned') print '<script>document.forms.psearchform.submit();</script>';
}
?>