<?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(@$storesessionvalue=="") $storesessionvalue="virtualstore".time();
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';

if(@$_SESSION['loggedon']!=$storesessionvalue||@$GLOBALS['disallowlogin']||!@$GLOBALS['incfunctionsdefined']) exit;
$success=TRUE;
if(@$mailinglistpurgedays=='') $mailinglistpurgedays=32;
$alreadygotadmin=getadminsettings();
$dorefresh=FALSE;
$haserror=FALSE;
if(strtolower($adminencoding)=='iso-8859-1') $raquo='»'; else $raquo='>';
$resultcounter=0;
function writemenulevel($id,$itlevel){
	global $allcatsa,$numcats,$thecat,$raquo;
	if($itlevel<10){
		for($wmlindex=0; $wmlindex < $numcats; $wmlindex++){
			if($allcatsa[$wmlindex]['topSection']==$id){
				print "<option value='" . $allcatsa[$wmlindex]['sectionID'] . "'";
				if(is_array($thecat)){
					foreach($thecat as $catid){
						if($allcatsa[$wmlindex]['sectionID']==(int)$catid) print ' selected="selected"';
					}
				}
				print '>';
				for($index=0; $index < $itlevel-1; $index++)
					print $raquo . ' ';
				print $allcatsa[$wmlindex]['sectionWorkingName'] . "</option>\r\n";
				if($allcatsa[$wmlindex]['rootSection']==0) writemenulevel($allcatsa[$wmlindex]['sectionID'],$itlevel+1);
			}
		}
	}
}
function hiddenparams(){
	if(is_array($ordstate=@$_REQUEST['ordstate'])) $ordstate=implode(',',$ordstate);
	if(is_array($ordcountry=@$_REQUEST['ordcountry'])) $ordcountry=implode(',',$ordcountry);
	if(is_array($smanufacturer=@$_REQUEST['smanufacturer'])) $smanufacturer=implode(',',$smanufacturer);
	if(is_array($thecat=@$_REQUEST['scat'])) $thecat=implode(',',$thecat);
	writehiddenvar('stext', getpost('stext'));
	writehiddenvar('mindate', getpost('mindate'));
	writehiddenvar('maxdate', getpost('maxdate'));
	writehiddenvar('listem', getpost('listem'));
	writehiddenvar('stype', getpost('stype'));
	writehiddenvar('pg', getpost('pg'));
	writehiddenvar('id', getpost('id'));
	writehiddenvar('ordstate', $ordstate);
	writehiddenvar('ordcountry', $ordcountry);
	writehiddenvar('smanufacturer', $smanufacturer);
	writehiddenvar('scat', $thecat);
	writehiddenvar('stsearch', getpost('stsearch'));
	writehiddenvar('swholesale', getpost('swholesale'));
	writehiddenvar('sortorder', getpost('sort'));
}
function checkmailchimperror($res){
	$tretval=TRUE;
	if($res!=''){
		$mcrarray=json_decode($res);
		$mctype=@$mcrarray->{'type'};
		$mctitle=@$mcrarray->{'title'};
		$mcdetail=@$mcrarray->{'detail'};
		if($mctype!=''&&$mctitle!=''&&$mcdetail!=''){
			$tretval=FALSE;
			print '<div style="padding:30px;color:#f00;text-align:center">The following error occurred: ' . $mcdetail . '</div>';
			print '<div style="padding:30px;text-align:center"><input type="button" value="Go Back And Try Again" onclick="history.go(-1)"</div>';
		}
	}
	return $tretval;
}
if(getpost('posted')=='1'){
	if(getpost('act')=='confirm'){
		$sSQL="UPDATE mailinglist SET isconfirmed=1 WHERE email='" . escape_string(getpost('id')) . "'";
		ect_query($sSQL) or ect_error();
	}elseif(getpost('act')=='delete'){
		$sSQL="DELETE FROM mailinglist WHERE email='" . escape_string(getpost('id')) . "'";
		ect_query($sSQL) or ect_error();
		$dorefresh=TRUE;
	}elseif(getpost('act')=='doaddnew'){
		$sSQL="INSERT INTO mailinglist (email,mlName,isconfirmed,mlConfirmDate,mlIPAddress) VALUES ('" . escape_string(strtolower(getpost('email'))) . "','" . escape_string(getpost('mlname')) . "',1,'".date('Y-m-d', time())."','".escape_string(getipaddress())."')";
		@ect_query($sSQL);
		$dorefresh=TRUE;
	}elseif(getpost('act')=='domodify'){
		if(strtolower(getpost("email"))!=strtolower(getpost("id"))){
			$sSQL="SELECT email FROM mailinglist WHERE email='" . escape_string(strtolower(getpost('email'))) . "'";
			$result=ect_query($sSQL) or ect_error();
			if(ect_num_rows($result)>0) $haserror=TRUE;
			ect_free_result($result);
		}
		if($haserror)
			$errormessage='Cannot rename email from &quot;' . htmlspecials(getpost('id')) . '&quot; to &quot;' . htmlspecials(getpost('email')) . '&quot; as that address is already in use.';
		else{
			$sSQL="UPDATE mailinglist SET email='" . escape_string(strtolower(getpost('email'))) . "',mlName='" . escape_string(getpost('mlname')) . "' WHERE email='" . escape_string(strtolower(getpost('id'))) . "'";
			ect_query($sSQL) or ect_error();
			$dorefresh=TRUE;
		}
	}elseif(getpost('act')=='purgeunconfirmed'){
		$sSQL="DELETE FROM mailinglist WHERE isconfirmed=0 AND mlConfirmDate<'".date('Y-m-d', time()-($mailinglistpurgedays*60*60*24))."'";
		ect_query($sSQL) or ect_error();
		$dorefresh=TRUE;
	}elseif(getpost('act')=='checkemptyname'){
		@set_time_limit(300);
		$numpatched=0;
		$sSQL="SELECT DISTINCTROW email,ordName,ordLastName FROM mailinglist INNER JOIN orders ON mailinglist.email=orders.ordEMail WHERE mlName='' OR mlName IS NULL";
		$result=ect_query($sSQL) or ect_error();
		while($rs=ect_fetch_assoc($result)){
			$sSQL="UPDATE mailinglist SET mlName='" . escape_string(trim_($rs['ordName'] . ' ' . $rs['ordLastName'])) . "' WHERE email='" . escape_string($rs['email']) . "'";
			ect_query($sSQL) or ect_error();
			$numpatched++;
		}
		ect_free_result($result);
		print '<div style="margin:50px;text-align:center">Number of Names patched: ' . $numpatched . '</div>';
		$dorefresh=TRUE;
	}elseif(getpost('act')=='clearsent'){
		$sSQL="UPDATE mailinglist SET emailsent=0";
		ect_query($sSQL) or ect_error();
		$dorefresh=TRUE;
	}elseif(getpost('act')=='quickupdate'){
		foreach(@$_POST as $objItem => $objValue){
			if(substr($objItem, 0, 4)=='pra_'){
				$origid=substr($objItem, 4);
				$theid=getpost('pid'.$origid);
				$theval=trim(unstripslashes($objValue));
				$mlact=getpost('mlact');
				$sSQL='';
				if($mlact=='del'){
					if($theval=='del') $sSQL="DELETE FROM mailinglist";
				}
				if($sSQL!=''){
					$sSQL.=" WHERE email='".escape_string($theid)."'";
					ect_query($sSQL) or ect_error();
				}
			}
		}
		$dorefresh=TRUE;
	}
}
if($dorefresh){
	print '<meta http-equiv="refresh" content="1; url=adminmailinglist.php' .
		'?stext=' . urlencode(getpost('stext')) .
		'&ordstate=' . urlencode(getpost('ordstate')) .
		'&ordcountry=' . urlencode(getpost('ordcountry')) .
		'&smanufacturer=' . urlencode(getpost('smanufacturer')) .
		'&scat=' . urlencode(getpost('scat')) .
		'&stsearch=' . getpost('stsearch') .
		'&swholesale=' . getpost('swholesale') .
		'&sortorder=' . getpost('sortorder') .
		'&stype=' . urlencode(getpost('stype')) .
		'&listem=' . urlencode(getpost('listem')) .
		'&mindate=' . getpost('mindate') .
		'&maxdate=' . getpost('maxdate') .
		'&mlact=' . getpost('mlact') .
		'&pg=' . urlencode(getpost('pg'));
	print '">';
}
if(getpost('posted')=='1' && $haserror){
	print '<div style="padding:50px;text-align:center">' . $yySorErr . '</div>';
	print '<div style="padding:50px;text-align:center;color:#FF1010">' . $errormessage . '</div>';
	print '<div style="padding:50px;text-align:center"><input type="button" onclick="history.go(-1)" value="' . $yyClkBac . '"></div>';
}elseif(getpost('posted')=='1' && getpost('act')=='dosendem'){
	@set_time_limit(1800);
	$breatherseconds=(@$debugmode?10:300);
?>
<script>
/* <![CDATA[ */
function breatherfunction(){
	var breathersecs=document.getElementById('breathersecs');
	document.getElementById('emerrordiv').innerHTML='<?php print 'Taking breather. Sending next batch in <span id="breathersecs">'.$breatherseconds.'</span> seconds.'?><br><br>'+document.getElementById('emerrordiv').innerHTML;
	setTimeout('document.getElementById(\'breatherform\').submit();',<?php print ($breatherseconds*1000)?>);
	setInterval('document.getElementById(\'breathersecs\').innerHTML=Math.max(parseInt(document.getElementById(\'breathersecs\').innerHTML)-1,0)',1000);
}
function nextbatchfunction(){
	document.getElementById('emerrordiv').innerHTML+='<div style="text-align:center"><input type="button" value="Send Next Batch Now" onclick="document.getElementById(\'breatherform\').submit();"></div>';
	document.getElementById('totalsentsofar').value='';
}
/* ]]> */
</script>
      <table border="0" cellspacing="0" cellpadding="0" width="100%" align="center">
        <tr>
		  <td width="100%" align="center">
		  <form name="mainform" method="post" action="adminmailinglist.php" onsubmit="return formvalidator(this)">
<?php		writehiddenvar("posted", "1");
			writehiddenvar("act", "dosendem");
			hiddenparams(); ?>
            <table width="100%" border="0" cellspacing="2" cellpadding="1">
			  <tr>
                <td align="center"><strong><?php print $yyMaLiMa?> - Sending Emails</strong></td>
			  </tr>
			  <tr> 
                <td align="center"><br>&nbsp;<br>&nbsp;<br>&nbsp;<br>&nbsp;<br>&nbsp;<br>&nbsp;<br>
				<strong>Please do not refresh this page</strong>
				<br>&nbsp;<br>Sending email: <span name="sendspan" id="sendspan">1</span>
				<br>&nbsp;<br>&nbsp;<br>&nbsp;<br><div id="emerrordiv"></div><br>&nbsp;<br>&nbsp;<br>&nbsp;<br>&nbsp;<br>&nbsp;
				</td>
			  </tr>
			  <tr>
                <td align="center"><br>
                          <a href="adminmailinglist.php"><strong><?php print $yyAdmHom?></strong></a><br>
                          &nbsp;</td>
			  </tr>
            </table>
		  </form>
		  </td>
        </tr>
      </table>
<?php
	if(getpost('emformat')=='1' || getpost('emformat')=='2') $htmlemails=TRUE; else $htmlemails=FALSE;
	$sendemailerrnum=0;
	$sendemailerrdesc='';
	$batchesof=getpost('batchesof');
	$takebreather=(getpost("takebreather")=="ON");
	$totalsentsofar=getpost("totalsentsofar");
	$takingbreather=FALSE;
	if(! is_numeric($totalsentsofar)) $totalsentsofar=0;
	setcookie('EMAILBATCHNUM', getpost('batchesof'), time()+86400000, '/', '', @$_SERVER['HTTPS']=='on');
	if(! is_numeric($batchesof) || $batchesof=='') $batchesof=0; else $batchesof=(int)$batchesof;
	if($htmlemails==TRUE) $emlNl='<br>'; else $emlNl="\n";
	$theemail=getpost('theemail');
	if(getpost('emformat')=='2'&&@$htmleditor=='froala') $theemail=getpost('theemailfck');	
	$fromemail=getpost('fromemail');
	$GLOBALS['oremailfromname']=getpost('emailfromname');
	$unsubscribe=(getpost('unsubscribe')=='ON');
	$unsublink='';
	print '</div>'; // to match the div that encloses this include file.
	$index=0;
	if(@$customheaders==''){
		$customheaders="MIME-Version: 1.0".$GLOBALS['emailcr'];
		if(@$GLOBALS['oremailfromname']!='') $customheaders.='From: %fromname% <%from%>'.$GLOBALS['emailcr']; else $customheaders.='From: %from%'.$GLOBALS['emailcr'];
		if(@$htmlemails==TRUE)
			$customheaders.='Content-type: text/html; charset='.$emailencoding.$GLOBALS['emailcr'];
		else
			$customheaders.='Content-type: text/plain; charset='.$emailencoding.$GLOBALS['emailcr'];
	}else{
		if($htmlemails==TRUE)
			$customheaders=str_replace('text/plain', 'text/html', $customheaders);
		else
			$customheaders=str_replace('text/html', 'text/plain', $customheaders);
	}
	$rowcounter=0;
	$sSQL='SELECT email,mlName FROM mailinglist WHERE 1=1 ';
	if(getpost('sendto')=='0'){
		$sSQL="SELECT adminEmail AS email,'Admin' AS mlName FROM admin";
		$batchesof=0;
		$takebreather=FALSE;
	}elseif(getpost('sendto')=='1'){
		$sSQL.="AND selected<>0 ";
	}elseif(getpost('sendto')=='2'){
		// Nothing - entire DB
	}elseif(getpost('sendto')=='3'){
		$sSQL='SELECT affilEmail AS email,affilName AS mlName FROM affiliates WHERE 1=1 ';
		$unsubscribe=FALSE;
	}
	if(($batchesof!=0 || $takebreather) && getpost('sendto')!='3')
		$sSQL.='AND emailsent=0 ';
	if(getpost('sendto')!='0'&&getpost('sendto')!='3'){
		if(! @$noconfirmationemail==TRUE) $sSQL.='AND isconfirmed<>0 ';
		$sSQL.=' ORDER BY email';
	}
	$hasunsubscribe=strpos($theemail, '%unsubscribe%')!==FALSE;
	$result=ect_query($sSQL) or ect_error();
	while($rs=ect_fetch_assoc($result)){
		if($unsubscribe){
			if(! $hasunsubscribe) $unsublink=$emlNl . $emlNl . $yyToUnsu . $emlNl;
			$thelink=$storeurl . 'cart'.$GLOBALS['extension'].'?unsubscribe=' . $rs['email'];
			if($hasunsubscribe)
				$unsublink = $thelink;
			else{
				if(@$htmlemails==TRUE) $thelink='<a class="unsubscribe" href="' . $thelink . '">' . $thelink . '</a>';
				$unsublink.=$thelink;
			}
		}
		$temailtxt=replaceemailtxt($theemail,'%name%',$rs['mlName'],$replaceone);
		if($hasunsubscribe) $temailtxt=str_replace('%unsubscribe%',$unsublink,$temailtxt);
		if(! @$debugmode) dosendemail($rs['email'], $fromemail, '', getpost('emailsubject'), $temailtxt . (! $hasunsubscribe?$unsublink:''));
		if($sendemailerrnum!=0)
			print '<script>document.getElementById(\'emerrordiv\').innerHTML+=\'Could not send: ' . jsspecials($rs['email']) . ' : ' . $sendemailerrdesc . "<br>';</script>\r\n";
		else
			ect_query("UPDATE mailinglist SET emailsent=1 WHERE email='".escape_string($rs['email'])."'") or ect_error();
		if($batchesof!=0){
			if($totalsentsofar+$index>=$batchesof) break;
		}
		if($index % 50==0 || $index==1 || $index==10){
			print '<script>document.getElementById(\'sendspan\').innerHTML=' . ($totalsentsofar+$index) . ";</script>\r\n";
			flush();
		}
		if($index==50 && $takebreather){
			print '<script>breatherfunction();</script>' . "\r\n";
			$takingbreather=TRUE;
			break;
		}
		$index++;
	}
	$hassentall=($rs==FALSE);
	if($takebreather || $batchesof!=0){ ?>
<form method="post" id="breatherform" action="adminmailinglist.php">
<?php	foreach($_POST as $key=>$val){
			if($key!='totalsentsofar') print whv($key,$val);
		}
		if(is_numeric(getpost('totalsentsofar'))) $totalsentsofar=(int)getpost('totalsentsofar'); else $totalsentsofar=0;
		writehiddenidvar('totalsentsofar',$totalsentsofar+$index); ?>
</form>
<?php
	}
	if($batchesof!=0 && ! $hassentall & ! $takingbreather){
		print '<script language="javascript">nextbatchfunction();</script>' . "\r\n";
	}
	ect_free_result($result);
	print '<script>document.getElementById(\'sendspan\').innerHTML=\'' . ($totalsentsofar+$index) . " - All Done!';</script>\r\n";
	print '</body></html>';
	flush();
	exit;
}elseif(getpost('posted')=='1' && getpost('act')=='mailchimpdeletelist'&&@$mailchimpapikey!=''){
	$mcsuccess=TRUE;
	$xmlfnuser='anystr'; $xmlfnpassword=$mailchimpapikey;
	$mcpwarray=explode('-',$xmlfnpassword);
	$xmlfnheaders=array('Content-Type: application/json','X-HTTP-Method-Override: DELETE');
	if(callcurlfunction('https://'.$mcpwarray[1].'.api.mailchimp.com/3.0/lists/'.getpost('listid'),'DELETE',$res,'',$errormsg,FALSE)){
		// print 'RES: ' . $res."<br>\r\n";
		if($res!=''){
			$mcrarray=json_decode($res);
			$mctype=@$mcrarray->{'type'};
			$mctitle=@$mcrarray->{'title'};
			$mcdetail=@$mcrarray->{'detail'};
			if($mctype!=''&&$mctitle!=''&&$mcdetail!=''){
				$mcsuccess=FALSE;
				print '<div style="padding:30px;color:#f00;text-align:center">The following error occurred: ' . $mcdetail . '</div>';
				print '<div style="padding:30px;text-align:center"><input type="button" value="Go Back And Try Again" onclick="history.go(-1)"</div>';
			}
		}
	}
	if($mcsuccess) print  '<div style="padding:30px;text-align:center">' . $yyOpSuc . '</div><meta http-equiv="refresh" content="1; url=adminmailinglist.php?act=mailchimp">';
}elseif(getpost('posted')=='1' && getpost('act')=='syncmailchimp'&&@$mailchimpapikey!=''){
	@set_time_limit(1800);
	$mcsuccess=TRUE;
	$numemails=0;
	$rowcounter=0;
	$total_created=0;
	$total_updated=0;
	$error_count=0;
	$sSQL='SELECT COUNT(*) as tcount FROM mailinglist WHERE isconfirmed=1'.(getpost('subact')=='selected'?' AND selected<>0':'');
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)) $numemails=$rs['tcount'];
	ect_free_result($result);
	$mcpwarray=explode('-',$mailchimpapikey);
	if($numemails>0){
		$json_data='{"members": ['; $addcomma='';
		$sSQL='SELECT email,mlName,mlIPAddress,mlConfirmDate FROM mailinglist WHERE isconfirmed=1'.(getpost('subact')=='selected'?' AND selected<>0':'');
		$result=ect_query($sSQL) or ect_error();
		while(($rs=ect_fetch_assoc($result))&&$mcsuccess){
			splitname($rs['mlName'],$firstname,$lastname);
			$json_data.=$addcomma.'{"email_address":' . json_encode($rs['email']);
			if($rs['mlIPAddress']!=''&&$rs['mlIPAddress']!='::1') $json_data.=', "ip_signup":' . json_encode($rs['mlIPAddress']);
			if($rs['mlConfirmDate']!='') $json_data.=', "timestamp_signup":' . json_encode(date('Y-m-d 12:00:00', strtotime($rs['mlConfirmDate'])));
			$json_data.=', "status": "subscribed","merge_fields":{"FNAME":' . json_encode($firstname) . ',"LNAME":' . json_encode($lastname);

			$hasaddress=FALSE;
			$sSQL="SELECT clID,addAddress,addAddress2,addCity,addState,addZip,addCountry FROM customerlogin INNER JOIN address ON clID=addCustID WHERE clEmail='" . escape_string($rs['email']) . "' ORDER BY addIsDefault DESC LIMIT 0,1";
			$result2=ect_query($sSQL) or ect_error();
			if($rs2=ect_fetch_assoc($result2)){
				$hasaddress=TRUE;
				$addAddress=$rs2['addAddress'];
				$addAddress2=$rs2['addAddress2'];
				$addCity=$rs2['addCity'];
				$addState=$rs2['addState'];
				$addZip=$rs2['addZip'];
				$addCountry=$rs2['addCountry'];
			}
			if(!$hasaddress){
				$sSQL="SELECT ordID,ordAddress,ordAddress2,ordCity,ordState,ordZip,ordCountry FROM orders WHERE ordEmail='" . escape_string($rs['email']) . "' ORDER BY ordID DESC LIMIT 0,1";
				$result2=ect_query($sSQL) or ect_error();
				if($rs2=ect_fetch_assoc($result2)){
					$hasaddress=TRUE;
					$addAddress=$rs2['ordAddress'];
					$addAddress2=$rs2['ordAddress2'];
					$addCity=$rs2['ordCity'];
					$addState=$rs2['ordState'];
					$addZip=$rs2['ordZip'];
					$addCountry=$rs2['ordCountry'];
				}
			}
			if($hasaddress)
				$json_data.=',"ADDRESS":{"addr1":' . json_encode($addAddress) . ',"addr2":' . json_encode($addAddress2) . ',"city":' . json_encode($addCity) . 
					',"state":' . json_encode($addState) . ',"zip":' . json_encode($addZip) . ',"country":' . json_encode($addCountry) . '}';
			
			$json_data.='}}';
			$addcomma=',';
			$rowcounter++;
			if(($rowcounter % 500)==0){
				$json_data.='], "update_existing": true}';
				$xmlfnuser='anystr'; $xmlfnpassword=$mailchimpapikey;
				$xmlfnheaders=array('Content-Type: application/json');
				if(callcurlfunction('https://'.$mcpwarray[1].'.api.mailchimp.com/3.0/lists/'.getpost('listid'),$json_data,$res,'',$errormsg,FALSE)){
					$aljsonobj=json_decode($res);
					if(is_numeric(@$aljsonobj->{'total_created'})) $total_created+=(int)@$aljsonobj->{'total_created'};
					if(is_numeric(@$aljsonobj->{'total_updated'})) $total_updated+=(int)@$aljsonobj->{'total_updated'};
					if(is_numeric(@$aljsonobj->{'error_count'})) $error_count+=(int)@$aljsonobj->{'error_count'};
					$mcsuccess=checkmailchimperror($res);
				}
				$json_data='{"members": ['; $addcomma='';
			}
		}
		ect_free_result($result);
		if($mcsuccess){
			if(($rowcounter % 500)!=0){
				$json_data.='], "update_existing": true}';
				$xmlfnuser='anystr'; $xmlfnpassword=$mailchimpapikey;
				$xmlfnheaders=array('Content-Type: application/json');
				if(callcurlfunction('https://'.$mcpwarray[1].'.api.mailchimp.com/3.0/lists/'.getpost('listid'),$json_data,$res,'',$errormsg,FALSE)){
					$aljsonobj=json_decode($res);
					if(is_numeric(@$aljsonobj->{'total_created'})) $total_created+=(int)@$aljsonobj->{'total_created'};
					if(is_numeric(@$aljsonobj->{'total_updated'})) $total_updated+=(int)@$aljsonobj->{'total_updated'};
					if(is_numeric(@$aljsonobj->{'error_count'})) $error_count+=(int)@$aljsonobj->{'error_count'};
					$mcsuccess=checkmailchimperror($res);
				}
			}
			print '<div style="display:table;margin:auto">';
				print '<div class="ecttablerow">';
					print '<div style="text-align:right">Total Created : </div><div> ' . $total_created . '</div>';
				print '</div>';
				print '<div class="ecttablerow">';
					print '<div style="text-align:right">Total Updated : </div><div> ' . $total_updated . '</div>';
				print '</div>';
				print '<div class="ecttablerow">';
					print '<div style="text-align:right">Error Count : </div><div> ' . $error_count . '</div>';
				print '</div>';
			print '</div>';
		}
	}else
		print '<div style="padding:30px;text-align:center">No Emails To Sync.</div>';
	if($mcsuccess){
		print '<meta http-equiv="refresh" content="5; url=adminmailinglist.php?act=mailchimp">';
		adminsuccessforward("adminmailinglist.php","act=mailchimp");
	}
}elseif(getpost('posted')=='1' && getpost('act')=='mailchimpcreatelist'&&@$mailchimpapikey!=''){
	$mcsuccess=TRUE;
	$json_data='{"name":' . json_encode(getpost('mclistname')) . ',' .
		'"contact":{"company":' . json_encode(getpost('mccompany')) . ',' .
			'"address1":' . json_encode(getpost('mcaddr1')) . ',' .
			'"address2":' . json_encode(getpost('mcaddr2')) . ',' .
			'"city":' . json_encode(getpost('mccity')) . ',' .
			'"state":' . json_encode(getpost('mcstate')) . ',' .
			'"zip":' . json_encode(getpost('mczip')) . ',' .
			'"country":' . json_encode(getpost('mccountry')) . ',' .
			'"phone":""},' .
		'"visibility":' . json_encode(getpost('listpublicity')) . ',' .
		'"permission_reminder":' . json_encode(getpost('howsignedup')) . ',' .
		'"notify_on_subscribe":' . json_encode(getpost('mcnotifysubscribe')) . ',' .
		'"notify_on_unsubscribe":' . json_encode(getpost('mcnotifyunsubscribe')) . ',' .
		'"campaign_defaults":{"from_name":' . json_encode(getpost('mcdefaultfromname')) . ',' .
			'"from_email":' . json_encode(getpost('mcdefaultfromemail')) . ',' .
			'"subject":' . json_encode(getpost('mcdefaultsubject')) . ',' .
			'"language":"' . ($adminlang==''?'en':$adminlang) . '"},' .
		'"email_type_option":' . (getpost('mcemailtype')=='ON'?'true':'false') . '}';
	
	//print $json_data."<br>";
	
	$xmlfnuser='anystr'; $xmlfnpassword=$mailchimpapikey;
	$mcpwarray=explode('-',$xmlfnpassword);
	$xmlfnheaders=array('Content-Type: application/json');
	if(callcurlfunction('https://'.$mcpwarray[1].'.api.mailchimp.com/3.0/lists',$json_data,$res,'',$errormsg,FALSE)){
		// print 'RES: ' . $res."<br>\r\n";
		if($res!=''){
			$mcrarray=json_decode($res);
			$mctype=@$mcrarray->{'type'};
			$mctitle=@$mcrarray->{'title'};
			$mcdetail=@$mcrarray->{'detail'};
			if($mctype!=''&&$mctitle!=''&&$mcdetail!=''){
				$mcsuccess=FALSE;
				print '<div style="padding:30px;color:#f00;text-align:center">The following error occurred: ' . $mcdetail . '</div>';
				print '<div style="padding:30px;text-align:center"><input type="button" value="Go Back And Try Again" onclick="history.go(-1)"</div>';
			}
		}
	}
	if($mcsuccess) print  '<div style="padding:30px;text-align:center">' . $yyOpSuc . '</div><meta http-equiv="refresh" content="1; url=adminmailinglist.php?act=mailchimp">';
}elseif((getpost('posted')=='1' && getpost('act')=='mailchimp') || getget('act')=='mailchimp'){
	$isresetkey=FALSE;
	$errormsg='';
	if(getget('subact')=='resetkey'){
		$isresetkey=TRUE;
	}elseif(getpost('subact')=='updateapikey'){
		$sSQL="UPDATE admin SET mailchimpAPIKey='" . escape_string(getpost('apikey')) . "' WHERE adminID=1";
		ect_query($sSQL);
		$sSQL="SELECT mailchimpAPIKey FROM admin WHERE adminID=1";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)) $mailchimpapikey=$rs['mailchimpAPIKey'];
		ect_free_result($result);
	}elseif(getpost('subact')=='usemailchimplist'){
		$sSQL="UPDATE admin SET mailchimpList='" . escape_string(getpost('listid')) . "' WHERE adminID=1";
		ect_query($sSQL);
		$sSQL="SELECT mailchimpList FROM admin WHERE adminID=1";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)) $mailchimplist=$rs['mailchimpList'];
		ect_free_result($result);
	}
	?>
<script>
/* <![CDATA[ */
function confirmdelete(){
if(confirm("Are you sure you want to delete the MailChimp API Key?")){
	document.forms.apikeyform.apikey.value="";
	document.forms.apikeyform.submit();
}
}
function formvalidator2(theForm){
if (theForm.apikey.value==""){
alert("<?php print jscheck($yyPlsEntr . ' "' . 'API Key')?>\".");
theForm.apikey.focus();
return(false);
}
if (theForm.apikey.value.indexOf("-")===-1){
alert("You must include the full MailChimp API Key, including the server (for example \"-us12\")\".");
theForm.apikey.focus();
return(false);
}
return true;
}
function formvalidator(theForm){
if (theForm.mclistname.value==""){
alert("<?php print jscheck($yyPlsEntr . ' "' . 'List Name')?>\".");
theForm.mclistname.focus();
return(false);
}
if (theForm.mcdefaultfromemail.value==""){
alert("<?php print jscheck($yyPlsEntr . ' "' . 'Default From Email')?>\".");
theForm.mcdefaultfromemail.focus();
return(false);
}
if (theForm.mcdefaultfromname.value==""){
alert("<?php print jscheck($yyPlsEntr . ' "' . 'Default From Name')?>\".");
theForm.mcdefaultfromname.focus();
return(false);
}
if (theForm.howsignedup.value==""){
alert("<?php print jscheck($yyPlsEntr . ' "' . 'Remind people how they signed up to your list')?>\".");
theForm.howsignedup.focus();
return(false);
}
if (theForm.mccompany.value==""){
alert("<?php print jscheck($yyPlsEntr . ' "' . 'Company / organization')?>\".");
theForm.mccompany.focus();
return(false);
}
if (theForm.addr1.value==""){
alert("<?php print jscheck($yyPlsEntr . ' "' . 'Address')?>\".");
theForm.addr1.focus();
return(false);
}
if (theForm.mccity.value==""){
alert("<?php print jscheck($yyPlsEntr . ' "' . 'City')?>\".");
theForm.mccity.focus();
return(false);
}
if (theForm.mcstate.value==""){
alert("<?php print jscheck($yyPlsEntr . ' "' . 'State / Province / Region')?>\".");
theForm.mcstate.focus();
return(false);
}
if (theForm.mczip.value==""){
alert("<?php print jscheck($yyPlsEntr . ' "' . 'Zip / Postal code')?>\".");
theForm.mczip.focus();
return(false);
}
if (theForm.mccountry.selectedIndex==0){
	alert("<?php print jscheck($yyPlsSel . ' "' . 'Country')?>\".");
	return(false);
}
return(true);
}
function synclist(listid,listname){
	if(confirm("<?php print jscheck($yySureCa)?>")){
		document.getElementById('syncact').value='syncmailchimp';
		document.getElementById('synclistid').value=listid;
		document.getElementById('syncsubact').value='all';
		document.getElementById('synclistname').value=listname;
		document.getElementById('synclistform').submit();
	}
}
function synclistselected(listid,listname){
	if(confirm("<?php print jscheck($yySureCa)?>")){
		document.getElementById('syncact').value='syncmailchimp';
		document.getElementById('synclistid').value=listid;
		document.getElementById('syncsubact').value='selected';
		document.getElementById('synclistname').value=listname;
		document.getElementById('synclistform').submit();
	}
}
function deletelist(listid,listname){
	if(confirm("<?php print jscheck($yyConDel)?>")){
		document.getElementById('syncact').value='mailchimpdeletelist';
		document.getElementById('synclistid').value=listid;
		document.getElementById('synclistname').value=listname;
		document.getElementById('synclistform').submit();
	}
}
function uselist(listid){
	if(confirm("<?php print jscheck($yySureCa)?>")){
		document.getElementById('syncact').value='mailchimp';
		document.getElementById('syncsubact').value='usemailchimplist';
		document.getElementById('synclistid').value=listid;
		document.getElementById('synclistform').submit();
	}
}
function actionmenu(selmenid,listid){
	var selmenobj=document.getElementById('actmen'+selmenid);
	var taction=selmenobj[selmenobj.selectedIndex].value;
	if(taction=='')
		alert("Please select an action");
	else if(taction=='1')
		synclist(listid,'');
	else if(taction=='2')
		synclistselected(listid,'');
	else if(taction=='3')
		deletelist(listid,'');
	else if(taction=='4')
		uselist(listid);
}
/* ]]> */
</script>
<?php
	if(@$mailchimpapikey!=''&&strpos(@$mailchimpapikey,'-')!==FALSE&&!$isresetkey){
		$http_status=$numallemails=$numselectedemails=0;
		$sSQL="SELECT COUNT(*) AS tcount FROM mailinglist WHERE isconfirmed=1";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)) $numallemails=$rs['tcount'];
		ect_free_result($result);
		$sSQL="SELECT COUNT(*) AS tcount FROM mailinglist WHERE isconfirmed=1 AND selected<>0";
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)) $numselectedemails=$rs['tcount'];
		ect_free_result($result);
		print '<form id="synclistform" method="post" action="adminmailinglist.php">';
		print '<input type="hidden" name="act" id="syncact" value="syncmailchimp">';
		print '<input type="hidden" name="subact" id="syncsubact" value="">';
		print '<input type="hidden" name="posted" value="1">';
		print '<input type="hidden" name="listid" id="synclistid" value="">';
		print '<input type="hidden" name="listname" id="synclistname" value="">';
		print '</form>';
		$xmlfnuser='anystr'; $xmlfnpassword=$mailchimpapikey;
		$mcpwarray=explode('-',$xmlfnpassword,2);
		$xmlfnheaders=array("Content-Type: application/json");
		if($mcpwarray[1]==''){
			$isresetkey=TRUE;
			$errormsg="The MailChimp Server address is invalid";
		}elseif(callcurlfunction('https://'.$mcpwarray[1].'.api.mailchimp.com/3.0/','',$res,'',$errormsg,FALSE)){
			//print '<pre>' . str_replace(array(',','{','}'),array('<br>,','<br>{','<br>}'),$res) . "</pre><br><br>";
			$mcrarray=json_decode($res);
			if($http_status!=200){
				$isresetkey=TRUE;
				$errormsg=@$mcrarray->{'detail'};
			}else{
				$mccompany=@$mcrarray->{'contact'}->{'company'};
				$mcaddr1=@$mcrarray->{'contact'}->{'addr1'};
				$mcaddr2=@$mcrarray->{'contact'}->{'addr2'};
				$mccity=@$mcrarray->{'contact'}->{'city'};
				$mcstate=@$mcrarray->{'contact'}->{'state'};
				$mczip=@$mcrarray->{'contact'}->{'zip'};
				$mccountry=@$mcrarray->{'contact'}->{'country'};
				$mcemail=@$mcrarray->{'email'};
				$proenabled=@$mcrarray->{'pro_enabled'};
				print '<div id="accountdetails" class="ecttable">';
				print '<div class="ecttablerow"><div>API Key</div><div>' . substr($mcpwarray[0],0,4) . '************************' . substr($mcpwarray[0],-4) . '-' . $mcpwarray[1] . ' <a href="adminmailinglist.php?act=mailchimp&amp;subact=resetkey">(Reset / Delete API Key)</a></div></div>';
				print '<div class="ecttablerow"><div>Account ID</div><div>' . @$mcrarray->{'account_id'} . '</div></div>';
				print '<div class="ecttablerow"><div>Login ID</div><div>' . @$mcrarray->{'login_id'} . '</div></div>';
				print '<div class="ecttablerow"><div>Account Name</div><div>' . @$mcrarray->{'account_name'} . '</div></div>';
				print '<div class="ecttablerow"><div>Email</div><div>' . $mcemail . '</div></div>';
				print '<div class="ecttablerow"><div>Account Name</div><div>' . trim(@$mcrarray->{'first_name'} . ' ' . @$mcrarray->{'last_name'}) . '</div></div>';
				print '<div class="ecttablerow"><div>-</div><div>-</div></div>';
				print '<div class="ecttablerow"><div>Contact Information</div><div>' . $mccompany . '<br>' . $mcaddr1 . '<br>' . ($mcaddr2!=''?$mcaddr2.'<br>':'') . $mccity . ($mcstate!=''?', ' . $mcstate:'') . '<br>' . $mczip . '<br>' . $mccountry . '<br>' . '</div></div>';
				
				$xmlfnuser='anystr'; $xmlfnpassword=$mailchimpapikey;
				if(callcurlfunction('https://'.$mcpwarray[1].'.api.mailchimp.com/3.0/lists','',$res,'',$errormsg,FALSE)){
					$mcrarray=json_decode($res);
					$numlists=@$mcrarray->{'total_items'};
					$rowcounter=1;
					print '<div class="ecttablerow"><div>Lists Defined</div><div>' . $numlists . '</div></div>';
					for($index=0;$index<$numlists;$index++){
						$listid=@$mcrarray->{'lists'}[$index]->{'id'};
						$listname=@$mcrarray->{'lists'}[$index]->{'name'};
						$listmembercount=@$mcrarray->{'lists'}[$index]->{'stats'}->{'member_count'};
						print '<div class="ecttablerow"><div style="text-align:right' . (@$mailchimplist==$listid?';border:1px solid red':'') . '">' . $listname . ' - ' . $listmembercount . ' Members : </div><div>';
							print '<select id="actmen'.$rowcounter.'" size="1" style="width:300px;vertical-align:middle">';
							print '<option value="">' . $yySelect . '</option>';
							print '<option value="1">Sync ALL emails (' . $numallemails . ') with list: ' . htmlspecials($listname) . '</option>';
							if($numselectedemails!=$numallemails && $numselectedemails!=0) print '<option value="2">Sync selected emails (' . $numselectedemails . ') with list: ' . htmlspecials($listname) . '</option>';
							if(@$mailchimplist!=$listid){
								print '<option value="3">Delete list: ' . htmlspecials($listname) . '</option>';
								print '<option value="4">Add new signups to this list: ' . htmlspecials($listname) . '</option>';
							}
							print '</select>';
							print ' <input type="button" value="Go" onclick="actionmenu('.$rowcounter.",'" . $listid . '\')">';
						print '</div></div>';
						$rowcounter++;
					}
					print '<div class="ecttablerow"><div style="text-align:right' . ($mailchimplist==''?';border:1px solid red':'') . '">Ecommerce Plus Database - ' . $numallemails . ' Members : </div><div>';
					print '<select id="actmen'.$rowcounter.'" size="1" style="width:300px;vertical-align:middle">';
					print '<option value="">' . $yySelect . '</option>';
					print '<option value="4">Add new signups to this list: Ecommerce Plus Database</option>';
					print '</select> <input type="button" value="Go" onclick="actionmenu('.$rowcounter.',\'\')">';
					print '</div></div>';
				}
				print '<div class="ecttablerow"><div>&nbsp;</div><div><input type="button" id="createlistbutton" value="Create Mailchimp List" onclick="document.getElementById(\'accountdetails\').style.display=\'none\';document.getElementById(\'newmclist\').style.display=\'\'"></div></div>';
				print '</div>';

				// print '<br><br>' . $res . "<br><br>";
				
				print '<form method="post" action="adminmailinglist.php" onsubmit="return formvalidator(this)"><input type="hidden" name="posted" value="1"><input type="hidden" name="act" value="mailchimpcreatelist">';

				print '<div id="newmclist" style="display:none;padding:10px 0px;width:50%">';
				print '<h2>Create List</h2>';
				print '<h4>List details</h4>';
				print '<p style="padding-top:10px">' . $redasterix . ' List Name</p>';
				print '<input type="text" name="mclistname" style="width:100%">';
				print '<p style="font-size:0.8em;color:#555">Your subscribers will see this, so make it something appropriate.<br>Good example: "Acme Company Newsletter"<br>Bad example: "Cust_11_01_2007"</p>';

				print '<p style="padding-top:10px">' . $redasterix . ' Default From Email</p>';
				print '<input type="text" name="mcdefaultfromemail" style="width:100%">';
				print '<p style="font-size:0.8em;color:#555">This is the address people will reply to.</p>';

				print '<p style="padding-top:10px">' . $redasterix . ' Default From Name</p>';
				print '<input type="text" name="mcdefaultfromname" style="width:100%">';
				print '<p style="font-size:0.8em;color:#555">This is who your emails will come from. Use something they\'ll instantly recognize, like your company name.</p>';

				print '<p style="padding-top:10px">' . $redasterix . ' Default Subject</p>';
				print '<input type="text" name="mcdefaultsubject" style="width:100%">';
				print '<p style="font-size:0.8em;color:#555">Keep it relevant and non-spammy.</p>';

				print '<p style="padding-top:10px">List publicity: ';
				print '<select size="1" name="listpublicity"><option value="pub">Public</option><option value="prv">Private</option></select></p>';
				print '<p style="font-size:0.8em;color:#555">By default, campaigns are marked as public, but you can grant or revoke access to your data at any time.</p>';

				print '<p style="padding-top:10px">' . $redasterix . ' Remind people how they signed up to your list</p>';
				print '<textarea name="howsignedup" value="" style="height:5em;width:100%"></textarea>';
				print '<p style="font-size:0.8em;color:#555">Example: "You are receiving this email because you opted in at our website &hellip; " or "We send special offers to customers who opted in at &hellip; "</p>';
				
				print '<div id="contactinfo">';
					print '<p style="padding-top:10px">Contact information for the list. (<a target="_blank" href="http://kb.mailchimp.com/accounts/compliance-tips/terms-of-use-and-anti-spam-requirements?&_ga=2.156609917.778392790.1498039288-1254932490.1498039288">Why is this necessary</a>).</p>';
					print '<div style="background-color:#ccebf3;padding:10px;margin:10px 0px">' . $mccompany . '<br>' . $mcaddr1 . '<br>' . ($mcaddr2!=''?$mcaddr2.'<br>':'') . $mccity . ($mcstate!=''?', ' . $mcstate:'') . '<br>' . $mczip . '<br>' . $mccountry . '<br>' . '</div>';
					print '<input type="button" value="Edit" onclick="document.getElementById(\'contactinfo\').style.display=\'none\';document.getElementById(\'addressdiv\').style.display=\'\'">';
				print '</div>';

				print '<div id="addressdiv" style="display:none">';
					print '<p style="padding-top:10px">' . $redasterix . ' Company / organization</p>';
					print '<input type="text" name="mccompany" style="width:100%" value="' . htmlspecials($mccompany) . '">';
					
					print '<p style="padding-top:10px">' . $redasterix . ' Address</p>';
					print '<input type="text" name="mcaddr1" style="width:100%;margin-bottom:5px" value="' . htmlspecials($mcaddr1) . '">';
					print '<input type="text" name="mcaddr2" style="width:100%" value="' . htmlspecials($mcaddr2) . '">';

					print '<p style="padding-top:10px">' . $redasterix . ' City</p>';
					print '<input type="text" name="mccity" style="width:100%" value="' . htmlspecials($mccity) . '">';
					
					print '<p style="padding-top:10px">' . $redasterix . ' State / Province / Region</p>';
					print '<input type="text" name="mcstate" style="width:100%" value="' . htmlspecials($mcstate) . '">';
					
					print '<p style="padding-top:10px">' . $redasterix . ' Zip / Postal code</p>';
					print '<input type="text" name="mczip" style="width:100%" value="' . htmlspecials($mczip) . '">';
					
					print '<p style="padding-top:10px">' . $redasterix . ' Country</p>';				
					print '<select name="mccountry" size="1" style="width:100%">';
					$sSQL="SELECT countryCode,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="' . $rs['countryCode'] . '"';
						if($mccountry==$rs['countryCode']) print ' selected="selected"';
						print '>' . $rs['countryName'] . '</option>';
					}
					ect_free_result($result);
					print '</select>';
				print '</div>';
				
				print '<h4 style="padding-top:20px">New subscriber notifications</h4>';
				
				print '<p style="padding-top:10px">Email subscribe notifications to:</p>';
				print '<input type="text" name="mcnotifysubscribe" style="width:100%" value="">';
				print '<p style="font-size:0.8em;color:#555">Get quick email alerts when subscribers join or leave this list (not recommended for large lists). Additional email addresses must be separated by a comma.</p>';
				
				print '<p style="padding-top:10px">Email unsubscribe notifications to:</p>';
				print '<input type="text" name="mcnotifyunsubscribe" style="width:100%" value="">';
				print '<p style="font-size:0.8em;color:#555">Get quick email alerts when subscribers join or leave this list (not recommended for large lists). Additional email addresses must be separated by a comma.</p>';
				
				print '<p style="padding-top:10px">Email daily digest to:</p>';
				print '<input type="text" name="mcdailydigestemail" style="width:100%" value="">';
				print '<p style="font-size:0.8em;color:#555">Get an end-of-the-day summary of subscribe and unsubscribe activity.</p>';
				
				print '<div>&nbsp;</div>';

				if(FALSE){
					print '<div style="float:left;height:40px"><input style="margin:3px 10px" class="ectcheckbox" type="checkbox" name="mcdailysummary"></div><div>Send a final welcome email</div>';
					print '<div style="font-size:0.8em;color:#555">When people opt-in to your list, send them an email welcoming them to your list. The final welcome email can be edited in the list forms designer.</div>';
					
					print '<div>&nbsp;</div>';
				}

				print '<div style="float:left;height:40px"><input style="margin:3px 10px" class="ectcheckbox" type="checkbox" name="mcemailtype" value="ON"></div><div>Let users pick plain-text or HTML emails.</div>';
				print '<div style="font-size:0.8em;color:#555">When people sign up for your list, you can let them specify which email format they prefer to receive. If they choose "Plain-text", then they won\'t receive your fancy HTML version.</div>';
				
				print '<div>&nbsp;</div>';

				if(FALSE){
					print '<div style="float:left;height:40px"><input style="margin:3px 10px" class="ectcheckbox" type="checkbox" name="mcsendunsubconfirm"></div><div>Send unsubscribe confirmations to subscribers</div>';
					print '<div style="font-size:0.8em;color:#555">Send subscribers a final "Goodbye" email to let them know they have unsubscribed. These are helpful in cases where subscribers are accidentally unsubscribed by someone they forwarded a campaign to, a spam-filter/firewall, or the like.</div>';
				
					print '<div>&nbsp;</div>';
				}

				print '<input type="submit" value="Create Mailchimp List"> <input type="button" value="Cancel" onclick="document.getElementById(\'accountdetails\').style.display=\'\';document.getElementById(\'newmclist\').style.display=\'none\'" ';

				print '</div>';
				print '</form>';
			}
		}else
			$isresetkey=TRUE;
	}else
		$isresetkey=TRUE;
	if($isresetkey){ ?>
		<form method="post" action="adminmailinglist.php" name="apikeyform" onsubmit="return formvalidator2(this)">
		<input type="hidden" name="posted" value="1">
		<input type="hidden" name="act" value="mailchimp">
		<input type="hidden" name="subact" value="updateapikey">
		<h2>Please enter your MailChimp API Key</h2>
		<div style="padding-bottom:10px">This will be of the form abab01cd45984fbaab856a8ef31680a0-us12</div>
<?php	if($errormsg!=''){ ?>
		<div class="ectred" style="padding-bottom:10px"><?php print $errormsg?></div>
<?php	}
		if(($mailchimpapikey!='' && strpos(@$mailchimpapikey,'-')===FALSE) || $errormsg!=''){ ?>
		<div class="ectred" style="padding-bottom:10px">You must include the full MailChimp API Key, including the server (for example &quot;-us12&quot;)</div>
<?php	} ?>
		<div style="padding-bottom:10px">API Key: <input type="text" name="apikey" size="50"></div>
		<div style="padding-bottom:10px"><input type="submit" value="<?php print $yySubmit?>">
<?php	if($mailchimpapikey!=''){ ?>
			&nbsp;&nbsp;<input type="button" value="Delete API Key" onclick="confirmdelete()">
<?php	} ?>
		</div>
		<div style="padding-bottom:10px;font-size:0.8em;color:#555">(you only need to do this once.)</div>
		</form>
<?php
	}
}elseif(getpost('posted')=='1' && getpost('act')=='sendem'){ ?>
<script>
/* <![CDATA[ */
function formvalidator(theForm){
<?php	if(@$htmleditor=='ckeditor'||@$htmleditor=='froala'){ ?>
	if(wasusingfck){
		var inst=theemailfck;
		var sValue=inst.getData();
		if(sValue=='<br>') sValue='';
		document.getElementById("theemail").value=sValue;
	}
<?php	} ?>
if (theForm.fromemail.value==""){
alert("<?php print jscheck($yyPlsEntr . ' "' . $yyFrmEm)?>\".");
theForm.fromemail.focus();
return(false);
}
if (theForm.emailsubject.value==""){
alert("<?php print jscheck($yyPlsEntr . ' "' . $yySubjc)?>\".");
theForm.emailsubject.focus();
return(false);
}
if (theForm.theemail.value==""){
alert("<?php print jscheck($yyPlsEntr . ' "' . $yyMessag)?>\".");
if(!wasusingfck) theForm.theemail.focus();
return(false);
}
if (theForm.sendto.selectedIndex!=0){
	if(!confirm("<?php print jscheck($yyCanSpm)?>")){
		return(false);
	}
}
<?php	if(@$htmleditor=='ckeditor'||@$htmleditor=='froala'){ ?>
	if(wasusingfck){
		document.getElementById("fckrow").style.display='none';
		document.getElementById("textarearow").style.display='';
	}
<?php	} ?>
return(true);
}
var wasusingfck=false;
function changeemailformat(obj){
<?php	if(@$htmleditor=='ckeditor'||@$htmleditor=='froala'){
			if(@$htmleditor=='ckeditor'){ ?>
	var inst=CKEDITOR.instances.theemailfck;
<?php		} ?>
	if(obj.selectedIndex==2){
		if(!wasusingfck){
<?php		if(@$htmleditor=='ckeditor'){ ?>
			inst.setData(document.getElementById("theemail").value);
<?php		}else{ ?>
			dfe_theemailfck();
			$('#theemailfck').froalaEditor('html.set',document.getElementById("theemail").value);
<?php		} ?>
			document.getElementById("fckrow").style.display='';
			document.getElementById("textarearow").style.display='none';
		}
		wasusingfck=true;
	}else{
		if(wasusingfck){
<?php		if(@$htmleditor=='ckeditor'){ ?>
			var sValue=inst.getData();
			if(sValue=='<br>') sValue='';
<?php		}else{ ?>
			var sValue=$('#theemailfck').froalaEditor('html.get');
<?php		} ?>
			document.getElementById("theemail").value=sValue;
			document.getElementById("fckrow").style.display='none';
			document.getElementById("textarearow").style.display='';
		}
		wasusingfck=false;
	}
<?php	} ?>
}
/* ]]> */
</script>
<?php	if(@$htmleditor=='ckeditor'){ ?>
<script src="ckeditor/ckeditor.js"></script>
<?php	} ?>
      <table border="0" cellspacing="0" cellpadding="0" width="100%" align="center">
        <tr>
		  <td width="100%" align="center">
		  <form name="mainform" method="post" action="adminmailinglist.php" onsubmit="return formvalidator(this)">
<?php		$batchsent=0; $numselected=0;
			$sSQL='SELECT COUNT(*) AS batchsent FROM mailinglist WHERE emailsent<>0';
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				if(! is_null($rs['batchsent'])) $batchsent=$rs['batchsent'];
			}
			ect_free_result($result);
			$sSQL='SELECT COUNT(*) AS numselected FROM mailinglist WHERE selected<>0';
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				if(! is_null($rs['numselected'])) $numselected=$rs['numselected'];
			}
			ect_free_result($result);
			
			$sSQL='SELECT emailfromname FROM admin WHERE adminID=1';
			$result=ect_query($sSQL) or ect_error();
			$rs=ect_fetch_assoc($result);
			$GLOBALS['emailfromname']=$rs['emailfromname'];
			ect_free_result($result);
			
			writehiddenvar("posted", "1");
			writehiddenvar("act", "dosendem");
			hiddenparams(); ?>
            <table width="100%" border="0" cellspacing="2" cellpadding="2">
			  <tr> 
                <td colspan="2" align="center" height="34"><strong><?php print $yyMaLiMa.' - '.$yySeEma?></strong></td>
			  </tr>
			  <tr>
				<td align="right" height="34"><?php print $yySenTo?>:</td>
				<td align="left"><select name="sendto" size="1">
							<option value="0"><?php print $yyAdmEm?></option>
<?php	if($numselected>0) print '<option value="1">'.$yySelEm.' (' . $numselected . ')</option>'; ?>
							<option value="2"><?php print $yyEntML?></option>
							<option value="3"><?php print $yyEntAL?></option>
						</select>
				</td>
			  </tr>
			  <tr>
				<td align="right" height="34"><?php print $yyEmlFm?>:</td>
				<td align="left"><select name="emformat" size="1" onchange="changeemailformat(this)">
							<option value="0"><?php print $yyText?></option>
							<option value="1">HTML</option>
<?php			if(@$htmleditor=='ckeditor'||@$htmleditor=='froala'){ ?>
							<option value="2">HTML Using HTML Editor</option>
<?php			} ?>
					</select>
				</td>
			  </tr>
			  <tr>
				<td align="right" height="34">Send in batches of:</td>
				<td align="left"><select name="batchesof" size="1">
							<option value="0">Unlimited</option>
							<option value="2"<?php if(@$_COOKIE['EMAILBATCHNUM']=='2') print ' selected="selected"'?>>2</option>
							<option value="50"<?php if(@$_COOKIE['EMAILBATCHNUM']=='50') print ' selected="selected"'?>>50</option>
							<option value="100"<?php if(@$_COOKIE['EMAILBATCHNUM']=='100') print ' selected="selected"'?>>100</option>
							<option value="150"<?php if(@$_COOKIE['EMAILBATCHNUM']=='150') print ' selected="selected"'?>>150</option>
							<option value="200"<?php if(@$_COOKIE['EMAILBATCHNUM']=='200') print ' selected="selected"'?>>200</option>
							<option value="300"<?php if(@$_COOKIE['EMAILBATCHNUM']=='300') print ' selected="selected"'?>>300</option>
							<option value="400"<?php if(@$_COOKIE['EMAILBATCHNUM']=='400') print ' selected="selected"'?>>400</option>
							<option value="500"<?php if(@$_COOKIE['EMAILBATCHNUM']=='500') print ' selected="selected"'?>>500</option>
							<option value="750"<?php if(@$_COOKIE['EMAILBATCHNUM']=='750') print ' selected="selected"'?>>750</option>
							<option value="1000"<?php if(@$_COOKIE['EMAILBATCHNUM']=='1000') print ' selected="selected"'?>>1000</option>
							<option value="1500"<?php if(@$_COOKIE['EMAILBATCHNUM']=='1500') print ' selected="selected"'?>>1500</option>
							<option value="2000"<?php if(@$_COOKIE['EMAILBATCHNUM']=='2000') print ' selected="selected"'?>>2000</option>
							<option value="3000"<?php if(@$_COOKIE['EMAILBATCHNUM']=='3000') print ' selected="selected"'?>>3000</option>
							<option value="4000"<?php if(@$_COOKIE['EMAILBATCHNUM']=='4000') print ' selected="selected"'?>>4000</option>
							<option value="5000"<?php if(@$_COOKIE['EMAILBATCHNUM']=='5000') print ' selected="selected"'?>>5000</option>
							<option value="10000"<?php if(@$_COOKIE['EMAILBATCHNUM']=='10000') print ' selected="selected"'?>>10000</option>
					</select>
<?php		if($batchsent!=0) print ' (' . $batchsent . ' Sent)' ?>
				</td>
			  </tr>
			  <tr>
				<td align="right" height="34">Take Breather every 50 emails:</td>
				<td align="left"><input type="checkbox" name="takebreather" value="ON">
				</td>
			  </tr>
			  <tr>
				<td align="right" height="34"><?php print $yyFrmEm?>:</td>
				<td align="left"><input type="text" name="fromemail" size="40" value="<?php print $emailAddr?>">
				</td>
			  </tr>
			  <tr>
				<td align="right" height="34"><?php print 'Email &quot;From&quot; Name'?>:</td>
				<td align="left"><input type="text" name="emailfromname" size="40" value="<?php print $GLOBALS['emailfromname']?>">
				</td>
			  </tr>
			  <tr>
				<td align="right" height="34"><?php print $yySubjc?>:</td>
				<td align="left"><input type="text" name="emailsubject" size="40">
				</td>
			  </tr>
			  <tr>
				<td align="right" height="34"><?php print $yyUnsubL?>:</td>
				<td align="left"><input type="checkbox" name="unsubscribe" value="ON" checked="checked">
				</td>
			  </tr>
<?php			if(@$htmleditor=="ckeditor"||@$htmleditor=='froala'){ ?>
			  <tr id="fckrow" style="display:none">
				<td align="right" height="34">&nbsp;</td>
				<td align="left"><textarea name="theemailfck" id="theemailfck" cols="70" rows="35"></textarea></td>
			  </tr>
<?php			} ?>
			  <tr id="textarearow">
				<td align="right" height="34">&nbsp;</td>
				<td align="left"><textarea name="theemail" id="theemail" cols="70" rows="35"></textarea></td>
			  </tr>
			  <tr>
                <td colspan="2" align="center" height="34">
					<p><span style="color:#F00">Important Note:</span> All images must use an absolute path or they won't display in your emails, for example&hellip;</p>
					<p><?php print $GLOBALS['storeurl']?>images/yourimage.jpg</p>
					<p style="margin-top:10px"><input type="submit" value="<?php print $yySubmit?>">&nbsp;<input type="reset" value="<?php print $yyReset?>"></p>
				</td>
			  </tr>
			  <tr>
                <td colspan="2" align="center" height="34"><br>
                          <a href="adminmailinglist.php"><strong><?php print $yyAdmHom?></strong></a><br>
                          &nbsp;</td>
			  </tr>
            </table>
		  </form>
		  </td>
        </tr>
      </table>
<?php
	if(@$htmleditor=="ckeditor"){
		$pathtovsadmin=dirname(@$_SERVER['PHP_SELF']);
		print '<script>';
		print "var theemailfck=CKEDITOR.replace('theemailfck',{width: 660,height: 800,toolbarStartupExpanded : false, toolbar : 'Basic', filebrowserBrowseUrl :'ckeditor/filemanager/browser/default/browser.html?Connector=".$pathtovsadmin."/ckeditor/filemanager/connectors/php/connector.php',filebrowserImageBrowseUrl : 'ckeditor/filemanager/browser/default/browser.html?Type=Image&Connector=".$pathtovsadmin."/ckeditor/filemanager/connectors/php/connector.php',filebrowserFlashBrowseUrl :'ckeditor/filemanager/browser/default/browser.html?Type=Flash&Connector=".$pathtovsadmin."/ckeditor/filemanager/connectors/php/connector.php',filebrowserUploadUrl:'".$pathtovsadmin."/ckeditor/filemanager/connectors/php/upload.php?Type=File',filebrowserImageUploadUrl:'".$pathtovsadmin."/ckeditor/filemanager/connectors/php/upload.php?Type=Image',filebrowserFlashUploadUrl:'".$pathtovsadmin."/ckeditor/filemanager/connectors/php/upload.php?Type=Flash'});\r\n";
		print "theemailfck.on('instanceReady',function(event){var myToolbar='Basic';event.editor.on( 'beforeMaximize', function(){if(event.editor.getCommand('maximize').state==CKEDITOR.TRISTATE_ON && myToolbar != 'Basic'){theemailfck.setToolbar('Basic');myToolbar='Basic';theemailfck.execCommand('toolbarCollapse');}else if(event.editor.getCommand('maximize').state==CKEDITOR.TRISTATE_OFF && myToolbar != 'Full'){theemailfck.setToolbar('Full');myToolbar='Full';theemailfck.execCommand('toolbarCollapse');}});event.editor.on('contentDom', function(e){event.editor.document.on('blur', function(){if(!theemailfck.isToolbarCollapsed){theemailfck.execCommand('toolbarCollapse');theemailfck.isToolbarCollapsed=true;}});event.editor.document.on('focus',function(){if(theemailfck.isToolbarCollapsed){theemailfck.execCommand('toolbarCollapse');theemailfck.isToolbarCollapsed=false;}});});theemailfck.fire('contentDom');theemailfck.isToolbarCollapsed=true;});\r\n";
		print '</script>';
	}elseif(@$htmleditor=='froala'){
		displayfroalaeditor('theemailfck',$yyMessag,'',TRUE,FALSE,1,TRUE);
	}
}elseif(getpost('posted')=='1' && (getpost('act')=='modify' || getpost('act')=='addnew')){
?>
<script>
<!--
function formvalidator(theForm){
if (theForm.email.value==""){
alert("<?php print jscheck($yyPlsEntr . ' "' . $yyEmail)?>\".");
theForm.email.focus();
return(false);
}
return(true);
}
//-->
</script>
<?php
		if(getpost('act')=='modify'){
			$email=getpost('id');
			$sSQL="SELECT isconfirmed,mlConfirmDate,mlIPAddress,mlName FROM mailinglist WHERE email='" . escape_string($email) . "'";
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)){
				$dateadded=$rs['mlConfirmDate'];
				$ipaddress=$rs['mlIPAddress'];
				$mlname=$rs['mlName'];
			}
			ect_free_result($result);
		}else{
			$email='';
			$mlname='';
		}
?>
      <table border="0" cellspacing="0" cellpadding="0" width="100%" align="center">
        <tr>
		  <td width="100%" align="center">
		  <form name="mainform" method="post" action="adminmailinglist.php" onsubmit="return formvalidator(this)">
<?php		writehiddenvar('posted', '1');
			if(getpost('act')=='modify') writehiddenvar('act', 'domodify'); else writehiddenvar('act', 'doaddnew');
			hiddenparams(); ?>
            <table width="100%" border="0" cellspacing="2" cellpadding="2">
			  <tr>
                <td width="100%" colspan="2" align="center" height="34"><strong><?php print $yyMaLiMa;
			if(getpost('act')=='modify') print ' - ' . htmlspecials(getpost('id'))?></strong></td>
			  </tr>
			  <tr>
				<td align="right" height="34"><strong><?php print $yyName?>:</strong></td>
				<td align="left"><input type="text" name="mlname" size="34" value="<?php print htmlspecials($mlname)?>"></td>
			  </tr>
			  <tr>
				<td align="right" height="34"><strong><?php print $yyEmail?>:</strong></td>
				<td align="left"><input type="text" name="email" size="34" value="<?php print htmlspecials($email)?>"></td>
			  </tr>
<?php	if(getpost('act')=='modify'){ ?>
			  <tr>
				<td align="right" height="34"><strong><?php print $yyDateAd?>:</strong></td>
				<td align="left"><?php print $dateadded?></td>
			  </tr>
			  <tr>
				<td align="right" height="34"><strong><?php print $yyIPAdd?>:</strong></td>
				<td align="left"><?php print $ipaddress?></td>
			  </tr>
<?php	} ?>
			  <tr>
                <td width="100%" colspan="2" align="center" height="34"><br><input type="submit" value="<?php print $yySubmit?>">&nbsp;<input type="reset" value="<?php print $yyReset?>"><br>&nbsp;</td>
			  </tr>
			  <tr>
                <td width="100%" colspan="2" align="center" height="34"><br>
                          <a href="admin.php"><strong><?php print $yyAdmHom?></strong></a><br>
                          &nbsp;</td>
			  </tr>
            </table>
		  </form>
		  </td>
        </tr>
      </table>
<?php
}elseif(getpost('posted')=='1' && getpost('act')!='confirm' && $success){ ?>
      <table border="0" cellspacing="0" cellpadding="0" width="100%" align="center">
        <tr>
          <td width="100%">
			<table width="100%" border="0" cellspacing="0" cellpadding="2">
			  <tr> 
                <td width="100%" colspan="2" align="center"><br><strong><?php print $yyUpdSuc?></strong><br><br><?php print $yyNowFrd?><br><br>
                        <?php print $yyNoAuto?> <a href="adminmailinglist.php"><strong><?php print $yyClkHer?></strong></a>.<br>
                        <br><br>&nbsp;
                </td>
			  </tr>
			</table></td>
        </tr>
      </table>
<?php
}elseif(getpost('posted')=='1' && getpost('act')!='confirm'){ ?>
      <table border="0" cellspacing="0" cellpadding="0" width="100%" align="center">
        <tr>
          <td width="100%">
			<table width="100%" border="0" cellspacing="0" cellpadding="2">
			  <tr> 
                <td width="100%" colspan="2" align="center"><br><span style="color:#FF0000;font-weight:bold"><?php print $yyOpFai?></span><br><br><?php print $errmsg?><br><br>
				<a href="javascript:history.go(-1)"><strong><?php print $yyClkBac?></strong></a></td>
			  </tr>
			</table></td>
        </tr>
      </table>
<?php
}else{
	$sSQL='SELECT count(*) AS thecount FROM mailinglist';
	if(@$noconfirmationemail!=TRUE) $sSQL.=' WHERE isconfirmed<>0';
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)) $numemails=$rs['thecount']; else $numemails=0;
	ect_free_result($result);
	$sSQL='SELECT count(*) AS thecount FROM mailinglist WHERE emailsent<>0';
	$result=ect_query($sSQL) or ect_error();
	if($rs=ect_fetch_assoc($result)) $numsentemails=$rs['thecount']; else $numsentemails=0;
	ect_free_result($result);
	$ordstate=@$_REQUEST['ordstate'];
	if(! is_array($ordstate)){
		if($ordstate!='') $ordstate=explode(',',$ordstate);
	}
	$ordcountry=@$_REQUEST['ordcountry'];
	if(! is_array($ordcountry)){
		if($ordcountry!='') $ordcountry=explode(',',$ordcountry);
	}
	$smanufacturer=@$_REQUEST['smanufacturer'];
	if(! is_array($smanufacturer)){
		if($smanufacturer!='') $smanufacturer=explode(',',$smanufacturer);
	}
	$thecat=@$_REQUEST['scat'];
	if(! is_array($thecat)){
		if($thecat!='') $thecat=explode(',',$thecat);
	}
	$stext=getrequest('stext');
	$stype=getrequest('stype');
	$stsearch=getrequest('stsearch');
	$swholesale=getrequest('swholesale');
	$sortorder=getrequest('sort');
	$mlact=getrequest('mlact');
?>
<script src="popcalendar.js"></script>
<script>
<!--
try{languagetext('<?php print @$adminlang?>');}catch(err){}
function mrec(id) {
	document.mainform.action="adminmailinglist.php";
	document.mainform.id.value=id;
	document.mainform.act.value="modify";
	document.mainform.posted.value="1";
	document.mainform.submit();
}
function crec(id) {
	document.mainform.action="adminmailinglist.php";
	document.mainform.id.value=id;
	document.mainform.act.value="confirm";
	document.mainform.posted.value="1";
	document.mainform.submit();
}
function newrec(id) {
	document.mainform.action="adminmailinglist.php";
	document.mainform.id.value=id;
	document.mainform.act.value="addnew";
	document.mainform.posted.value="1";
	document.mainform.submit();
}
function sendem(id) {
	document.mainform.action="adminmailinglist.php";
	document.mainform.act.value="sendem";
	document.mainform.posted.value="1";
	document.mainform.submit();
}
function mailchimp(id) {
	document.mainform.action="adminmailinglist.php";
	document.mainform.act.value="mailchimp";
	document.mainform.posted.value="1";
	document.mainform.submit();
}
function drec(id){
if(confirm("<?php print jscheck($yyConDel)?>\n")){
	document.mainform.action="adminmailinglist.php";
	document.mainform.id.value=id;
	document.mainform.act.value="delete";
	document.mainform.posted.value="1";
	document.mainform.submit();
}
}
function startsearch(){
	document.mainform.action="adminmailinglist.php";
	document.mainform.act.value="search";
	document.mainform.listem.value="";
	document.mainform.posted.value="";
	document.mainform.submit();
}
function listem(thelet){
	document.mainform.action="adminmailinglist.php";
	document.mainform.act.value="search";
	document.mainform.listem.value=thelet;
	document.mainform.posted.value="";
	document.mainform.submit();
}
function removeuncon(){
if(confirm("<?php print jscheck($yyConDel)?>\n")){
	document.mainform.action="adminmailinglist.php";
	document.mainform.act.value="purgeunconfirmed";
	document.mainform.posted.value="1";
	document.mainform.submit();
}
}
function clearsent(){
if(confirm("<?php print jscheck($yySureCa)?>")) {
	document.mainform.action="adminmailinglist.php";
	document.mainform.act.value="clearsent";
	document.mainform.posted.value="1";
	document.mainform.submit();
}
}
function checkact(tmen){
	tact=tmen[tmen.selectedIndex].value;
	if(tact=='CSL') clearsent();
	if(tact=='ROU') removeuncon();
	if(tact=='DUS'){
		document.mainform.action="dumporders.php";
		document.mainform.act.value="dumpemails";
		document.mainform.submit();
	}else if(tact=='DUE'){
		document.mainform.action="dumporders.php?entirelist=1";
		document.mainform.act.value="dumpemails";
		document.mainform.submit();
	}else if(tact=='CEN'){
		if(confirm('This will search the orders database for any empty "Name" fields. Continue?')){
			document.mainform.action="adminmailinglist.php";
			document.mainform.act.value="checkemptyname";
			document.mainform.posted.value="1";
			document.mainform.submit();
		}
	}
	tmen.selectedIndex=0;
}
function changesortorder(men){
	var thesort=men[men.selectedIndex].value;
	document.mainform.action="adminmailinglist.php<?php if(getpost('act')=='search' || getrequest('pg')!='') print '?pg=1&'; else print '?'?>sort="+thesort;
	document.mainform.act.value="search";
	document.mainform.listem.value="";
	document.mainform.posted.value="";
	document.mainform.submit();
}
function changepract(obj){
	startsearch("search");
}
function quickupdate(){
	if(document.mainform.mlact.value=="del"){
		if(!confirm("<?php print jscheck($yyConDel)?>\n"))
			return;
	}
	document.mainform.action="adminmailinglist.php";
	document.mainform.act.value="quickupdate";
	document.mainform.posted.value="1";
	document.mainform.listem.value="";
	document.mainform.submit();
}
function checkboxes(docheck){
	maxitems=document.getElementById("resultcounter").value;
	for(index=0;index<maxitems;index++){
		var thiselem=document.getElementById("chkbx"+index);
		if(thiselem.checked!=docheck){
			thiselem.checked=docheck;
			thiselem.onchange();
		}
	}
}
// -->
</script>
		  <form name="mainform" method="post" action="adminmailinglist.php">
			<input type="hidden" name="posted" value="1">
			<input type="hidden" name="act" value="xxxxx">
			<input type="hidden" name="listem" value="<?php print @$_REQUEST['listem']?>">
			<input type="hidden" name="id" value="xxxxx">
			<input type="hidden" name="pg" value="<?php print (getpost('act')=='search' ? '1' : getrequest('pg'))?>">
			<table class="cobtbl" width="100%" border="0" cellspacing="1" cellpadding="3">
			  <tr>
				<td class="cobhl" colspan="4" align="center"><strong><?php
					print $numemails . ' ' . 'Emails - ';
					print '<a href="javascript:listem(\'#\')">#</a> ';
					for($index=0; $index < 26; $index++){
						print '<a href="javascript:listem(\'' . chr(65+$index) . '\')">' . chr(65+$index) . '</a> ';
					}
				?></strong></td>
			  </tr>
			  <tr> 
				<td class="cobhl" width="25%" align="right"><select name="stsearch" size="1">
					<option value="srchemail"><?php print $yySrchFr.': '.$yyEmail?></option>
					<option value="srchprodid"<?php if($stsearch=="srchprodid") print ' selected'?>><?php print $yySrchFr.': '.$yyPrId?></option>
					<option value="srchprodname"<?php if($stsearch=="srchprodname") print ' selected'?>><?php print $yySrchFr.': '.$yyPrName?></option>
					<option value="srchordersmore"<?php if($stsearch=="srchordersmore") print ' selected'?>><?php print $yySrchFr.': Spent &gt; $$$'?></option>
					<option value="srchordersless"<?php if($stsearch=="srchordersless") print ' selected'?>><?php print $yySrchFr.': Spent &lt; $$$'?></option>
					<option value="srchorderslesszero"<?php if($stsearch=="srchorderslesszero") print ' selected'?>><?php print $yySrchFr.': Spent &lt; $$$ OR &empty;'?></option>
					</select></td>
				<td class="cobll"><input type="text" name="stext" size="20" value="<?php print htmlspecials($stext)?>">
					<select name="stype" size="1">
					<option value=""><?php print $yySrchAl?></option>
					<option value="any"<?php if($stype=="any") print ' selected'?>><?php print $yySrchAn?></option>
					<option value="exact"<?php if($stype=="exact") print ' selected'?>><?php print $yySrchEx?></option>
					</select>
				</td>
				<td class="cobhl" align="right"><select name="swholesale" size="1" style="float:left">
					<option value=""><?php print $yyAll?></option>
					<option value="wholesale"<?php if($swholesale=="wholesale") print ' selected'?>><?php print $yyWholes?></option>
					<option value="nonwholesale"<?php if($swholesale=="nonwholesale") print ' selected'?>><?php print $yyNoWhol?></option>
					</select><p style="margin-top:4px"><?php print $yyDatRan?>:</p></td>
				<td class="cobll"><div style="position:relative;display:inline"><input type="text" name="mindate" size="10" value="<?php print @$_REQUEST['mindate']?>" style="vertical-align:middle">&nbsp;<input type="button" onclick="popUpCalendar(this, document.forms.mainform.mindate, '<?php print $themask?>', -205)" value="DP">&nbsp;<?php print $yyTo?>:&nbsp;<input type="text" name="maxdate" size="10" value="<?php print @$_REQUEST['maxdate']?>" style="vertical-align:middle">&nbsp;<input type="button" onclick="popUpCalendar(this, document.forms.mainform.maxdate, '<?php print $themask?>', -205)" value="DP"></div></td>
			  </tr>
			  <tr>
				<td class="cobhl" width="25%" align="center"><strong><?php print $yySection?></strong>&nbsp;&nbsp;<input type="checkbox" name="notsection" value="ON" <?php if(getpost('notsection')=="ON") print 'checked="checked"'?>/><strong>...<?php print $yyNot?></strong></td>
				<td class="cobhl" width="25%" align="center"><strong><?php print $yyManuf?></strong>&nbsp;&nbsp;<input type="checkbox" name="notmanufacturer" value="ON" <?php if(getpost('notmanufacturer')=="ON") print 'checked="checked"'?>/><strong>...<?php print $yyNot?></strong></td>
				<td class="cobhl" width="25%" align="center"><strong><?php print $yyState?></strong>&nbsp;&nbsp;<input type="checkbox" name="notstate" value="ON" <?php if(getpost('notstate')=="ON") print 'checked="checked"'?>/><strong>...<?php print $yyNot?></strong></td>
				<td class="cobhl" width="25%" align="center"><strong><?php print $yyCountry?></strong>&nbsp;&nbsp;<input type="checkbox" name="notcountry" value="ON" <?php if(getpost('notcountry')=="ON") print 'checked="checked"'?>/><strong>...<?php print $yyNot?></strong></td>
			  </tr>
			  <tr>
				<td class="cobll" align="center"><select name="scat[]" size="5" multiple="multiple" style="max-width:400px"><?php
						$sSQL="SELECT sectionID,sectionWorkingName,topSection,rootSection FROM sections " . (@$adminonlysubcats==TRUE ? "WHERE rootSection=1 ORDER BY sectionWorkingName" : "ORDER BY sectionOrder");
						$allcats=ect_query($sSQL) or ect_error();
						$lasttsid=-1;
						$numcats=0;
						while($row=ect_fetch_assoc($allcats))
							$allcatsa[$numcats++]=$row;
						ect_free_result($allcats);
						if($numcats > 0){
							if(@$adminonlysubcats==TRUE){
								for($index=0;$index<$numcats;$index++){
									print '<option value="' . $allcatsa[$index]['sectionID'] . '"';
									if(is_array($thecat)){
										foreach($thecat as $catid){
											if($allcatsa[$index]['sectionID']==$catid) print ' selected="selected"';
										}
									}
									print '>' . $allcatsa[$index]['sectionWorkingName'] . "</option>\n";
								}
							}else
								writemenulevel(0,1);
						} ?>
					  </select></td>
				<td class="cobll" align="center"><select name="smanufacturer[]" size="5" multiple="multiple"><?php
						$sSQL='SELECT scID,scName FROM searchcriteria WHERE scGroup=0 ORDER BY scName';
						$result=ect_query($sSQL) or ect_error();
						while($rs=ect_fetch_assoc($result)){
							print '<option value="' . htmlspecials($rs['scID']) . '"';
							if(is_array($smanufacturer)){
								foreach($smanufacturer as $objValue){
									if($objValue==$rs['scID']) print ' selected="selected"';
								}
							}
							print '>' . $rs['scName'] . "</option>\n";
						}
						ect_free_result($result); ?></select></td>
				<td class="cobll" align="center"><select name="ordstate[]" size="5" multiple="multiple"><?php
						$sSQL="SELECT stateID,stateName,stateAbbrev FROM states WHERE stateEnabled=1 AND stateCountryID=" . $origCountryID . " 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="selected"';
								}
							}
							print '>' . $rs['stateName'] . "</option>\n";
						}
						ect_free_result($result); ?></select></td>
				<td class="cobll" align="center"><select name="ordcountry[]" size="5" multiple="multiple"><?php
						$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="selected"';
								}
							}
							print '>' . $rs['countryName'] . "</option>\n";
						}
						ect_free_result($result); ?></select></td>
			  </tr>
			  <tr>
				<td class="cobhl" align="center"><select onchange="checkact(this)">
						<option value=""><?php print $yyAct?>...</option>
						<option value="CSL">Clear &quot;Sent&quot; List<?php if($numsentemails!=0) print ' ('.$numsentemails.')'?></option>
<?php
	$mlcount=0;
	$sSQL="SELECT COUNT(*) AS mlcount FROM mailinglist WHERE isConfirmed=0 AND mlConfirmDate<'".date('Y-m-d', time()-($mailinglistpurgedays*60*60*24))."'";
	$result=ect_query($sSQL) or print_sql_error();
	if($rs=ect_fetch_assoc($result)){
		if(! is_null($rs['mlcount'])) $mlcount=$rs['mlcount'];
	}
	ect_free_result($result);
	if($mlcount > 0) print '<option value="ROU">Remove Old Unconfirmed ('.$mlcount.')</option>' ?>
						<option value="DUS">Dump <?php print $yySelEm?></option>
						<option value="DUE">Dump <?php print $yyEntML?></option>
						<option value="CEN">Patch Empty Name Fields from Orders</option>
						</select>
<?php				if($mlact=='del'){ ?>
					<div style="margin-top:2px"><input type="button" value="<?php print $yyCheckA?>" onclick="checkboxes(true);"> <input type="button" value="<?php print $yyUCheck?>" onclick="checkboxes(false);"></div>
<?php				} ?>
						</td>
				<td class="cobll" colspan="3" align="center">
						<select name="sort" size="1" onchange="changesortorder(this)">
						<option value="naa"<?php if($sortorder=='naa') print ' selected="selected"'?>>Sort - Name ASC</option>
						<option value="nad"<?php if($sortorder=='nad') print ' selected="selected"'?>>Sort - Name DESC</option>
						<option value=""<?php if($sortorder=='') print ' selected="selected"'?>>Sort - Email ASC</option>
						<option value="emd"<?php if($sortorder=='emd') print ' selected="selected"'?>>Sort - Email DESC</option>
						<option value="daa"<?php if($sortorder=='daa') print ' selected="selected"'?>>Sort - Date ASC</option>
						<option value="dad"<?php if($sortorder=='dad') print ' selected="selected"'?>>Sort - Date DESC</option>
						<option value="coa"<?php if($sortorder=='coa') print ' selected="selected"'?>>Sort - Confirmed ASC</option>
						<option value="cod"<?php if($sortorder=='cod') print ' selected="selected"'?>>Sort - Confirmed DESC</option>
						<option value="nsf"<?php if($sortorder=='nsf') print ' selected="selected"'?>>No Sort (Fastest)</option>
						</select>
						<input type="button" value="<?php print $yyListRe?>" onclick="startsearch()"> &nbsp;
						<input type="button" value="Add Email" onclick="newrec()">
						<input type="button" value="Send Emails To List" onclick="sendem()">
						<input type="button" value="Mailchimp Integration" onclick="mailchimp()">
				</td>
			  </tr>
			</table>
<br>
            <table width="100%" class="stackable admin-table-a sta-white">
<?php
	$jscript=$qetype=$errortext='';
	if(getpost('act')=='search' || getrequest('pg')!='' || getpost('act')=='confirm'){
		function displayprodrow($xrs){
			global $yyModify,$yyDelete,$bgcolor,$noconfirmationemail,$yyConfrm,$resultcounter,$jscript,$qetype,$mlact;
			$jscript.='pa['.$resultcounter.']=[';
?><tr class="<?php print $bgcolor?>" id="tr<?php print $resultcounter?>">
<td><?php	print '-';
			if($mlact=='del'){
				$jscript.="'del'";
				$qetype='delbox';
			}else
				print '-';
		?></td>
<td><?php print htmlspecials($xrs['mlName']) ?>&nbsp;</td><td></td><td><?php print htmlspecials($xrs['mlConfirmDate']) ?></td>
<td class="minicell"><?php if(@$noconfirmationemail!=TRUE && $xrs['isconfirmed']==0) print '<input type="button" value="'.$yyConfrm.'" onclick="crec(\''.str_replace(array("'",'"'),array("\'",'&quot;'),$xrs['email']).'\')">'; else print '&nbsp;'?></td>
<td class="minicell"><input type="button" value="<?php print $yyModify?>" onclick="mrec('<?php print jsspecials($xrs['email'])?>')"></td>
<td class="minicell"><input type="button" value="<?php print $yyDelete?>" onclick="drec('<?php print jsspecials($xrs['email'])?>')"></td></tr>
<?php		$jscript.=",'".jsspecials($xrs['email'])."'];\r\n";
			$resultcounter++;
		}
		function displayheaderrow(){
			global $yyName,$yyEmail,$yyModify,$yyDelete,$noconfirmationemail,$yyConfrm,$mlact; ?>
			<tr>
				<th><select name="mlact" id="mlact" size="1" onchange="changepract(this)" style="width:150px">
					<option value="none">Quick Entry...</option>
					<option value="" disabled="disabled">---------------------</option>
					<option value="del"<?php if($mlact=='del') print ' selected="selected"'?>><?php print $yyDelete?></option>
					</select></th>
				<th class="maincell"><?php print $yyName?></th>
				<th class="maincell"><?php print $yyEmail?></th>
				<th class="maincell">Date</th>
				<th class="minicell"><?php if(@$noconfirmationemail!=TRUE) print $yyConfrm; else print '&nbsp;'?></th>
				<th class="minicell"><?php print $yyModify?></th>
				<th class="minicell"><?php print $yyDelete?></th>
			</tr>
<?php	}
		$rowcounter=0;
		$ordersjoined=FALSE;
		$sSQL='SELECT DISTINCT email FROM mailinglist ';
		if(($stext!='' && ($stsearch=='srchprodid' || $stsearch=='srchprodname' || $stsearch=='srchordersless' || $stsearch=='srchorderslesszero' || $stsearch=='srchordersmore')) || $thecat!='' || $smanufacturer!='' || $ordstate!='' || $ordcountry!=''){
			$sSQL.=($stsearch=='srchorderslesszero'?'LEFT':'INNER') . ' JOIN orders ON mailinglist.email=orders.ordEmail ' . ($stsearch=='srchprodid' || $stsearch=='srchprodname' ? 'INNER JOIN cart ON orders.ordID=cart.cartOrderID INNER JOIN products ON cart.cartProdID=products.pId ' : '');
			$ordersjoined=TRUE;
		}
		$whereand='WHERE';
		if(getrequest('listem')!=''){
			if(@$_REQUEST['listem']=='#')
				$sSQL.="WHERE (email < 'A') ";
			else
				$sSQL.="WHERE (email LIKE '" . escape_string(@$_REQUEST['listem']) . "%') ";
			$whereand='AND';
		}elseif($stext!=''){
			if(!($stsearch=='srchordersless' || $stsearch=='srchorderslesszero' || $stsearch=='srchordersmore')){
				$sText=escape_string($stext);
				$aText=explode(',', $sText);
				$arrelms=count($aText);
				if($stype=="exact"){
					$sSQL.=$whereand . " (email LIKE '%" . $sText . "%') ";
					$whereand='AND';
				}else{
					if($stype=="any") $sJoin="OR "; else $sJoin="AND ";
					$sSQL.=$whereand . ' (';
					$whereand='AND';
					foreach($aText as $theopt){
						if(is_array($theopt))$theopt=$theopt[0];
						if($stsearch=='srchemail'||$stsearch=='') $sSQL.="email ";
						if($stsearch=='srchprodid') $sSQL.="cartProdId ";
						if($stsearch=='srchprodname') $sSQL.="cartProdName ";
						$sSQL.=" LIKE '%" . $theopt . "%' ";
						if(++$rowcounter < $arrelms) $sSQL.=$sJoin;
					}
					$sSQL.=') ';
				}
			}
		}
		if(is_array($thecat)){
			$sectionids=getsectionids(implode(',',$thecat), TRUE);
			if($sectionids!=''){
				$sSQL.= $whereand . ' ' . (getpost('notsection')=='ON'?'NOT ':'') . "(products.pSection IN (" . $sectionids . ")) ";
				$whereand='AND';
			}
		}
		if(is_array($smanufacturer)){
			$sSQL.= $whereand . ' ' . (getpost('notmanufacturer')=='ON'?'NOT ':'') . "(products.pManufacturer IN (" . implode(',',$smanufacturer) . ")) ";
			$whereand='AND';
		}
		if(is_array($ordstate)){
			$sSQL.= $whereand . ' ' . (getpost('notstate')=='ON'?'NOT ':'') . "(ordState IN ('" . implode("','", $ordstate) . "')) ";
			$whereand='AND';
		}
		if(is_array($ordcountry)){
			$sSQL.= $whereand . ' ' . (getpost('notcountry')=='ON'?'NOT ':'') . "(ordCountry IN ('" . implode("','",$ordcountry) . "')) ";
			$whereand='AND';
		}
		$mindate=getrequest('mindate');
		$maxdate=getrequest('maxdate');
		if($mindate!='' || $maxdate!=''){
			if($mindate!='') $themindate=parsedate($mindate); else $themindate='';
			if($maxdate!='') $themaxdate=parsedate($maxdate); else $themaxdate='';
			if($themindate!='' && $themaxdate!=''){
				$sSQL.=$whereand . " " . ($ordersjoined?'ordDate':'mlConfirmDate') . " BETWEEN '" . date('Y-m-d', $themindate) . "' AND '" . date('Y-m-d', $themaxdate) . "'";
				$whereand=" AND ";
			}elseif($themindate!=''){
				$sSQL.=$whereand . " " . ($ordersjoined?'ordDate':'mlConfirmDate') . " >= '" . date('Y-m-d', $themindate) . "'";
				$whereand=" AND ";
			}elseif($themaxdate!=''){
				$sSQL.=$whereand . " " . ($ordersjoined?'ordDate':'mlConfirmDate') . " <= '" . date('Y-m-d', $themaxdate) . "'";
				$whereand=" AND ";
			}
		}
		
		if($stsearch=='srchordersless' || $stsearch=='srchorderslesszero' || $stsearch=='srchordersmore'){
			if(is_numeric($stext)){
				$sSQL.=" GROUP BY(email) HAVING (SUM(ordTotal)" . ($stsearch=='srchordersmore'?'>=':'<=') . $stext . ($stsearch=='srchorderslesszero'?' OR SUM(ordTotal) IS NULL':'') . ") ";
				$whereand=" AND ";
			}else
				$errortext='Amount must be numeric';
		}
		
		// print $sSQL."<br>";
		
		if($whereand=='WHERE'){
			$sSQL='SELECT email,mlName,isconfirmed,mlConfirmDate FROM mailinglist';
			ect_query("UPDATE mailinglist SET selected=1") or ect_error();
		}else{
			ect_query("UPDATE mailinglist SET selected=0") or ect_error();
			$result=ect_query($sSQL) or ect_error();
			while($rs=ect_fetch_assoc($result)){
				ect_query("UPDATE mailinglist SET selected=1 WHERE email='" . escape_string($rs['email']) . "'") or ect_error();
			}
			ect_free_result($result);
		}
		if($swholesale=='nonwholesale'){
			$sSQL="SELECT DISTINCT email FROM mailinglist LEFT JOIN customerlogin ON mailinglist.email=customerlogin.clEmail WHERE selected<>0 AND (clActions&8)=8";
			$result=ect_query($sSQL) or ect_error();
			while($rs=ect_fetch_assoc($result)){
				ect_query("UPDATE mailinglist SET selected=0 WHERE email='" . escape_string($rs['email']) . "'") or ect_error();
			}
			ect_free_result($result);
		}elseif($swholesale=='wholesale'){
			$sSQL="SELECT DISTINCT email FROM mailinglist LEFT JOIN customerlogin ON mailinglist.email=customerlogin.clEmail WHERE selected<>0 AND ((clActions&8)<>8 OR clActions IS NULL)";
			$result=ect_query($sSQL) or ect_error();
			while($rs=ect_fetch_assoc($result)){
				ect_query("UPDATE mailinglist SET selected=0 WHERE email='" . escape_string($rs['email']) . "'") or ect_error();
			}
			ect_free_result($result);
		}
		
		if($errortext!=''){
			print '<tr><td width="100%" colspan="6" style="color:#F00;text-align:center"><br>' . $errortext . '<br>&nbsp;</td></tr>';
		}else{
			$sSQL='SELECT count(*) AS thecount FROM mailinglist WHERE isconfirmed<>0 AND selected<>0';
			$result=ect_query($sSQL) or ect_error();
			if($rs=ect_fetch_assoc($result)) $numselectedemails=$rs['thecount']; else $numselectedemails=0;
			ect_free_result($result);
			if($numselectedemails!=0){ ?>
			<div style="text-align:center;margin:10px"><?php print $numselectedemails?> Selected from search</div>
<?php		}

			$thesort=' ORDER BY email';
			if($sortorder=='emd') $thesort=' ORDER BY email DESC';
			if($sortorder=='naa') $thesort=' ORDER BY mlName';
			if($sortorder=='nad') $thesort=' ORDER BY mlName DESC';
			if($sortorder=='daa') $thesort=' ORDER BY mlConfirmDate';
			if($sortorder=='dad') $thesort=' ORDER BY mlConfirmDate DESC';
			if($sortorder=='coa') $thesort=' ORDER BY isconfirmed,email';
			if($sortorder=='cod') $thesort=' ORDER BY isconfirmed DESC,email';
			if($sortorder=='nsf') $thesort='';
			$sSQL='SELECT DISTINCT email,mlName,isconfirmed,mlConfirmDate FROM mailinglist WHERE selected<>0' . $thesort;
			if(! @is_numeric(getrequest('pg')))
				$CurPage=1;
			else
				$CurPage=(int)getrequest('pg');
			if(@$adminemailsperpage=='') $adminemailsperpage=200;
			$result=ect_query($sSQL) or ect_error();
			if(ect_num_rows($result)>0) $iNumOfPages=ceil(ect_num_rows($result)/$adminemailsperpage); else $iNumOfPages=0;
			ect_free_result($result);
			$sSQL.=' LIMIT ' . ($adminemailsperpage*($CurPage-1)) . ', ' . $adminemailsperpage;
			$result=ect_query($sSQL) or ect_error();
			if(ect_num_rows($result) > 0){
				$ordstatearr='';
				if(is_array($ordstate)){
					$ordstatearr=implode(',',$ordstate);
				}
				$ordcountryarr='';
				if(is_array($ordcountry)){
					$ordcountryarr=implode(',',$ordcountry);
				}
				$smanufacturerarr='';
				if(is_array($smanufacturer)){
					$smanufacturerarr=implode(',',$smanufacturer);
				}
				$thecatarr='';
				if(is_array($thecat)){
					$thecatarr=implode(',',$thecat);
				}
				$pblink='<a href="adminmailinglist.php?stext=' . urlencode($stext) . '&stype=' . $stype . '&ordstate=' . urlencode($ordstatearr) . '&ordcountry=' . urlencode($ordcountryarr) . '&smanufacturer=' . urlencode($smanufacturerarr) . '&scat=' . urlencode($thecatarr) . '&stsearch=' . urlencode($stsearch) . '&swholesale=' . urlencode($swholesale) . '&mindate=' . $mindate . '&maxdate=' . $maxdate . '&pg=';
				if($iNumOfPages > 1) print '<tr><td colspan="6" align="center">' . writepagebar($CurPage,$iNumOfPages,$yyPrev,$yyNext,$pblink,FALSE) . '</td></tr>';
				displayheaderrow();
				while($rs=ect_fetch_assoc($result)){
					if(@$bgcolor=='altdark') $bgcolor='altlight'; else $bgcolor='altdark';
					displayprodrow($rs);
				}
				if($iNumOfPages > 1) print '<tr><td colspan="6" align="center">' . writepagebar($CurPage,$iNumOfPages,$yyPrev,$yyNext,$pblink,FALSE) . '</td></tr>';
			}else{
				print '<tr><td width="100%" colspan="6" align="center"><br>' . $yyItNone . '<br>&nbsp;</td></tr>';
			}
			ect_free_result($result);
		}
	}else{
		$selectedunsent=0;
		$sSQL="SELECT COUNT(*) AS selectedunsent FROM mailinglist WHERE selected<>0 AND emailsent=0";
		if(@$noconfirmationemail!=TRUE) $sSQL.= ' AND isconfirmed<>0';
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result)) $selectedunsent=$rs['selectedunsent']; else $selectedunsent=0;
		ect_free_result($result);
		if($selectedunsent!=0){ ?>
			<tr><td width="100%" colspan="6" align="center"><br><?php print $selectedunsent?> Unsent from previous search<br>&nbsp;</td></tr>
<?php	}
		$numitems=0;
		$sSQL='SELECT COUNT(*) as totcount FROM mailinglist';
		$result=ect_query($sSQL) or ect_error();
		if($rs=ect_fetch_assoc($result))
		$numitems=$rs['totcount'];
		print '<tr><td colspan="6"><div class="itemsdefine">You have ' . $numitems . ' mailing list entries.</div></td></tr>';
	}
	if($resultcounter>0 && $mlact!='' && $mlact!='none'){ ?>
			  <tr>
				<td align="center" style="white-space:nowrap"><?php print '<input type="hidden" name="resultcounter" id="resultcounter" value="'.$resultcounter.'"><input type="button" value="'.$yyUpdate.'" onclick="quickupdate()"> <input type="reset" value="'.$yyReset.'">';?></td>
                <td colspan="6">&nbsp;</td>
			  </tr>
<?php
	} ?>
            </table>
			<div style="text-align:center;margin:20px"><a href="admin.php"><strong><?php print $yyAdmHom?></strong></a></div>
		  </form>
<script>
var pa=[];
<?php
	print $jscript?>
	function patch_pid(pid){
		document.getElementById('pid'+pid).name='pid'+pid;
		document.getElementById('pid'+pid).value=pa[pid][1];
		return pid;
	}
	for(var pidind in pa){
		var ttr=document.getElementById('tr'+pidind);
		ttr.cells[0].className='minicell';
		//ttr.cells[3].style.textAlign=ttr.cells[4].style.textAlign=ttr.cells[5].style.textAlign=ttr.cells[6].style.textAlign='center';
		ttr.cells[2].innerHTML='<input type="hidden" id="pid'+pidind+'" value="">'+pa[pidind][1];
		ttr.cells[0].innerHTML=
<?php		if($qetype=="delbox"){ ?>
	'<input type="checkbox" id="chkbx'+pidind+'" onchange="this.name=\'pra_'+patch_pid(pidind)+'\'" value="del" tabindex="'+(pidind+1)+'">';
<?php		}else{ ?>
	'&nbsp;';
<?php		} ?>
	}
</script>
<?php
}
?>
