<?php
/*
Plugin Name:[GWA] AutoResponder Pro
Plugin URI: http://FreeAutoresponder.biz
Description:A plugin to add an Double Opt-In Auto-Responder and (multi) List Builder to your Wordpress Weblog.
Version: 4.2.1 Pro (GBK/JIS)
Author: G.J.P.
Author URI: http://Code4Cookies.com
*/
/*
    4.2 Professional v4
    - Full double opt-in email confirmation.
    - Intelligent Queue - sendmail management.
    - Manage MULTIPLE mailing lists.
    - Reach your WordPress Users by their roles.
*/
/*
    Copyright 2009-2011 GetWebActive  (email : cookies@getwebactive.com)
    Released under license from GetWebActive
    Use of this plugin is governed by the software licence included in the package. 
    Contact the author if there is no licence in your package.
    *THIS IS NOT FREE SOFTWARE* 
    *All rights reserved* 

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
$export_separator = "\t"; $gwa_version_tag = '4.2.1'; $ar_gwa_debug = get_option('ar_gwa_debug');
if(!($ar_gwa_enc2 = get_option('ar_gwa_enc'))) { $ar_gwa_enc2 = '8bit'; update_option('ar_gwa_enc',$ar_gwa_enc2); }if(!($ar_gwa_enc = get_option('ar_gwa_char'))) $ar_gwa_enc = 'UTF-8'; if (version_compare(PHP_VERSION, '5.0.0', '<') ) $phpmailerDir = 'PHP4'; else $phpmailerDir = 'PHP5'; 
function ar_gwa_js_admin_header() {
global $postem;
echo $postem; 
wp_print_scripts( array( 'sack' ));?>
<script type="text/javascript">
 //<![CDATA[
 function ar_gwa_name_update( name_field, id_field, email_field )
 {
  var mysack = new sack( 
       "<?php bloginfo( 'wpurl' ); ?>/wp-admin/admin-ajax.php" );    
  mysack.execute = 1;
  mysack.method = 'POST';
  mysack.setVar( "action", "ar_gwa_name_update" );
  mysack.setVar( "lID", id_field );
  mysack.setVar( "lName", name_field.value );
  mysack.setVar( "lEmail", email_field );
  mysack.encVar( "cookie", document.cookie, false );
  mysack.onError = function() { alert(__('Ajax error updating record','argwa'))};
  mysack.runAJAX();
  return true;
}

 function ar_gwa_email_update( email_field, id_field )
 {
  var mysack = new sack( 
       "<?php bloginfo( 'wpurl' ); ?>/wp-admin/admin-ajax.php" );    
  mysack.execute = 1;
  mysack.method = 'POST';
  mysack.setVar( "action", "ar_gwa_email_update" );
  mysack.setVar( "lID", id_field );
  mysack.setVar( "lEmail", email_field.value );
  mysack.encVar( "cookie", document.cookie, false );
  mysack.onError = function() { alert(__('Ajax error updating record','argwa'))};
  mysack.runAJAX();
  return true;
  }

 function ar_gwa_day_update( day_field, id_field, email_field )
 {
  var mysack = new sack( 
       "<?php bloginfo( 'wpurl' ); ?>/wp-admin/admin-ajax.php" );    
  mysack.execute = 1;
  mysack.method = 'POST';
  mysack.setVar( "action", "ar_gwa_day_update" );
  mysack.setVar( "lID", id_field );
  mysack.setVar( "lEmail", email_field );
  mysack.setVar( "lMOut", day_field.value );
  mysack.encVar( "cookie", document.cookie, false );
  mysack.onError = function() { alert(__('Ajax error updating record','argwa'))};
  mysack.runAJAX();
  return true;
  }

 function ar_gwa_fields_update( id_field, field_one, field_two, field_three, field_four, field_five )
 {
  var mysack = new sack( 
       "<?php bloginfo( 'wpurl' ); ?>/wp-admin/admin-ajax.php" );    
  mysack.execute = 1;
  mysack.method = 'POST';
  mysack.setVar( "action", "ar_gwa_fields_update" );
  mysack.setVar( "lID", id_field );
  mysack.setVar( "field_1", field_one.value );
  mysack.setVar( "field_2", field_two.value );
  mysack.setVar( "field_3", field_three.value );
  mysack.setVar( "field_4", field_four.value );
  mysack.setVar( "field_5", field_five.value );
  mysack.encVar( "cookie", document.cookie, false );
  mysack.onError = function() { alert(__('Ajax error updating record','argwa'))};
  mysack.runAJAX();
  return true;
  }
  //]]>
</script>
<?php
if(file_exists(ABSPATH.'wp-content/plugins/autoresponder-gwa/gwa-xinha.txt')){
echo file_get_contents(ABSPATH.'wp-content/plugins/autoresponder-gwa/gwa-xinha.txt');
}
}
add_action('admin_print_scripts', 'ar_gwa_js_admin_header' );
add_action('wp_ajax_ar_gwa_name_update', 'ar_gwa_name_update' );
add_action('wp_ajax_ar_gwa_email_update', 'ar_gwa_email_update' );
add_action('wp_ajax_ar_gwa_day_update', 'ar_gwa_day_update' );
add_action('wp_ajax_ar_gwa_fields_update', 'ar_gwa_fields_update' );

$l = file_exists(ABSPATH."/wp-content/plugins/GWASplash/GWASplash.php");
if((!$_COOKIE["GWAPOPX"] || isset($_COOKIE["GWAADMINPOP"]))){
 add_action('wp_print_scripts','ar_gwa_dyn_header');
 add_action('wp_footer','ar_gwa_dyn_footer');
}

function ar_gwa_dyn_footer() {
if(get_option('ar_gwa_footerlist'))
echo '<div id="triqui_ad"></div>';
}
function ar_gwa_dyn_header() {
$listid = get_option('ar_gwa_footer_list');
if(get_option('ar_gwa_footerlist')) {
?>
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
	<script type="text/javascript">
	jQuery.noConflict();
	jQuery(function(){
		jQuery.ajaxSetup({cache:false});
		jQuery('#triqui_ad').wrap('<div id="triqui_container"></div>');
		jQuery('#triqui_ad').load('?ar_gwa_subscription_form=<?php echo get_option('ar_gwa_footer_list');?>',function(){
			jQuery('#triqui_ad').css('display','block');
			jQuery('#triqui_container').hide().slideDown('slow');
			jQuery('#triqui_ad').append(' <span style="float:right"><a title="Close" id="triqui_ad_close"><img src="<?php echo WP_PLUGIN_URL;?>/autoresponder-gwa/close1.jpg" alt="close" align="top" border="0" / alt="Close"></a></span>');
			jQuery('#triqui_ad_close').click(function(){ 
	   			jQuery('#triqui_container').slideUp('slow'); 
	  		}); 
		}); 
	});
	</script>
<style type="text/css">
	#triqui_container {
	width: 100%;
	position: fixed;
	bottom: 0; left: 0;
}
 
#triqui_ad{
 color: <?php echo get_option('ar_gwa_sldfg'.'_'.$listid);?>;
	background-color: <?php echo get_option('ar_gwa_sldbkg'.'_'.$listid);?>;
	border-top: <?php echo get_option('ar_gwa_sborder'.'_'.$listid);?>px solid <?php echo get_option('ar_gwa_sldbor'.'_'.$listid);?>;
	height: <?php echo get_option('ar_gwa_sldht'.'_'.$listid);?>px;
	text-align:center;
	display:none;
}
 
#triqui_ad_close {
	background-color: <?php echo get_option('ar_gwa_sldbkg'.'_'.$listid);?>;
	cursor: pointer;
}
</style>
<?php
}}
//
function ar_gwa_popin() {
echo '<script type="text/javascript" src="'.WP_PLUGIN_URL.'/autoresponder-gwa/flyh.js"></script>';

if(file_exists(ABSPATH.'wp-content/plugins/autoresponder-gwa/fly.css')) 
echo '<link rel="stylesheet" href="'.WP_PLUGIN_URL.'/autoresponder-gwa/fly.css" type="text/css" media="screen">';
else echo '<style type="text/css">
#flyad {color:'.get_option('ar_gwa_popfg_'.get_option('ar_gwa_popin_list')).';background-color:'.get_option('ar_gwa_popbkg_'.get_option('ar_gwa_popin_list')).';border:'.get_option('ar_gwa_border_'.get_option('ar_gwa_popin_list')).'px solid '.get_option('ar_gwa_popbor_'.get_option('ar_gwa_popin_list')).';
z-Index:999;visibility:hidden;position:absolute;top:300px;left:200px;width:'.get_option('ar_gwa_wwidth_'.get_option('ar_gwa_popin_list')).'px;height:'.get_option('ar_gwa_wheight_'.get_option('ar_gwa_popin_list')).'text-align:center}
#flyad a {color: '.get_option('ar_gwa_popfg_'.get_option('ar_gwa_popin_list')).';}
#fa1 {text-align:right;background-color:'.get_option('ar_gwa_popbkg_'.get_option('ar_gwa_popin_list')).';}

</style>';
}

function print_ar_gwa_popin() {
echo '<div id="flyad"><div id="fa1"><a href="#" onclick="moveback()"><img src="'.WP_PLUGIN_URL.'/autoresponder-gwa/close1.jpg" alt="close" align="top" border="0" /></a></div><div id="fa2">';
echo is_autoresponder_gwa_popin_display(get_option('ar_gwa_popin_list'));
echo '</div></div>';
}

if((is_admin()) & (isset($_REQUEST['popintest'])))  { setcookie("GWAADMINPOP", "1", 0 ,"/"); $_COOKIE["GWAADMINPOP"]=1;} else if((is_admin()) & (isset($_REQUEST['poptest']))) { setcookie("GWAADMINPOP", false, 0 ,"/"); unset($_COOKIE["GWAADMINPOP"]);}
if((!$_COOKIE["GWAPOP"] || isset($_COOKIE["GWAADMINPOP"]))) {
 if((get_option('ar_gwa_popin')=='checked' || isset($_COOKIE["GWAADMINPOP"])) && (!is_admin())){
    if(!(get_option('ar_gwa_footerlist'))) {
     add_action('wp_print_scripts','ar_gwa_popin');
     add_action('loop_end','print_ar_gwa_popin');
    }
  setcookie("GWAPOP", "1", 0, "/");
 }
}

function ar_gwa_name_update() {
global $wpdb;
$qry = 'UPDATE `'.$wpdb->prefix.'ar_gwa_leads` SET lName = "'.$wpdb->escape($_POST['lName']).'" WHERE lID="'.$wpdb->escape($_POST['lID']).'"';
$z = $wpdb->query($qry);
$val = '<input  onblur="sss = confirm(\''.__("Confirm changes to",'argwa')."&nbsp;".$_POST['lEmail'].'?\');if(sss==true)ar_gwa_name_update(document.getElementById(\'argwaleadname'.$_POST['lID'].'\'),'.$_POST['lID'].',\''.$_POST['lEmail'].'\');return false;" type="text" name="lLead" id="argwaleadname'.$_POST['lID'].'" value="'.$_POST['lName'].'" size="22">';

die("document.getElementById('tdname".$_POST['lID']."').innerHTML = '".addslashes($val)."'
alert('".__("Changes saved to database.",'argwa')."')");
}

function ar_gwa_email_update() {
global $wpdb;
$qry = 'UPDATE `'.$wpdb->prefix.'ar_gwa_leads` SET lEmail = "'.$wpdb->escape($_POST['lEmail']).'" WHERE lID="'.$wpdb->escape($_POST['lID']).'"';
$z = $wpdb->query($qry);
$val = '<input  onblur="sss = confirm(\''.__("Confirm changes to",'argwa')."&nbsp;".$_POST['lEmail'].'?\');if(sss==true)ar_gwa_email_update(document.getElementById(\'argwaleademail'.$_POST['lID'].'\'),'.$_POST['lID'].');return false;" type="text" name="lEmail" id="argwaleademail'.$_POST['lID'].'" value="'.$_POST['lEmail'].'" size="22">';

die("document.getElementById('tdemail".$_POST['lID']."').innerHTML = '".addslashes($val)."'
alert('".__("Changes saved to database.",'argwa')."')");
}

function ar_gwa_day_update() {
global $wpdb;
if(preg_match("/^\d+$/",$_POST['lMOut'])) {
$qry = 'UPDATE `'.$wpdb->prefix.'ar_gwa_leads` SET lMOut = "'.$wpdb->escape($_POST['lMOut']).'" , lDateEntry = "'.date('Y-m-d', strtotime('-'.($_POST['lMOut']+1).' days')).'" WHERE lID="'.$wpdb->escape($_POST['lID']).'"';
$z = $wpdb->query($qry);
$val = '<input  onblur="sss = confirm(\''.__("Confirm changes to",'argwa')."&nbsp;".$_POST['lEmail'].'?\');if(sss==true)ar_gwa_day_update(document.getElementById(\'argwaleadday'.$_POST['lID'].'\'),'.$_POST['lID'].',\''.$_POST['lEmail'].'\');return false;" type="text" name="lMOut" id="argwaleadday'.$_POST['lID'].'" value="'.$_POST['lMOut'].'" size="3">';

die("document.getElementById('tdday".$_POST['lID']."').innerHTML = '".addslashes($val)."'
document.getElementById('tdentry".$_POST['lID']."').innerHTML = '".date('Y-m-d', strtotime('-'.($_POST['lMOut']+1).' days'))."'
alert('".__("Changes saved to database.",'argwa')."')");
} else {
die("alert('".__("Please enter a valid Msg Day Number 0-999 only.",'argwa')."')");
}
}

function ar_gwa_fields_update() {
global $wpdb;
#$wpdb->show_errors();
$qry = 'UPDATE '.$wpdb->prefix.'ar_gwa_leads SET lField1 = "'.$wpdb->escape($_POST['field_1']).'" , lField2 = "'.$wpdb->escape($_POST['field_2']).'", lField3 = "'.$wpdb->escape($_POST['field_3']).'", lField4 = "'.$wpdb->escape($_POST['field_4']).'", lField5 = "'.$wpdb->escape($_POST['field_5']).'" WHERE lID="'.$wpdb->escape($_POST['lID']).'"';
$z = $wpdb->query($qry);

die("document.getElementById('gwatable".$_POST['lID']."').innerHTML = '".__("Updated",'argwa')."&nbsp;".$z."'");

}

function ar_gwa_unsub_page($uID,$lEmail,$step=NULL) {
global $wpdb;
	$qry = "SELECT lLID FROM ".$wpdb->prefix."ar_gwa_leads WHERE lEmail LIKE '%".$lEmail."%' AND lID='".$uID."'";
	$listid = $wpdb->get_var($qry);

if(!$listid) {
  $qry = "SELECT lEmail FROM ".$wpdb->prefix."ar_gwa_leads WHERE lID='".$uID."'";
	$listemail = $wpdb->get_var($qry);
  if($lEmail == preg_replace("/@/",$listemail))
	$qry = "SELECT lLID FROM ".$wpdb->prefix."ar_gwa_leads WHERE lID='".$uID."' AND lEmail='".$l."'";
	$listid = $wpdb->get_var($qry);
}

if($listid>0) $wpdb->query("DELETE FROM ".$wpdb->prefix."ar_gwa_leads WHERE  lID='".$uID."'");


  $mssg = '<span style="color:#f00;font-weight:bolder;">'.stripslashes(stripslashes(stripslashes($mssg))).'</span>';
  function autoresponder_output($in=null,$out=null) {
  global $mssg;
  echo $in.$mssg.$out;
  }
  function is_autoresponder_output($in=null,$out=null) {
  global $mssg;
  return $in.$mssg.$out;
  }
  $rpag = get_option('ar_gwa_unsub_'.$listid);
  if(!$rpag) $rpag = $wpdb->get_var("SELECT xReturn FROM ".$wpdb->prefix."  ar_gwa_lists LIMIT 1");
  if(!preg_match("/^http/i",$rpag)) {
  query_posts($query_string."&page_id=$rpag");
  } else {
  header("Location:".$rpag);
  }  
}

function ar_gwa_signup() {
global $wpdb,$mssg,$list_name,$rpag,$query_string,$phpmailerDir,$ar_gwa_enc,$ar_gwa_enc2;

if(!class_exists('ar_gwa_single') && file_exists(dirname(__FILE__).'/ar_gwa_single.php')) include_once(dirname(__FILE__).'/ar_gwa_single.php');
if(isset($_REQUEST['argwaknn']) && strlen($_REQUEST['argwaknn'])==10) {
if(class_exists('ar_gwa_single')) {
$optin = new ar_gwa_single();
$listid = $_REQUEST['listid'];
$sff = $optin->catchLead($_REQUEST['argwaknn']);
if(!$_REQUEST['act']) {
echo $sff;exit;
} else {
$rpag = get_option('ar_gwa_confirm_'.$listid);
if(!$rpag) $rpag = $wpdb->get_var("SELECT xReturn FROM ".$wpdb->prefix."ar_gwa_lists WHERE xID='$listid'");
$mssg = '<span id="argwa_output">'.get_option('ar_gwa_addlead').'</span>';
$mssg = stripslashes(stripslashes(stripslashes($mssg)));
function autoresponder_output($in=null,$out=null) {
global $mssg;
echo $in.$mssg.$out;
}
function is_autoresponder_output($in=null,$out=null) {
global $mssg;
return $in.$mssg.$out;
}
 if(!preg_match("/^http/i",$rpag)) {
 query_posts($query_string."&page_id=$rpag");
 } else {
 header("Location:".$rpag);
 exit;
 }
#return;
}
}
}
if(isset($_GET['gwatk']) && preg_match("/^\d+$/",$_GET['gwatk'])) {
$trk = new ar_gwa_track();
$trk->redirectLink($_GET['gwatk']);
exit;
}
if(isset($_REQUEST['ar_gwa_subscription_form']) && $fnum = $_REQUEST['ar_gwa_subscription_form']) {
  if(!$_COOKIE["GWAPOPX"] || isset($_COOKIE["GWAADMINPOP"])){
setcookie("GWAPOPX", "1", 0, "/");
echo is_autoresponder_gwa_slide_display($fnum);
exit;
  }
exit;
}
if(isset($_REQUEST['listid']) && ($listid = $_REQUEST['listid']))
if(!$rpag) $rpag = $wpdb->get_var("SELECT xReturn FROM ".$wpdb->prefix."ar_gwa_lists WHERE xID='$listid'");
$trx = new ar_gwa_internationalized();
if(!$mssg) $mssg = '<strong style="color:#ff0000">'.$trx->gwa_intn('problem').' ('.get_bloginfo('admin_email').')</strong>';

if(!class_exists('ar_gwa_user_edit') && file_exists(dirname(__FILE__).'/ar_gwa_user_edit.php')) include_once(dirname(__FILE__).'/ar_gwa_user_edit.php');

// SECIND IF
if(isset($_GET['argwa_uID']) && !(isset($_REQUEST['argwa_UPD']))&& (isset($_POST['ar_gwa_vid']))) {
$uce = new ar_gwa_user_edit($_GET['argwa_uID']);
$uce->unsubscribe($_POST['ar_gwa_vid']);
 $msg = '<span id="argwa_output" style="color:#f00;text-decoration:underline;">'.__('Confirm your unsubscribe request. Look in your email and click the link.','argwa').'</span>';
   $mssg = $uce->display_confirm_page($msg);
} else 
if(isset($_GET['D'])) {
 $ucd = new ar_gwa_user_edit();
  $uID = $ucd->unsub_email(($_GET['D']));
 $ucd->uID = $uID;
 $msg = '<span style="color:green;text-decoration:underline;">'.__('Unsubscribe confirmed.','argwa').'</span>';
   $mssg = $ucd->display_confirm_page($msg);
} else 
if($_REQUEST['argwa_UPD']!='') {
if(isset($_REQUEST['argwa_uID'])){
 $uID = $_REQUEST['argwa_uID'];
$ucd = new ar_gwa_user_edit($uID);
  $ucd->update_user($_POST['ar_gwa_uid'],$_POST['ar_gwa_name'],$_POST['ar_gwa_email']);
 $msg = '<span id="argwa_output" style="color:#f00;text-decoration:underline;">'.__('Confirm your changes. Look in your email and click the link.','argwa').'</span>';
   $mssg = $ucd->display_confirm_page($msg);
}} else
if(isset($_GET['C'])) {
 $ucd = new ar_gwa_user_edit();
 $uID = $ucd->update_email(($_GET['C']));
 $ucd->uID = $uID;
 $msg = '<span style="color:green;text-decoration:underline;">'.__('Changes confirmed.','argwa').'</span>';
   $mssg = $ucd->display_confirm_page($msg);
} 
// FIRST IF
if((isset($_REQUEST['argwa_uID']) && ($uID = $_REQUEST['argwa_uID'])) || (isset($uID) && $uID>0) ) {
     $qry = $wpdb->get_results("SELECT lID,xReturn,xID FROM ".$wpdb->prefix."ar_gwa_leads, ".$wpdb->prefix."ar_gwa_lists WHERE xID=lLID AND lID='$uID'");
    if(isset($qry[0]->lID) && $qry[0]->lID>0)
      $rpag = get_option('ar_gwa_ui_'.$qry[0]->xID);
    if(!$rpag)
      $rpag = $qry[0]->xReturn;      
if(!class_exists('ar_gwa_user_edit') && file_exists(dirname(__FILE__).'/ar_gwa_user_edit.php')) include_once(dirname(__FILE__).'/ar_gwa_user_edit.php');
if(class_exists('ar_gwa_user_edit')) {
$ucc = new ar_gwa_user_edit($uID);
  if(isset($_GET['argwa_uID'])) {
   $mssg = $ucc->display_page($msg);
  }
}  
function autoresponder_output($in=null,$out=null) {
global $mssg;
echo $in.$mssg.$out;
}
function is_autoresponder_output($in=null,$out=null) {
global $mssg;
return $in.$mssg.$out;
}

if(!$rpag) 
 $rpag = $wpdb->get_var("SELECT xReturn FROM ".$wpdb->prefix."ar_gwa_lists LIMIT 1");
 if(!preg_match("/^http/i",$rpag)) {
 query_posts($query_string."&page_id=$rpag");
 } else {
 header("Location:".$rpag);
 exit;
 }  
} else if (isset($_REQUEST['r']) && ($r = substr($_REQUEST['r'],0,21))) {
    $qry = $wpdb->get_results("SELECT lID,lLID,lEmail, xReturn,xID FROM ".$wpdb->prefix."ar_gwa_leads, ".$wpdb->prefix."ar_gwa_lists WHERE xID=lLID AND lCnf='$r'");
    if(isset($qry[0]->lID) && $qry[0]->lID>0)  {
      $rpag = get_option('ar_gwa_confirm_'.$qry[0]->xID);
    if(!$rpag)
      $rpag = $qry[0]->xReturn;      
    $dt = date('Y-m-d H:i:s');
    $ip = $_SERVER['REMOTE_ADDR'];
    $dns = gethostbyaddr($ip);
	  if(!$wpdb->query("UPDATE ".$wpdb->prefix."ar_gwa_leads SET lCnf='1',lTime='$dt',lIP='$ip',lDNS='$dns' WHERE lID='".$qry[0]->lID."'")) { 
    $mssg = '<span id="argwa_output">'.get_option('ar_gwa_badlead').'</span>';
    } else {
    if((get_option('ar_gwa_drop_'.$qry[0]->lLID)=='checked')) {
    $wpdb->show_errors();
     if((get_option('ar_gwa_remove_'.$qry[0]->lLID)!='checked')) {
     $wpdb->query("UPDATE ".$wpdb->prefix."ar_gwa_leads SET lCnf='2' WHERE lEmail = '".$qry[0]->lEmail."' AND lID !='".$qry[0]->lID."'");
     } else {
     $wpdb->query("DELETE FROM ".$wpdb->prefix."ar_gwa_leads WHERE lEmail = '".$qry[0]->lEmail."' AND lID !='".$qry[0]->lID."'");
     }
    }
    $ms = new MailProcess();
    if( $ms->setLead($qry[0]->lID) && $ms->setMsg(0,$qry[0]->xID))
	    $ms->mailLead(0,$qry[0]->lID);
     $mssg = '<span id="argwa_output">'.get_option('ar_gwa_addlead').'</span>';
     if(get_option('ar_gwa_notify_'.$qry[0]->xID)=='checked'){
     $mto = get_bloginfo('admin_email')."\r\n";
     $mfrom = $ms->lead['lEmail'];
     $msubj = $trx->gwa_intn('newsub')."\r\n";
     $mmsg = $ms->lead['xName'] . ' : '. $ms->lead['lName'].' ('.$ms->lead['lEmail'].') : '.$dns. ' : ( '.$ip.' ) : '.$dt."\r\n\r\n";
     $fld = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."ar_gwa_leads WHERE lID ='".$qry[0]->lID."'");
     if($fld[0]->lField1!='')
     $mmsg .= __("Field",'argwa')." 1: {$fld[0]->lField1}\r\n";
     if($fld[0]->lField2!='')
     $mmsg .= __("Field",'argwa')." 2: {$fld[0]->lField2}\r\n";
     if($fld[0]->lField3!='')
     $mmsg .= __("Field",'argwa')." 3: {$fld[0]->lField3}\r\n";
     if($fld[0]->lField4!='')
     $mmsg .= __("Field",'argwa')." 4: {$fld[0]->lField4}\r\n";
     if($fld[0]->lField5!='')
     $mmsg .= __("Field",'argwa')." 5: {$fld[0]->lField5}\r\n";
 		  if(get_option('ar_gwa_smtp_auth')!='checked') {
$sc = mail($mto,$msubj,nl2br($mmsg)."\r\n","From: $mfrom <{$mfrom}>"."\r\n"."Mime-Version: 1.0\nContent-Type: text/plain; charset=$ar_gwa_enc\nContent-Transfer-Encoding: $ar_gwa_enc2\n",'-f'.$mfrom);
#      $sc = mail($mto,$msubj,$mmsg,"From: $mfrom"."\r\n"."Mime-Version: 1.0\r\nContent-Type: text/plain; charset=$ar_gwa_enc\r\nContent-Transfer-Encoding: $ar_gwa_enc2\r\n",'-f'.$mfrom);
      if(!$sc) mail($mto,$msubj,nl2br($mmsg)."\r\n","From: $mfrom <{$mfrom}>"."\r\n"."Mime-Version: 1.0\nContent-Type: text/plain; charset=$ar_gwa_enc\nContent-Transfer-Encoding: $ar_gwa_enc2\n");
      } else {
      $mail['method']='smtp';
      $mail['SMTPAuth']=true;
      $mail['Host'] = get_option('ar_gwa_smtp_srv');
      $mail['Username'] = get_option('ar_gwa_smtp_user');
      $mail['Password'] = get_option('ar_gwa_smtp_pass');
      $mail['From'] = $mfrom;
      $mail['FromName'] = $mfrom;
      $mail['recepientMail'] = $mto;
      $mail['recepientName'] = $mto;
      $mail['subject'] = $msubj;
      $mail['body'] = $mmsg;
      $mails[] = $mail;
      if (! class_exists('PHPMailer'))
       include($phpmailerDir.'/class.phpmailer.php');    
      $newsletter = new newsletter;
      $suc = $newsletter->SendMail($mails);    
      }
     }
    }
  setcookie("GWAPOP", "1", (time()+(60*60*24*365)), "/");
  } else {
  $mssg = '<span id="argwa_output">'.get_option('ar_gwa_badlead').'</span>';
  }
$mssg = stripslashes(stripslashes(stripslashes($mssg)));
function autoresponder_output($in=null,$out=null) {
global $mssg;
echo $in.$mssg.$out;
}
function is_autoresponder_output($in=null,$out=null) {
global $mssg;
return $in.$mssg.$out;
}
if(!$rpag) 
 $rpag = $wpdb->get_var("SELECT xReturn FROM ".$wpdb->prefix."ar_gwa_lists LIMIT 1");
 if(!preg_match("/^http/i",$rpag)) {
 query_posts($query_string."&page_id=$rpag");
 } else {
 header("Location:".$rpag);
 exit;
 }
} else if (($_REQUEST['act']=='s_add')) {    
    $dt = date('Y-m-d H:i:s');
    $ip = $_SERVER['REMOTE_ADDR'];
    $dns = gethostbyaddr($ip);
    if(isset($_REQUEST['gwaname'])) $lName = $wpdb->escape($_REQUEST['gwaname']); else $lName = $wpdb->escape($_REQUEST['name']);    
    if(isset($_REQUEST['gwaemail'])) $lEmail = $wpdb->escape($_REQUEST['gwaemail']); else $lEmail = $wpdb->escape($_REQUEST['email']);    
    $i_url = get_bloginfo('url').'/index.php';
    $lField1 = mysql_real_escape_string($_REQUEST['Field1']);
    $lField2 = mysql_real_escape_string($_REQUEST['Field2']);
    $lField3 = mysql_real_escape_string($_REQUEST['Field3']);
    $lField4 = mysql_real_escape_string($_REQUEST['Field4']);
    $lField5 = mysql_real_escape_string($_REQUEST['Field5']);
    
if(isset($listid) && $listid>0)
$cpt = get_option('ar_gwa_captcha_'.$listid);
if($cpt == "checked" & (($_REQUEST['uword']=="") && ($_REQUEST['udword']=="")))
$mssg = '<span id="argwa_output">'.__('CAPTCHA Human Verification FAILED! Please try subscribing again!','argwa').'</span>';    
else if(ar_gwa_check_email($lEmail) && (isset($listid) && $listid>0)){
  global $wpdb;
  #$wpdb->show_errors;
	$qry = "SELECT * FROM ".$wpdb->prefix."ar_gwa_leads WHERE lEmail='".$lEmail."' AND lLID='".$listid."' AND lCnf=1";
	$qry2 = "SELECT * FROM ".$wpdb->prefix."ar_gwa_leads WHERE lEmail='".$lEmail."' AND lLID='".$listid."' AND lCnf!=1";
	if($wpdb->get_results($qry)) { 
  $mssg = '<span id="argwa_output">'.$trx->gwa_intn('exists').'</span>';
	} else if($wpdb->get_results($qry2)) { 
	$qry = "DELETE FROM ".$wpdb->prefix."ar_gwa_leads WHERE lEmail='".$lEmail."' AND lLID='".$listid."' AND lCnf != 1";
  if($wpdb->query($qry))
  $mssg = '<span id="argwa_output">'.$trx->gwa_intn('prev_conf').'</span>';  
  } else
	{	
  $pword='ar';
  $vals = "ABCDEFGHIJKLMNOPQRSTUVWXYZabchefghjkmnpqrstuvwxyz0123456789";           
  while (strlen($pword) < 21) {
                mt_getrandmax();  // Returns the maximum value that can be returned by a call  rand
                $num = rand(1,strlen($vals));
                $tmp = substr($vals, $num+4, 1);
                $pword = $pword . $tmp;
                $tmp ="";
  }
    $lCnf = $pword;
    $to = "$lEmail\r\n";
    $from = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix."ar_gwa_lists WHERE xID='$listid'");
    $subj = html_entity_decode(sprintf($trx->gwa_intn('conf_subj'),$from->xName)."\r\n",ENT_NOQUOTES,'UTF-8');
    $msg = sprintf($trx->gwa_intn('conf_subj'),$from->xName)."\r\n";
    $msg .= "\r\n".$trx->gwa_intn('click_here')."-> ".$i_url."?r=$lCnf\r\n\r\n";
    $msg .= sprintf($trx->gwa_intn('signup_detail'),$ip,$dns,$dt);
    $msg .= sprintf($trx->gwa_intn('disclaimer'),get_bloginfo('url'));
    $nicename = $from->xName;
    if(get_option('ar_gwa_smtp_auth')!='checked') {
    if($wwrap = get_option('ar_gwa_wrap')) $msg = wordwrap($msg,$wwrap,"\r\n");
    $suc = mail($to,$subj,$msg."\r\n","from: {$from->xEmail}"."\r\n"."Mime-Version: 1.0\nContent-Type: text/plain; charset=$ar_gwa_enc\nContent-Transfer-Encoding: $ar_gwa_enc2\n",'-f'.$from->xEmail);
#    $suc = mail($to,$subj,$msg,"From: $nicename <{$from->xEmail}>"."\r\n"."Mime-Version: 1.0\r\nContent-Type: text/plain; charset=$ar_gwa_enc\r\nContent-Transfer-Encoding: $ar_gwa_enc2\r\n",'-f'.$from->xEmail);
        if (!$suc) $suc = mail($to,$subj,$msg."\r\n","from: {$from->xEmail}"."\r\n"."Mime-Version: 1.0\nContent-Type: text/plain; charset=$ar_gwa_enc\nContent-Transfer-Encoding: $ar_gwa_enc2\n");
    } else {
    $mail['method']='smtp';
    $mail['SMTPAuth']=true;
    $mail['Host'] = get_option('ar_gwa_smtp_srv');
    $mail['Username'] = get_option('ar_gwa_smtp_user');
    $mail['Password'] = get_option('ar_gwa_smtp_pass');
    $mail['From'] = $from->xEmail;
    $mail['FromName'] = $nicename;
    $mail['recepientMail'] = $to;
    $mail['recepientName'] = $to;
    $mail['subject'] = $subj;
    $mail['body'] = $msg;
    $mails[] = $mail;
    if (! class_exists('PHPMailer'))
      include($phpmailerDir.'/class.phpmailer.php');    
    $newsletter = new newsletter;
    $suc = $newsletter->SendMail($mails);    
    }
    if(!$suc) {
      $mssg = '<span id="argwa_output">'.sprintf($trx->gwa_intn('conf_error'),get_bloginfo('admin_email')).'</span> ';
    } else {
		$qry = "INSERT INTO ".$wpdb->prefix."ar_gwa_leads(lLID, lName, lEmail, lDateEntry, lDateOut, lMOut, lCnf,lIP,lDNS, lField1, lField2, lField3, lField4, lField5) VALUES('".$listid."','".$lName."', '".$lEmail."' ,current_date, current_date, '-1','".$lCnf."','','','".$lField1."','".$lField2."','".$lField3."','".$lField4."','".$lField5."')";
		$wpdb->query($qry);    
      $mssg = '<span id="argwa_output">'.sprintf($trx->gwa_intn('conf_success'),$from->xEmail).'</span>';
    }
  } // if check email
 } // if act = s_add
if(!$rpag) $rpag = $wpdb->get_var("SELECT xReturn FROM ".$wpdb->prefix."ar_gwa_lists WHERE xID=".$listid);
if(isset($_REQUEST['argwaknn']) && isset($sff)) $mssg = '<span id="argwa_output">'.get_option('ar_gwa_addlead').'</span>';
$mssg = stripslashes(stripslashes(stripslashes($mssg)));

if(!function_exists('autoresponder_output')) {
function autoresponder_output($in=null,$out=null) {
global $mssg;
echo $in.$mssg.$out;
}
}
if(!function_exists('is_autoresponder_output')){
function is_autoresponder_output($in=null,$out=null) {
global $mssg;
return $in.$mssg.$out;
}
}

if(!$rpag) $rpag = $wpdb->get_var("SELECT xReturn FROM ".$wpdb->prefix."ar_gwa_lists LIMIT 1");
if(!preg_match("/^http/i",$rpag)) {
$query_string = "page_id=$rpag";
query_posts($query_string);
} else {
header("Location:".$rpag);
exit;
#query_posts($query_string);
}
} else if (isset($_REQUEST['aID']) && preg_match("/^\d+$/",$_REQUEST['aID'])) {
  $lEmail = $wpdb->escape($_REQUEST['Email']);
  $urec = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."ar_gwa_leads WHERE lID={$_REQUEST['aID']}",ARRAY_A);
  $lrec = $wpdb->get_results("SELECT xName,xLabel FROM ".$wpdb->prefix."ar_gwa_lists WHERE xID={$urec[0]['lLID']}");
  $channels=Array(
	$lrec[0]->xLabel,
	get_bloginfo('url'),
	$lrec[0]->xName.__(" Archives for",'argwa')."&nbsp;".$urec[0]['lName'],
	"SELECT `mSubject`,`mBody`,`mDay`,`mLID` FROM `".$wpdb->prefix."ar_gwa_msg` WHERE mLID = {$urec[0]['lLID']} AND mDay <= {$urec[0]['lMOut']} ORDER by mDay DESC");
#print_r($urec);exit;
#header ("Content-type: text/xml");
archive($channels,$urec[0]); // create RSS content
exit;
} else if((isset($_REQUEST['argwa_mid']) && preg_match("/^\d+$/",$_REQUEST['argwa_mid'])) && (isset($_REQUEST['argwa_lid']) && preg_match("/^\d+$/",$_REQUEST['argwa_lid'])) && (isset($_REQUEST['argwa_uid']) && preg_match("/^\d+$/",$_REQUEST['argwa_uid']))) {

get_header();
echo '<div style="width:90%;margin-left:50px;">';
$rft = $wpdb->get_results("SELECT mSubject,mBody FROM ".$wpdb->prefix."ar_gwa_msg WHERE mDay=".$_REQUEST['argwa_mid']." AND mLID=".$_REQUEST['argwa_lid']);
$lead = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix."ar_gwa_leads WHERE lID=".$_REQUEST['argwa_uid'],ARRAY_A);
$msg1['mType'] = $msg2['mType'] = 'html'; 
$msg1['mSubject'] = $rft[0]->mSubject;
$msg2['mBody'] = $rft[0]->mBody;
$mSubj = formatMsg($lead,$msg1);
$mBody = formatMsg($lead,$msg2);

echo "<h2 style='font-size:13pt'>".$mSubj."</h2><br><span style='font-size:12pt'>";

 $mBody = preg_replace("/\<\?\w+\?\>/",'',$mBody);
 $mBody = preg_replace("/\&lt;\?\w+\?\&gt;/",'',$mBody);
echo $mBody;
echo '</span></div>';
get_footer();
exit;
} else if (isset($_REQUEST['uID']) && preg_match("/^\d+$/",$_REQUEST['uID'])) {
//
  #$wpdb->show_errors;

  $lEmail = $wpdb->escape($_REQUEST['Email']);
  $uID = $_REQUEST['uID'];

	$qry = "SELECT lLID FROM ".$wpdb->prefix."ar_gwa_leads WHERE lEmail LIKE '%".$lEmail."%' AND lID='".$uID."'";
	$listid = $wpdb->get_var($qry);

if(!$listid) {
	$qry = "SELECT lLID FROM ".$wpdb->prefix."ar_gwa_leads WHERE lID='".$uID."'";
	$listid = $wpdb->get_var($qry);
}
	if($listid>0) {
  $qry = "SELECT xName FROM ".$wpdb->prefix."ar_gwa_lists WHERE xID=$listid";
	$list_name = $wpdb->get_var($qry);
  }

if(get_option("ar_gwa_remove_".$listid)=="checked")
  $qry = "DELETE FROM ".$wpdb->prefix."ar_gwa_leads WHERE lID='".$uID."'";
else
  $qry = "UPDATE ".$wpdb->prefix."ar_gwa_leads SET lCnf='2' WHERE lID='".$uID."'";
  if($wpdb->query($qry)) {
    $mssg = get_option('ar_gwa_rmvlead');
  } else {
	$qry = "SELECT lEmail FROM ".$wpdb->prefix."ar_gwa_leads WHERE lID='".$uID."'";
	$tEmail = $wpdb->get_var($qry);  
  $t_Email = preg_replace("/@/",'',str_replace("\r\n", "", trim($tEmail)));
  $l_Email = preg_replace("/@/",'',$lEmail);
   if(preg_match("/$t_Email/", $l_Email)) {
    $qry = "DELETE FROM ".$wpdb->prefix."ar_gwa_leads WHERE lID='".$uID."' AND lEmail like '%".$tEmail."%'";
     if($wpdb->query($qry)) {
      $mssg = get_option('ar_gwa_rmvlead');
     }  
    }
  } 
$mssg = '<span id="argwa_output">'.stripslashes(stripslashes(stripslashes($mssg))).'</span>';
function autoresponder_output($in=null,$out=null) {
global $mssg;
echo $in.$mssg.$out;
}
function is_autoresponder_output($in=null,$out=null) {
global $mssg;
return $in.$mssg.$out;
}

$rpag = get_option('ar_gwa_unsub_'.$listid);
if(!$rpag) $rpag = $wpdb->get_var("SELECT xReturn FROM ".$wpdb->prefix."ar_gwa_lists LIMIT 1");
 if(!preg_match("/^http/i",$rpag)) {
 query_posts($query_string."&page_id=$rpag");
 } else {
 header("Location:".$rpag);
 exit;
 }
}

if(!function_exists('is_autoresponder_output')) {
function is_autoresponder_output($in=null,$out=null,$listid=null) {
global $wpdb;
if(!isset($listid) && isset($_REQUEST['page_id']))
$listid = $wpdb->get_var("SELECT xID FROM ".$wpdb->prefix."ar_gwa_lists WHERE xPage=".$_REQUEST['page_id']);
else if($listid==0)
$listid = $wpdb->get_var("SELECT MIN(xID) FROM ".$wpdb->prefix."ar_gwa_lists");
if($listid>0)
  return is_autoresponder_gwa_form_display($listid);
}
}
}

if(!function_exists('ar_gwa_short_code')) {
  function ar_gwa_short_code($atts) {
  $ats = shortcode_atts( array('listid' => 0), $atts );
    if(function_exists('is_autoresponder_output')) return is_autoresponder_output(null,null,$atts['listid']);
    else return ix_autoresponder_output();
  }
}

	function formatMsg($lead,$msg)
	{
		$archivelink = get_bloginfo('url').'/index.php?aID='.$lead['lID'] . '&Email='.htmlentities($lead['lEmail']);
		$affiliate = 'http://www.freeautoresponder.biz/?/'.get_option('ar_gwa_aff');
    $affiliate_text = "Wordpress Newsletter Manager\n".$affiliate;
		$ar_gwa_no_spam = get_option('ar_gwa_no_spam');
    if($ar_gwa_no_spam=='checked'){
		$ar_gwa_nospam_text = "\r\n\r\n".get_option('ar_gwa_nospam');    
    } else {
		$ar_gwa_nospam_text = "\r\n\r\n".get_option('ar_gwa_footer_'.$lead['lLID']);    
    }
		if($msg['mType'] == 'html') {
     if($ar_gwa_no_spam=='checked' && $ar_gwa_nospam_text != '') {
     $ar_gwa_nospam_text = preg_replace("/\r\n\r\n/",'<p>',$ar_gwa_nospam_text);
     $ar_gwa_nospam_text = preg_replace("/\r\n/",'<br>',$ar_gwa_nospam_text);
         }
     $affiliate_text = '<a href="'.$affiliate.'">Wordpress Newsletter Manager</a>';
     $archivelink = '<a href="'.$archivelink.'">View your message archive.</a>'; 
    } else {
     $archivelink = "View your message archive.\n$archivelink"; 
    }
		$msg['mBody'] = str_replace('<?Name?>', $lead['lName'], $msg['mBody']);
		$msg['mSubject'] = str_replace('<?Name?>', $lead['lName'], $msg['mSubject']);
		$msg['mBody'] = str_replace('<?Email?>', $lead['lEmail'], $msg['mBody']);
		$msg['mSubject'] = str_replace('<?Email?>', $lead['lEmail'], $msg['mSubject']);
		$msg['mBody'] = str_replace('<?Unsubscribe?>', $unsubscribe, $msg['mBody']);
		$msg['mBody'] = str_replace('<?Archive?>', $archivelink, $msg['mBody']);

		$msg['mBody'] = str_replace('<?Field1?>', $lead['lField1'], $msg['mBody']);
		$msg['mBody'] = str_replace('<?Field2?>', $lead['lField2'], $msg['mBody']);
		$msg['mBody'] = str_replace('<?Field3?>', $lead['lField3'], $msg['mBody']);
		$msg['mBody'] = str_replace('<?Field4?>', $lead['lField4'], $msg['mBody']);
		$msg['mBody'] = str_replace('<?Field5?>', $lead['lField5'], $msg['mBody']);
		
//For html emails composed in tinymce
		$msg['mBody'] = str_replace('&lt;?Name?&gt;', $lead['lName'], $msg['mBody']);
		$msg['mSubject'] = str_replace('&lt;?Name?&gt;', $lead['lName'], $msg['mSubject']);
		$msg['mBody'] = str_replace('&lt;?Email?&gt;', $lead['lEmail'], $msg['mBody']);
		$msg['mSubject'] = str_replace('&lt;?Email?&gt;', $lead['lEmail'], $msg['mSubject']);
		$msg['mBody'] = str_replace('&lt;?Unsubscribe?&gt;', $unsubscribe, $msg['mBody']);
		$msg['mBody'] = str_replace('&lt;?Archive?&gt;', $archivelink, $msg['mBody']);

		$msg['mBody'] = str_replace('&lt;?Field1?&gt;', $lead['lField1'], $msg['mBody']);
		$msg['mBody'] = str_replace('&lt;?Field2?&gt;', $lead['lField2'], $msg['mBody']);
		$msg['mBody'] = str_replace('&lt;?Field3?&gt;', $lead['lField3'], $msg['mBody']);
		$msg['mBody'] = str_replace('&lt;?Field4?&gt;', $lead['lField4'], $msg['mBody']);
		$msg['mBody'] = str_replace('&lt;?Field5?&gt;', $lead['lField5'], $msg['mBody']);

	if($msg['mType'] == 'html') { $lb = '<br /><br />'; } else { $lb ="\r\n\r\n"; }
  if(isset($ar_gwa_nospam_text) && $ar_gwa_nospam_text != '')
    $msg['mBody'] .= $ar_gwa_nospam_text.$lb;
	if(get_option('ar_gwa_cb')=='checked')
    $msg['mBody'] .= $lb.$affiliate_text.$lb;
	if(get_option('ar_gwa_addsub')==1)
    $msg['mBody'] .= $lb.$unsubscribe.$lb;
  
  if(isset($msg['mSubject']) && $msg['mSubject'] !='') return $msg['mSubject'];
  else return $msg['mBody'];
  }


function archive($channels,$mLead=NULL) {
global $encoding,$wpdb;
$encoding="iso-8859-1";
header("Content-Type: application/xml; charset=ISO-8859-1"); 
print "<?xml version=\"1.0\" encoding=\"{$encoding}\"?>\n<rss version=\"2.0\">\n <channel>";
if(count($channels)>0) {
 $id=0;
 if(isset($_GET['rss']))
    for($i=0;$i<count($channels);$i++)
 print "  <title>{$channels[0]}</title> 
  <link>{$channels[1]}</link> 
  <description>{$channels[2]}</description>";
 $result=$wpdb->get_results($channels[3]);
 foreach($result as $line) {
  $mBody['mBody'] = $line->mBody;
  $mBody['mType'] = 'html';
  $fmBody = formatMsg($mLead,$mBody);
 $fmBody = preg_replace("/\<\?\w+\?\>/",'',$fmBody);
 $fmBody = preg_replace("/\&lt;\?\w+\?\&gt;/",'',$fmBody);
  $fmBody = substr($fmBody,0,110).'...';
  $mSubject['mSubject'] = $line->mSubject;
  $fmSubject = formatMsg($mLead,$mSubject);
  print "\n  <item>
  <title>".htmlspecialchars($fmSubject)."</title> 
  <link>".htmlentities("{$channels[1]}/?argwa_mid={$line->mDay}".'&'."argwa_lid={$line->mLID}".'&'."argwa_uid={$mLead['lID']}")."</link>";
  print "<description>".htmlspecialchars($fmBody)."</description>\n  </item>";
 }
}
print "\n  </channel>\n  </rss>";
}

if($_REQUEST['page'] != 'ar_gwa_run') 
ar_gwa_queue_start();
ar_gwa_responder_start();
$trx = new ar_gwa_internationalized();
$ctag='<p align="center"><small>'.__("Created by",'argwa').' <a href="http://www.code4cookies.com" target="_blank">Code4Cookies</a> &copy; 2011 GetWebActive. <strong>'.__("Translation",'argwa').': '.$trx->gwa_intn('courtesy').'.</strong> '.__("Use at your own risk.",'argwa').' <em><a href="http://en.wikipedia.org/wiki/CAN-SPAM_Act_of_2003" target="_blank">'.__("Know the Can-Spam Act",'argwa').'.</a></em><br />'.__("This is NOT free software. The software licence allows for installation on a single Wordpress weblog only.",'argwa').'</strong></small></p></div>';

function ar_gwa_check_email($email)
{
    $atom = '[-a-z0-9!#$%&\'*+/=?^_`{|}~]';
    $domain = '[a-z0-9]([-a-z0-9]{0,61}[a-z0-9])';
    return eregi("^$atom+(\\.$atom+)*@($domain?\\.)+$domain\$", $email);
}

if (function_exists('wp_enqueue_script')) wp_enqueue_script('admin-forms');
add_action('autoresponder_gwa_form_display', 'autoresponder_gwa_form_display');
add_action('wp_dashboard_setup', 'ar_gwa_register_dashboard_widget');
function ar_gwa_register_dashboard_widget() {
	wp_register_sidebar_widget('dashboard_ar_gwa', '[GWA] '.__('AutoResponder Statistics','argwa'), 'dashboard_ar_gwa',
		array('feed_link' => 'http://code4cookies.com/feed','width' => 'half','height' => 'single'));
}
add_filter('wp_dashboard_widgets', 'ar_gwa_add_dashboard_widget');
function ar_gwa_add_dashboard_widget($widgets) {
	global $wp_registered_widgets;
	if (!isset($wp_registered_widgets['dashboard_ar_gwa'])) {
		return $widgets;
	}
	array_splice($widgets, sizeof($widgets)-1, 0, 'dashboard_ar_gwa');
	return $widgets;
}

function dashboard_ar_gwa($sidebar_args) {
	global $wpdb;
	echo $before_widget;
	echo $before_title;
	echo $widget_name;
	echo $after_title;
	admin_ar_gwa_get_stats(1);
	echo $after_widget;
}
$popular= array();
function admin_ar_gwa_get_stats($d) {
global $wpdb;
$wpdb->show_errors;
$qry = "SELECT COUNT(*) FROM ".$wpdb->prefix."ar_gwa_leads WHERE lCnf=1";
$num = $wpdb->get_var($qry);
$qry = "SELECT COUNT(*) FROM ".$wpdb->prefix."ar_gwa_leads WHERE "
          ."lDateEntry = current_date AND lCnf=1";
$today =  $wpdb->get_var($qry);
$timestamp = time() - (7 * 86400);
$qry = "SELECT COUNT(*) FROM ".$wpdb->prefix."ar_gwa_leads WHERE "
          ."lDateEntry > FROM_UNIXTIME($timestamp) AND lCnf=1";
$week =  $wpdb->get_var($qry);
$timestamp = time() - (30 * 86400);
$qry = "SELECT COUNT(*) FROM ".$wpdb->prefix."ar_gwa_leads WHERE "
          ."lDateEntry > FROM_UNIXTIME($timestamp) AND lCnf=1";
$month =  $wpdb->get_var($qry);
if(current_user_can('manage_options')) {
echo "<div style='position:relative;'>";
_e("Total addresses subscribed:",'argwa')."&nbsp;";
echo $num.'<br /><br />'.__("Email added today:",'argwa')."&nbsp;$today<br />".__("Email added last 7 Days:",'argwa')."&nbsp;$week<br />".__("Email added last 30 Days:",'argwa')."&nbsp;$month<br /><br />";
_e("Next Mailing in",'argwa');
echo "&nbsp;".round(((((wp_next_scheduled('ar_gwa_daily_event')-time())/60)/60)),1) . __(' hours.','argwa');
echo '</div>';
}}
function ar_gwa_options_default()
{
	return array( 'title' => __("Subscribe",'argwa') );
}

function ar_gwa_optin_init()  
  {  
$st = get_option('ar_gwa_widget_num');

	if ( !function_exists('register_sidebar_widget') || !function_exists('register_widget_control') )
		return;
		
       function ar_gwa_display_1($args, $number = 1)
       {
       $options = get_option_ar_gwa('ar_gwa_widget');
        if(!$options[$number]) {
			   $options[$number] = ar_gwa_options_default();
		    }

    	 extract($options[$number]);
       $list_id = $xID;
    	 $title = $xLabel;
		   if(!isset($title))
          $title = 'Subscribe to '.$xName;        

  		extract($args);
       
        if(isset($xPage) && $xPage != 0) {
          if(is_page($xPage)) {
           echo $before_widget;
           if(get_option('ar_gwa_mShow_'.$list_id)) echo $before_title . $title . $after_title;
           autoresponder_gwa_form_display($list_id);
           echo $after_widget;
          }
        } else {
        echo $before_widget;
        if(get_option('ar_gwa_mShow_'.$list_id)) echo $before_title . $title . $after_title;
        echo autoresponder_gwa_form_display($list_id);
        echo $after_widget;
        }
       }
                   
       function ar_gwa_control_1($number)  
       {  
    		global $wpdb;
        // Collect our widget's options.
        $options = $newoptions = get_option_ar_gwa('ar_gwa_widget');

		    if ( !is_array($options) ) {
			   $options = $newoptions = array();
			  }
		    if(!$options[$number]) {
			    $options[$number] = $newoptions[$number] = ar_gwa_options_default();
		    }
        
    		if($_REQUEST["ar-gwa-submit-{$number}"]) { 
		  	$newoptions[$number]['xLabel'] = strip_tags(stripslashes($_REQUEST["ar-gwa-title-{$number}"]));
		  	$newoptions[$number]['xName'] = strip_tags(stripslashes($_REQUEST["ar-gwa-name-{$number}"]));
		  	$newoptions[$number]['xEmail'] = strip_tags(stripslashes($_REQUEST["ar-gwa-email-{$number}"]));        
		  	$newoptions[$number]['xPage'] = strip_tags(stripslashes($_REQUEST["ar-gwa-page-{$number}"]));        
		  	$newoptions[$number]['xReturn'] = strip_tags(stripslashes($_REQUEST["ar-gwa-return-{$number}"]));
        if($_REQUEST["ar-gwa-return-{$number}"])        
		  	$newoptions[$number]['xReturn'] = strip_tags(stripslashes($_REQUEST["ar-gwa-return-{$number}"]));
        else
		  	$newoptions[$number]['xReturn'] = strip_tags(stripslashes($_REQUEST["ar-gwa-href-{$number}"]));                       
#        update_option('ar_gwa_reg_optin_'.$options[$number]['xID'],$_REQUEST["ar-gwa-optin-".$number]);
        update_option('ar_gwa_notify_'.$options[$number]['xID'],$_REQUEST["ar-gwa-notify-".$number]);
        }  
                if ( $options != $newoptions ) {
#             $options = ar_gwa_array_copy($newoptions);
#            update_option_ar_gwa('ar_gwa_widget', $options);
        }
        $title = htmlspecialchars($options[$number]['xLabel'], ENT_QUOTES);
        $name = htmlspecialchars($options[$number]['xName'], ENT_QUOTES);
        $email = htmlspecialchars($options[$number]['xEmail'], ENT_QUOTES);
        $page = htmlspecialchars($options[$number]['xPage'], ENT_QUOTES);
        if(!preg_match("/^http/i",$options[$number]['xReturn']))        
        $return = htmlspecialchars($options[$number]['xReturn'], ENT_QUOTES);
        else
        $href =  htmlspecialchars($options[$number]['xReturn'], ENT_QUOTES);
?>        <div><div>
        <input type="text" id="ar-gwa-title-<?php echo $number; ?>" name="ar-gwa-title-<?php echo $number; ?>" value="<?php echo $title; ?>" />
<br /><?php _e("For widget options see Update Link on [GWA] Menu page",'argwa')."&nbsp;"; ?><a href="admin.php?page=ar_gwa_lists&update=1&lLID=<?php echo $options[$number]['xID'];?>" title="<?php _e("Click the Update link for each list on the Lists page.",'argwa'); ?>" style="font-weight:bolder"><?php _e("List Details",'argwa'); ?></a>.<br />        <input type="hidden" name="ar-gwa-submit-<?php echo $number; ?>" value="1" /></div></div>
        <?php
   }

       function ar_gwa_display_2($args, $number = 1)
       {
       $options = get_option_ar_gwa('ar_gwa_widget');
        if(!$options[$number]) {
			   $options[$number] = ar_gwa_options_default();
		    }

    	 extract($options[$number]);
       $list_id = $xID;
    	 $title = $xLabel;
		   if(!isset($title))
          $title = 'Subscribe to '.$xName;        

  		extract($args);
       
        if(isset($xPage) && $xPage != 0) {
          if(is_page($xPage)) {
           echo $before_widget;
           if(get_option('ar_gwa_mShow_'.$list_id)) echo $before_title . $title . $after_title;
           autoresponder_gwa_form_display($list_id);
           echo $after_widget;
          }
        } else {
        echo $before_widget;
        if(get_option('ar_gwa_mShow_'.$list_id)) echo $before_title . $title . $after_title;
        echo autoresponder_gwa_form_display($list_id);
        echo $after_widget;
        }
       }
                   
       function ar_gwa_control_2($number)  
       {  
    		global $wpdb;
        // Collect our widget's options.
        $options = $newoptions = get_option_ar_gwa('ar_gwa_widget');

		    if ( !is_array($options) ) {
			   $options = $newoptions = array();
			  }
		    if(!$options[$number]) {
			    $options[$number] = $newoptions[$number] = ar_gwa_options_default();
		    }
        
    		if($_REQUEST["ar-gwa-submit-{$number}"]) { 
		  	$newoptions[$number]['xLabel'] = strip_tags(stripslashes($_REQUEST["ar-gwa-title-{$number}"]));
		  	$newoptions[$number]['xName'] = strip_tags(stripslashes($_REQUEST["ar-gwa-name-{$number}"]));
		  	$newoptions[$number]['xEmail'] = strip_tags(stripslashes($_REQUEST["ar-gwa-email-{$number}"]));        
		  	$newoptions[$number]['xPage'] = strip_tags(stripslashes($_REQUEST["ar-gwa-page-{$number}"]));        
		  	$newoptions[$number]['xReturn'] = strip_tags(stripslashes($_REQUEST["ar-gwa-return-{$number}"]));
        if($_REQUEST["ar-gwa-return-{$number}"])        
		  	$newoptions[$number]['xReturn'] = strip_tags(stripslashes($_REQUEST["ar-gwa-return-{$number}"]));
        else
		  	$newoptions[$number]['xReturn'] = strip_tags(stripslashes($_REQUEST["ar-gwa-href-{$number}"]));                       
#        update_option('ar_gwa_reg_optin_'.$options[$number]['xID'],$_REQUEST["ar-gwa-optin-".$number]);
        update_option('ar_gwa_notify_'.$options[$number]['xID'],$_REQUEST["ar-gwa-notify-".$number]);
        }  
                if ( $options != $newoptions ) {
 #            $options = ar_gwa_array_copy($newoptions);
 #           update_option_ar_gwa('ar_gwa_widget', $options);
        }
        $title = htmlspecialchars($options[$number]['xLabel'], ENT_QUOTES);
        $name = htmlspecialchars($options[$number]['xName'], ENT_QUOTES);
        $email = htmlspecialchars($options[$number]['xEmail'], ENT_QUOTES);
        $page = htmlspecialchars($options[$number]['xPage'], ENT_QUOTES);
        if(!preg_match("/^http/i",$options[$number]['xReturn']))        
        $return = htmlspecialchars($options[$number]['xReturn'], ENT_QUOTES);
        else
        $href =  htmlspecialchars($options[$number]['xReturn'], ENT_QUOTES);
?>        <div><div>
        <input type="text" id="ar-gwa-title-<?php echo $number; ?>" name="ar-gwa-title-<?php echo $number; ?>" value="<?php echo $title; ?>" />
<br /><?php _e("For widget options see Update Link on [GWA] Menu page",'argwa')."&nbsp;"; ?><a href="admin.php?page=ar_gwa_lists&update=1&lLID=<?php echo $options[$number]['xID'];?>" title="<?php _e("Click the Update link for each list on the Lists page.",'argwa'); ?>" style="font-weight:bolder"><?php _e("List Details",'argwa'); ?></a>.<br />        <input type="hidden" name="ar-gwa-submit-<?php echo $number; ?>" value="1" /></div></div>
<?php
   }
   
       function ar_gwa_display_3($args, $number = 1)
       {
       $options = get_option_ar_gwa('ar_gwa_widget');
        if(!$options[$number]) {
			   $options[$number] = ar_gwa_options_default();
		    }

    	 extract($options[$number]);
       $list_id = $xID;
    	 $title = $xLabel;
		   if(!isset($title))
          $title = 'Subscribe to '.$xName;        

  		extract($args);
       
        if(isset($xPage) && $xPage != 0) {
          if(is_page($xPage)) {
           echo $before_widget;
           if(get_option('ar_gwa_mShow_'.$list_id)) echo $before_title . $title . $after_title;
           autoresponder_gwa_form_display($list_id);
           echo $after_widget;
          }
        } else {
        echo $before_widget;
        if(get_option('ar_gwa_mShow_'.$list_id)) echo $before_title . $title . $after_title;
        echo autoresponder_gwa_form_display($list_id);
        echo $after_widget;
        }
       }
                   
       function ar_gwa_control_3($number)  
       {  
    		global $wpdb;
        // Collect our widget's options.
        $options = $newoptions = get_option_ar_gwa('ar_gwa_widget');

		    if ( !is_array($options) ) {
			   $options = $newoptions = array();
			  }
		    if(!$options[$number]) {
			    $options[$number] = $newoptions[$number] = ar_gwa_options_default();
		    }
        
    		if($_REQUEST["ar-gwa-submit-{$number}"]) { 
		  	$newoptions[$number]['xLabel'] = strip_tags(stripslashes($_REQUEST["ar-gwa-title-{$number}"]));
		  	$newoptions[$number]['xName'] = strip_tags(stripslashes($_REQUEST["ar-gwa-name-{$number}"]));
		  	$newoptions[$number]['xEmail'] = strip_tags(stripslashes($_REQUEST["ar-gwa-email-{$number}"]));        
		  	$newoptions[$number]['xPage'] = strip_tags(stripslashes($_REQUEST["ar-gwa-page-{$number}"]));        
		  	$newoptions[$number]['xReturn'] = strip_tags(stripslashes($_REQUEST["ar-gwa-return-{$number}"]));
        if($_REQUEST["ar-gwa-return-{$number}"])        
		  	$newoptions[$number]['xReturn'] = strip_tags(stripslashes($_REQUEST["ar-gwa-return-{$number}"]));
        else
		  	$newoptions[$number]['xReturn'] = strip_tags(stripslashes($_REQUEST["ar-gwa-href-{$number}"]));                       
#        update_option('ar_gwa_reg_optin_'.$options[$number]['xID'],$_REQUEST["ar-gwa-optin-".$number]);
        update_option('ar_gwa_notify_'.$options[$number]['xID'],$_REQUEST["ar-gwa-notify-".$number]);
        }  
                if ( $options != $newoptions ) {
         #    $options = ar_gwa_array_copy($newoptions);
         #   update_option_ar_gwa('ar_gwa_widget', $options);
        }
        $title = htmlspecialchars($options[$number]['xLabel'], ENT_QUOTES);
        $name = htmlspecialchars($options[$number]['xName'], ENT_QUOTES);
        $email = htmlspecialchars($options[$number]['xEmail'], ENT_QUOTES);
        $page = htmlspecialchars($options[$number]['xPage'], ENT_QUOTES);
        if(!preg_match("/^http/i",$options[$number]['xReturn']))        
        $return = htmlspecialchars($options[$number]['xReturn'], ENT_QUOTES);
        else
        $href =  htmlspecialchars($options[$number]['xReturn'], ENT_QUOTES);
?>        <div><div>
        <input type="text" id="ar-gwa-title-<?php echo $number; ?>" name="ar-gwa-title-<?php echo $number; ?>" value="<?php echo $title; ?>" />
<br /><?php _e("For widget options see Update Link on [GWA] Menu page",'argwa')."&nbsp;"; ?><a href="admin.php?page=ar_gwa_lists&update=1&lLID=<?php echo $options[$number]['xID'];?>" title="<?php _e("Click the Update link for each list on the Lists page.",'argwa'); ?>" style="font-weight:bolder"><?php _e("List Details",'argwa'); ?></a>.<br />        <input type="hidden" name="ar-gwa-submit-<?php echo $number; ?>" value="1" /></div></div><?php
   }

       function ar_gwa_display_4($args, $number = 1)
       {
       $options = get_option_ar_gwa('ar_gwa_widget');
        if(!$options[$number]) {
			   $options[$number] = ar_gwa_options_default();
		    }

    	 extract($options[$number]);
       $list_id = $xID;
    	 $title = $xLabel;
		   if(!isset($title))
          $title = 'Subscribe to '.$xName;        

  		extract($args);
       
        if(isset($xPage) && $xPage != 0) {
          if(is_page($xPage)) {
           echo $before_widget;
           if(get_option('ar_gwa_mShow_'.$list_id)) echo $before_title . $title . $after_title;
           autoresponder_gwa_form_display($list_id);
           echo $after_widget;
          }
        } else {
        echo $before_widget;
        if(get_option('ar_gwa_mShow_'.$list_id)) echo $before_title . $title . $after_title;
        echo autoresponder_gwa_form_display($list_id);
        echo $after_widget;
        }
       }
                   
       function ar_gwa_control_4($number)  
       {  
    		global $wpdb;
        // Collect our widget's options.
        $options = $newoptions = get_option_ar_gwa('ar_gwa_widget');

		    if ( !is_array($options) ) {
			   $options = $newoptions = array();
			  }
		    if(!$options[$number]) {
			    $options[$number] = $newoptions[$number] = ar_gwa_options_default();
		    }
        
    		if($_REQUEST["ar-gwa-submit-{$number}"]) { 
		  	$newoptions[$number]['xLabel'] = strip_tags(stripslashes($_REQUEST["ar-gwa-title-{$number}"]));
		  	$newoptions[$number]['xName'] = strip_tags(stripslashes($_REQUEST["ar-gwa-name-{$number}"]));
		  	$newoptions[$number]['xEmail'] = strip_tags(stripslashes($_REQUEST["ar-gwa-email-{$number}"]));        
		  	$newoptions[$number]['xPage'] = strip_tags(stripslashes($_REQUEST["ar-gwa-page-{$number}"]));        
		  	$newoptions[$number]['xReturn'] = strip_tags(stripslashes($_REQUEST["ar-gwa-return-{$number}"]));
        if($_REQUEST["ar-gwa-return-{$number}"])        
		  	$newoptions[$number]['xReturn'] = strip_tags(stripslashes($_REQUEST["ar-gwa-return-{$number}"]));
        else
		  	$newoptions[$number]['xReturn'] = strip_tags(stripslashes($_REQUEST["ar-gwa-href-{$number}"]));                       
#        update_option('ar_gwa_reg_optin_'.$options[$number]['xID'],$_REQUEST["ar-gwa-optin-".$number]);
        update_option('ar_gwa_notify_'.$options[$number]['xID'],$_REQUEST["ar-gwa-notify-".$number]);
        }  
                if ( $options != $newoptions ) {
          #   $options = ar_gwa_array_copy($newoptions);
          #  update_option_ar_gwa('ar_gwa_widget', $options);
        }
        $title = htmlspecialchars($options[$number]['xLabel'], ENT_QUOTES);
        $name = htmlspecialchars($options[$number]['xName'], ENT_QUOTES);
        $email = htmlspecialchars($options[$number]['xEmail'], ENT_QUOTES);
        $page = htmlspecialchars($options[$number]['xPage'], ENT_QUOTES);
        if(!preg_match("/^http/i",$options[$number]['xReturn']))        
        $return = htmlspecialchars($options[$number]['xReturn'], ENT_QUOTES);
        else
        $href =  htmlspecialchars($options[$number]['xReturn'], ENT_QUOTES);
?>        <div><div>
        <input type="text" id="ar-gwa-title-<?php echo $number; ?>" name="ar-gwa-title-<?php echo $number; ?>" value="<?php echo $title; ?>" />
<br /><?php _e("For widget options see Update Link on [GWA] Menu page",'argwa')."&nbsp;"; ?><a href="admin.php?page=ar_gwa_lists&update=1&lLID=<?php echo $options[$number]['xID'];?>" title="<?php _e("Click the Update link for each list on the Lists page.",'argwa'); ?>" style="font-weight:bolder"><?php _e("List Details",'argwa'); ?></a>.<br />        <input type="hidden" name="ar-gwa-submit-<?php echo $number; ?>" value="1" /></div></div><?php
   }

       function ar_gwa_display_5($args, $number = 1)
       {
       $options = get_option_ar_gwa('ar_gwa_widget');
        if(!$options[$number]) {
			   $options[$number] = ar_gwa_options_default();
		    }

    	 extract($options[$number]);
       $list_id = $xID;
    	 $title = $xLabel;
		   if(!isset($title))
          $title = 'Subscribe to '.$xName;        

  		extract($args);
       
        if(isset($xPage) && $xPage != 0) {
          if(is_page($xPage)) {
           echo $before_widget;
           if(get_option('ar_gwa_mShow_'.$list_id)) echo $before_title . $title . $after_title;
           autoresponder_gwa_form_display($list_id);
           echo $after_widget;
          }
        } else {
        echo $before_widget;
        if(get_option('ar_gwa_mShow_'.$list_id)) echo $before_title . $title . $after_title;
        echo autoresponder_gwa_form_display($list_id);
        echo $after_widget;
        }
       }
                   
       function ar_gwa_control_5($number)  
       {  
    		global $wpdb;
        // Collect our widget's options.
        $options = $newoptions = get_option_ar_gwa('ar_gwa_widget');

		    if ( !is_array($options) ) {
			   $options = $newoptions = array();
			  }
		    if(!$options[$number]) {
			    $options[$number] = $newoptions[$number] = ar_gwa_options_default();
		    }
        
    		if($_REQUEST["ar-gwa-submit-{$number}"]) { 
		  	$newoptions[$number]['xLabel'] = strip_tags(stripslashes($_REQUEST["ar-gwa-title-{$number}"]));
		  	$newoptions[$number]['xName'] = strip_tags(stripslashes($_REQUEST["ar-gwa-name-{$number}"]));
		  	$newoptions[$number]['xEmail'] = strip_tags(stripslashes($_REQUEST["ar-gwa-email-{$number}"]));        
		  	$newoptions[$number]['xPage'] = strip_tags(stripslashes($_REQUEST["ar-gwa-page-{$number}"]));        
		  	$newoptions[$number]['xReturn'] = strip_tags(stripslashes($_REQUEST["ar-gwa-return-{$number}"]));
        if($_REQUEST["ar-gwa-return-{$number}"])        
		  	$newoptions[$number]['xReturn'] = strip_tags(stripslashes($_REQUEST["ar-gwa-return-{$number}"]));
        else
		  	$newoptions[$number]['xReturn'] = strip_tags(stripslashes($_REQUEST["ar-gwa-href-{$number}"]));                       
#        update_option('ar_gwa_reg_optin_'.$options[$number]['xID'],$_REQUEST["ar-gwa-optin-".$number]);
        update_option('ar_gwa_notify_'.$options[$number]['xID'],$_REQUEST["ar-gwa-notify-".$number]);
        }  
                if ( $options != $newoptions ) {
        #     $options = ar_gwa_array_copy($newoptions);
        #    update_option_ar_gwa('ar_gwa_widget', $options);
        }
        $title = htmlspecialchars($options[$number]['xLabel'], ENT_QUOTES);
        $name = htmlspecialchars($options[$number]['xName'], ENT_QUOTES);
        $email = htmlspecialchars($options[$number]['xEmail'], ENT_QUOTES);
        $page = htmlspecialchars($options[$number]['xPage'], ENT_QUOTES);
        if(!preg_match("/^http/i",$options[$number]['xReturn']))        
        $return = htmlspecialchars($options[$number]['xReturn'], ENT_QUOTES);
        else
        $href =  htmlspecialchars($options[$number]['xReturn'], ENT_QUOTES);
?>        <div><div>
        <input type="text" id="ar-gwa-title-<?php echo $number; ?>" name="ar-gwa-title-<?php echo $number; ?>" value="<?php echo $title; ?>" />
<br /><?php _e("For widget options see Update Link on [GWA] Menu page",'argwa')."&nbsp;"; ?><a href="admin.php?page=ar_gwa_lists&update=1&lLID=<?php echo $options[$number]['xID'];?>" title="<?php _e("Click the Update link for each list on the Lists page.",'argwa'); ?>" style="font-weight:bolder"><?php _e("List Details",'argwa'); ?></a>.<br />        <input type="hidden" name="ar-gwa-submit-<?php echo $number; ?>" value="1" /></div></div><?php
   }
   
       function ar_gwa_display_6($args, $number = 1)
       {
       $options = get_option_ar_gwa('ar_gwa_widget');
        if(!$options[$number]) {
			   $options[$number] = ar_gwa_options_default();
		    }

    	 extract($options[$number]);
       $list_id = $xID;
    	 $title = $xLabel;
		   if(!isset($title))
          $title = 'Subscribe to '.$xName;        

  		extract($args);
       
        if(isset($xPage) && $xPage != 0) {
          if(is_page($xPage)) {
           echo $before_widget;
           if(get_option('ar_gwa_mShow_'.$list_id)) echo $before_title . $title . $after_title;
           autoresponder_gwa_form_display($list_id);
           echo $after_widget;
          }
        } else {
        echo $before_widget;
        if(get_option('ar_gwa_mShow_'.$list_id)) echo $before_title . $title . $after_title;
        echo autoresponder_gwa_form_display($list_id);
        echo $after_widget;
        }
       }
                   
       function ar_gwa_control_6($number)  
       {  
    		global $wpdb;
        // Collect our widget's options.
        $options = $newoptions = get_option_ar_gwa('ar_gwa_widget');

		    if ( !is_array($options) ) {
			   $options = $newoptions = array();
			  }
		    if(!$options[$number]) {
			    $options[$number] = $newoptions[$number] = ar_gwa_options_default();
		    }
        
    		if($_REQUEST["ar-gwa-submit-{$number}"]) { 
		  	$newoptions[$number]['xLabel'] = strip_tags(stripslashes($_REQUEST["ar-gwa-title-{$number}"]));
		  	$newoptions[$number]['xName'] = strip_tags(stripslashes($_REQUEST["ar-gwa-name-{$number}"]));
		  	$newoptions[$number]['xEmail'] = strip_tags(stripslashes($_REQUEST["ar-gwa-email-{$number}"]));        
		  	$newoptions[$number]['xPage'] = strip_tags(stripslashes($_REQUEST["ar-gwa-page-{$number}"]));        
		  	$newoptions[$number]['xReturn'] = strip_tags(stripslashes($_REQUEST["ar-gwa-return-{$number}"]));
        if($_REQUEST["ar-gwa-return-{$number}"])        
		  	$newoptions[$number]['xReturn'] = strip_tags(stripslashes($_REQUEST["ar-gwa-return-{$number}"]));
        else
		  	$newoptions[$number]['xReturn'] = strip_tags(stripslashes($_REQUEST["ar-gwa-href-{$number}"]));                       
#        update_option('ar_gwa_reg_optin_'.$options[$number]['xID'],$_REQUEST["ar-gwa-optin-".$number]);
        update_option('ar_gwa_notify_'.$options[$number]['xID'],$_REQUEST["ar-gwa-notify-".$number]);
        }  
                if ( $options != $newoptions ) {
         #    $options = ar_gwa_array_copy($newoptions);
         #   update_option_ar_gwa('ar_gwa_widget', $options);
        }
        $title = htmlspecialchars($options[$number]['xLabel'], ENT_QUOTES);
        $name = htmlspecialchars($options[$number]['xName'], ENT_QUOTES);
        $email = htmlspecialchars($options[$number]['xEmail'], ENT_QUOTES);
        $page = htmlspecialchars($options[$number]['xPage'], ENT_QUOTES);
        if(!preg_match("/^http/i",$options[$number]['xReturn']))        
        $return = htmlspecialchars($options[$number]['xReturn'], ENT_QUOTES);
        else
        $href =  htmlspecialchars($options[$number]['xReturn'], ENT_QUOTES);
?>        <div><div>
        <input type="text" id="ar-gwa-title-<?php echo $number; ?>" name="ar-gwa-title-<?php echo $number; ?>" value="<?php echo $title; ?>" />
<br /><?php _e("For widget options see Update Link on [GWA] Menu page",'argwa')."&nbsp;"; ?><a href="admin.php?page=ar_gwa_lists&update=1&lLID=<?php echo $options[$number]['xID'];?>" title="<?php _e("Click the Update link for each list on the Lists page.",'argwa'); ?>" style="font-weight:bolder"><?php _e("List Details",'argwa'); ?></a>.<br />        <input type="hidden" name="ar-gwa-submit-<?php echo $number; ?>" value="1" /></div></div><?php
   }
       function ar_gwa_display_7($args, $number = 1)
       {
       $options = get_option_ar_gwa('ar_gwa_widget');
        if(!$options[$number]) {
			   $options[$number] = ar_gwa_options_default();
		    }

    	 extract($options[$number]);
       $list_id = $xID;
    	 $title = $xLabel;
		   if(!isset($title))
          $title = 'Subscribe to '.$xName;        

  		extract($args);
       
        if(isset($xPage) && $xPage != 0) {
          if(is_page($xPage)) {
           echo $before_widget;
           if(get_option('ar_gwa_mShow_'.$list_id)) echo $before_title . $title . $after_title;
           autoresponder_gwa_form_display($list_id);
           echo $after_widget;
          }
        } else {
        echo $before_widget;
        if(get_option('ar_gwa_mShow_'.$list_id)) echo $before_title . $title . $after_title;
        echo autoresponder_gwa_form_display($list_id);
        echo $after_widget;
        }
       }
                   
       function ar_gwa_control_7($number)  
       {  
    		global $wpdb;
        // Collect our widget's options.
        $options = $newoptions = get_option_ar_gwa('ar_gwa_widget');

		    if ( !is_array($options) ) {
			   $options = $newoptions = array();
			  }
		    if(!$options[$number]) {
			    $options[$number] = $newoptions[$number] = ar_gwa_options_default();
		    }
        
    		if($_REQUEST["ar-gwa-submit-{$number}"]) { 
		  	$newoptions[$number]['xLabel'] = strip_tags(stripslashes($_REQUEST["ar-gwa-title-{$number}"]));
		  	$newoptions[$number]['xName'] = strip_tags(stripslashes($_REQUEST["ar-gwa-name-{$number}"]));
		  	$newoptions[$number]['xEmail'] = strip_tags(stripslashes($_REQUEST["ar-gwa-email-{$number}"]));        
		  	$newoptions[$number]['xPage'] = strip_tags(stripslashes($_REQUEST["ar-gwa-page-{$number}"]));        
		  	$newoptions[$number]['xReturn'] = strip_tags(stripslashes($_REQUEST["ar-gwa-return-{$number}"]));
        if($_REQUEST["ar-gwa-return-{$number}"])        
		  	$newoptions[$number]['xReturn'] = strip_tags(stripslashes($_REQUEST["ar-gwa-return-{$number}"]));
        else
		  	$newoptions[$number]['xReturn'] = strip_tags(stripslashes($_REQUEST["ar-gwa-href-{$number}"]));                       
#        update_option('ar_gwa_reg_optin_'.$options[$number]['xID'],$_REQUEST["ar-gwa-optin-".$number]);
        update_option('ar_gwa_notify_'.$options[$number]['xID'],$_REQUEST["ar-gwa-notify-".$number]);
        }  
                if ( $options != $newoptions ) {
        #     $options = ar_gwa_array_copy($newoptions);
        #    update_option_ar_gwa('ar_gwa_widget', $options);
        }
        $title = htmlspecialchars($options[$number]['xLabel'], ENT_QUOTES);
        $name = htmlspecialchars($options[$number]['xName'], ENT_QUOTES);
        $email = htmlspecialchars($options[$number]['xEmail'], ENT_QUOTES);
        $page = htmlspecialchars($options[$number]['xPage'], ENT_QUOTES);
        if(!preg_match("/^http/i",$options[$number]['xReturn']))        
        $return = htmlspecialchars($options[$number]['xReturn'], ENT_QUOTES);
        else
        $href =  htmlspecialchars($options[$number]['xReturn'], ENT_QUOTES);
?>        <div><div>
        <input type="text" id="ar-gwa-title-<?php echo $number; ?>" name="ar-gwa-title-<?php echo $number; ?>" value="<?php echo $title; ?>" />
<br /><?php _e("For widget options see Update Link on [GWA] Menu page",'argwa')."&nbsp;"; ?><a href="admin.php?page=ar_gwa_lists&update=1&lLID=<?php echo $options[$number]['xID'];?>" title="<?php _e("Click the Update link for each list on the Lists page.",'argwa'); ?>" style="font-weight:bolder"><?php _e("List Details",'argwa'); ?></a>.<br />        <input type="hidden" name="ar-gwa-submit-<?php echo $number; ?>" value="1" /></div></div><?php
   }
   
       function ar_gwa_display_8($args, $number = 1)
       {
       $options = get_option_ar_gwa('ar_gwa_widget');
        if(!$options[$number]) {
			   $options[$number] = ar_gwa_options_default();
		    }

    	 extract($options[$number]);
       $list_id = $xID;
    	 $title = $xLabel;
		   if(!isset($title))
          $title = 'Subscribe to '.$xName;        

  		extract($args);
       
        if(isset($xPage) && $xPage != 0) {
          if(is_page($xPage)) {
           echo $before_widget;
           if(get_option('ar_gwa_mShow_'.$list_id)) echo $before_title . $title . $after_title;
           autoresponder_gwa_form_display($list_id);
           echo $after_widget;
          }
        } else {
        echo $before_widget;
        if(get_option('ar_gwa_mShow_'.$list_id)) echo $before_title . $title . $after_title;
        echo autoresponder_gwa_form_display($list_id);
        echo $after_widget;
        }
       }
                   
       function ar_gwa_control_8($number)  
       {  
    		global $wpdb;
        // Collect our widget's options.
        $options = $newoptions = get_option_ar_gwa('ar_gwa_widget');

		    if ( !is_array($options) ) {
			   $options = $newoptions = array();
			  }
		    if(!$options[$number]) {
			    $options[$number] = $newoptions[$number] = ar_gwa_options_default();
		    }
        
    		if($_REQUEST["ar-gwa-submit-{$number}"]) { 
		  	$newoptions[$number]['xLabel'] = strip_tags(stripslashes($_REQUEST["ar-gwa-title-{$number}"]));
		  	$newoptions[$number]['xName'] = strip_tags(stripslashes($_REQUEST["ar-gwa-name-{$number}"]));
		  	$newoptions[$number]['xEmail'] = strip_tags(stripslashes($_REQUEST["ar-gwa-email-{$number}"]));        
		  	$newoptions[$number]['xPage'] = strip_tags(stripslashes($_REQUEST["ar-gwa-page-{$number}"]));        
		  	$newoptions[$number]['xReturn'] = strip_tags(stripslashes($_REQUEST["ar-gwa-return-{$number}"]));
        if($_REQUEST["ar-gwa-return-{$number}"])        
		  	$newoptions[$number]['xReturn'] = strip_tags(stripslashes($_REQUEST["ar-gwa-return-{$number}"]));
        else
		  	$newoptions[$number]['xReturn'] = strip_tags(stripslashes($_REQUEST["ar-gwa-href-{$number}"]));                       
#        update_option('ar_gwa_reg_optin_'.$options[$number]['xID'],$_REQUEST["ar-gwa-optin-".$number]);
        update_option('ar_gwa_notify_'.$options[$number]['xID'],$_REQUEST["ar-gwa-notify-".$number]);
        }  
                if ( $options != $newoptions ) {
        #     $options = ar_gwa_array_copy($newoptions);
        #    update_option_ar_gwa('ar_gwa_widget', $options);
        }
        $title = htmlspecialchars($options[$number]['xLabel'], ENT_QUOTES);
        $name = htmlspecialchars($options[$number]['xName'], ENT_QUOTES);
        $email = htmlspecialchars($options[$number]['xEmail'], ENT_QUOTES);
        $page = htmlspecialchars($options[$number]['xPage'], ENT_QUOTES);
        if(!preg_match("/^http/i",$options[$number]['xReturn']))        
        $return = htmlspecialchars($options[$number]['xReturn'], ENT_QUOTES);
        else
        $href =  htmlspecialchars($options[$number]['xReturn'], ENT_QUOTES);
?>        <div><div>
        <input type="text" id="ar-gwa-title-<?php echo $number; ?>" name="ar-gwa-title-<?php echo $number; ?>" value="<?php echo $title; ?>" />
<br /><?php _e("For widget options see Update Link on [GWA] Menu page",'argwa')."&nbsp;"; ?><a href="admin.php?page=ar_gwa_lists&update=1&lLID=<?php echo $options[$number]['xID'];?>" title="<?php _e("Click the Update link for each list on the Lists page.",'argwa'); ?>" style="font-weight:bolder"><?php _e("List Details",'argwa'); ?></a>.<br />        <input type="hidden" name="ar-gwa-submit-<?php echo $number; ?>" value="1" /></div></div><?php
   }

       function ar_gwa_display_9($args, $number = 1)
       {
       $options = get_option_ar_gwa('ar_gwa_widget');
        if(!$options[$number]) {
			   $options[$number] = ar_gwa_options_default();
		    }

    	 extract($options[$number]);
       $list_id = $xID;
    	 $title = $xLabel;
		   if(!isset($title))
          $title = 'Subscribe to '.$xName;        

  		extract($args);
       
        if(isset($xPage) && $xPage != 0) {
          if(is_page($xPage)) {
           echo $before_widget;
           if(get_option('ar_gwa_mShow_'.$list_id)) echo $before_title . $title . $after_title;
           autoresponder_gwa_form_display($list_id);
           echo $after_widget;
          }
        } else {
        echo $before_widget;
        if(get_option('ar_gwa_mShow_'.$list_id)) echo $before_title . $title . $after_title;
        echo autoresponder_gwa_form_display($list_id);
        echo $after_widget;
        }
       }
                   
       function ar_gwa_control_9($number)  
       {  
    		global $wpdb;
        // Collect our widget's options.
        $options = $newoptions = get_option_ar_gwa('ar_gwa_widget');

		    if ( !is_array($options) ) {
			   $options = $newoptions = array();
			  }
		    if(!$options[$number]) {
			    $options[$number] = $newoptions[$number] = ar_gwa_options_default();
		    }
        
    		if($_REQUEST["ar-gwa-submit-{$number}"]) { 
		  	$newoptions[$number]['xLabel'] = strip_tags(stripslashes($_REQUEST["ar-gwa-title-{$number}"]));
		  	$newoptions[$number]['xName'] = strip_tags(stripslashes($_REQUEST["ar-gwa-name-{$number}"]));
		  	$newoptions[$number]['xEmail'] = strip_tags(stripslashes($_REQUEST["ar-gwa-email-{$number}"]));        
		  	$newoptions[$number]['xPage'] = strip_tags(stripslashes($_REQUEST["ar-gwa-page-{$number}"]));        
		  	$newoptions[$number]['xReturn'] = strip_tags(stripslashes($_REQUEST["ar-gwa-return-{$number}"]));
        if($_REQUEST["ar-gwa-return-{$number}"])        
		  	$newoptions[$number]['xReturn'] = strip_tags(stripslashes($_REQUEST["ar-gwa-return-{$number}"]));
        else
		  	$newoptions[$number]['xReturn'] = strip_tags(stripslashes($_REQUEST["ar-gwa-href-{$number}"]));                       
#        update_option('ar_gwa_reg_optin_'.$options[$number]['xID'],$_REQUEST["ar-gwa-optin-".$number]);
        update_option('ar_gwa_notify_'.$options[$number]['xID'],$_REQUEST["ar-gwa-notify-".$number]);
        }  
                if ( $options != $newoptions ) {
        #     $options = ar_gwa_array_copy($newoptions);
        #    update_option_ar_gwa('ar_gwa_widget', $options);
        }
        $title = htmlspecialchars($options[$number]['xLabel'], ENT_QUOTES);
        $name = htmlspecialchars($options[$number]['xName'], ENT_QUOTES);
        $email = htmlspecialchars($options[$number]['xEmail'], ENT_QUOTES);
        $page = htmlspecialchars($options[$number]['xPage'], ENT_QUOTES);
        if(!preg_match("/^http/i",$options[$number]['xReturn']))        
        $return = htmlspecialchars($options[$number]['xReturn'], ENT_QUOTES);
        else
        $href =  htmlspecialchars($options[$number]['xReturn'], ENT_QUOTES);
?>        <div><div>
        <input type="text" id="ar-gwa-title-<?php echo $number; ?>" name="ar-gwa-title-<?php echo $number; ?>" value="<?php echo $title; ?>" />
<br /><?php _e("For widget options see Update Link on [GWA] Menu page",'argwa')."&nbsp;"; ?><a href="admin.php?page=ar_gwa_lists&update=1&lLID=<?php echo $options[$number]['xID'];?>" title="<?php _e("Click the Update link for each list on the Lists page.",'argwa'); ?>" style="font-weight:bolder"><?php _e("List Details",'argwa'); ?></a>.<br />        <input type="hidden" name="ar-gwa-submit-<?php echo $number; ?>" value="1" /></div></div><?php
   }


#    register_sidebar_widget(array('[GWA] Autoresponder', 'widgets',''), 'ar_gwa_display');     
#    register_widget_control('[GWA] Autoresponder', 'ar_gwa_control');

function get_option_ar_gwa($widget=NULL) {
  global $wpdb;
#  $wpdb->show_errors();
  
  if(is_int($widget)){
  $sql="SELECT * FROM ".$wpdb->prefix."ar_gwa_lists WHERE xID='".$widget."'";
  return $wpdb->get_var($sql);
  } else {
  $sql="SELECT * FROM ".$wpdb->prefix."ar_gwa_lists ORDER BY xID";
  $rec = $wpdb->get_results($sql,ARRAY_A);
  $arr = array();
  $arr[] = array('');
  $arr2 = array();
  $arr['number'] = count($rec);
  if($rec) {
  foreach($rec as $hey) {
   foreach($hey as $k => $v) {   
    $arr2[$k] = $v;
   }
   $arr[] = $arr2;
  }
  }
 return $arr;
 }
}

  function update_option_ar_gwa($widget,$options,$number=NULL) {
  global $wpdb,$ar_gwa_debug;
  if($ar_gwa_debug=="ON") $wpdb->show_errors();

    foreach($options as $op) {   
    if($op['xPage']=='') { $op['xPage'] = '0'; } 
     $sql = "UPDATE ".$wpdb->prefix."ar_gwa_lists set `xName`='{$op['xName']}',`xLabel`='{$op['xLabel']}',`xPage`='{$op['xPage']}',`xEmail`='{$op['xEmail']}',`xReturn`='{$op['xReturn']}' WHERE xID='{$op['xID']}'";
    $wpdb->query($sql);
    }
}
	function ar_gwa_widget_setup() {
		$options = $newoptions = get_option_ar_gwa('ar_gwa_widget');
		if ( isset($_POST['ar-gwa-number-submit']) ) {
			$number = (int) $_POST['ar-gwa-number'];
			if ( $number > 9 ) $number = 9;
			if ( $number < 1 ) $number = 1;
			$newoptions['number'] = $number;
		}
		
		if ( $options != $newoptions ) {
			$options = $newoptions;
        if(!$newoptions['number']) 
        $newoptions['number'] = $number;
$oopp = array();
$oopp[] = $options;
			update_option_ar_gwa('ar_gwa_widget', $oopp, $newoptions['number']);
			ar_gwa_widget_register($newoptions['number']);
		}
	}
	
	function ar_gwa_widget_register($number=NULL) {
		$options = get_option_ar_gwa('ar_gwa_widget');
		$number = $options['number'];

		if ( $number < 1 ) $number = 1;
		if ( $number > 9 ) $number = 9;
		for ($i = 1; $i <= 9; $i++) {
			$name = array('Autoresponder #%s', 'widgets', $i);
#			$name = "Autoresponder #$i";
			register_sidebar_widget($name, $i <= $number ? 'ar_gwa_display_'.$i : /* unregister */ '', $i);
			register_widget_control($name, $i <= $number ? 'ar_gwa_control_'.$i : /* unregister */ '', 0, 0, $i);
#			register_sidebar_widget($name, $i <= $number ? 'ar_gwa_display' : /* unregister */ '');
#			register_widget_control($name, $i <= $number ? 'ar_gwa_control' : /* unregister */ '');
		}
		add_action('sidebar_admin_setup', 'ar_gwa_widget_setup');
	}
	
	ar_gwa_widget_register();
}
add_action('plugins_loaded', 'ar_gwa_optin_init');
add_action( 'register_form', 'ar_gwa_reg_subscribe_form' );	
add_action( 'user_register', 'ar_gwa_reg_subscribe_user' );	

function ar_gwa_reg_subscribe_user() {
 global $wpdb;
 $lName = $_REQUEST['user_login'];
 $lEmail = $_REQUEST['user_email'];
# $wpdb->show_errors();
 if(is_array($_REQUEST['LIST'])){
  foreach($_REQUEST['LIST'] as $list) {
  global $wpdb;
	 $qry = "INSERT INTO ".$wpdb->prefix."ar_gwa_leads(lLID, lName, lEmail, lDateEntry, lDateOut, lMOut, lCnf) VALUES('".$list."','".$lName."', '".$lEmail."' ,current_date, current_date, '-1','1')";
	 $wpdb->query($qry);   
  } //end foreach
 }
}

function ar_gwa_reg_subscribe_form() {
 global $wpdb;
 
# $wpdb->show_errors();
 $qry = "SELECT * FROM ".$wpdb->prefix."ar_gwa_lists";
 $rec = $wpdb->get_results($qry,ARRAY_A);
 foreach($rec as $rc) { if(get_option('ar_gwa_reg_optin_'.$rc['xID']) == 'checked') { echo '<input type="checkbox" name="LIST[]" value="'.$rc['xID'].'" checked> '.__("Subscribe to our newsletter",'argwa').' '.$rc['xName'].'.<br /><br />'; } else if(get_option('ar_gwa_reg_optinb_'.$rc['xID']) == 'checked') { echo '<input type="hidden" name="LIST[]" value="'.$rc['xID'].'" checked>';}}}

function ar_gwa_getlistname($listid) {
 global $wpdb;
# $wpdb->show_errors();
 $qry = "SELECT xName FROM ".$wpdb->prefix."ar_gwa_lists WHERE xID='".$listid."'";
 return $wpdb->get_var($qry);
}

function ar_gwa_buildlistselect($listid=NULL,$two=NULL) {
 global $wpdb;
# $wpdb->show_errors();
 $option = '<select name="listid'.$two.'" style="border: solid 1px #000;" ';
 if($_REQUEST['page']=='ar_gwa_edit_message') $option .=' onchange="toggle(this.options.selectedIndex)"';
 $option .= ">";
 $qry = "SELECT * FROM ".$wpdb->prefix."ar_gwa_lists WHERE 1";
 $res = $wpdb->get_results($qry);
 if($_REQUEST['page'] != 'ar_gwa_add_leads' 
    && $_REQUEST['page'] != 'ar_gwa_add_message' 
    && ($_REQUEST['page'] == 'ar_gwa_edit_message' && (($_REQUEST['mID']==0) & !($_REQUEST['admin_ar_gwa_send_message']) & !($_REQUEST['admin_ar_gwa_add_message']))) 
    && $_REQUEST['page'] != 'ar_gwa_email_leads' 
    && $_REQUEST['page'] != 'autoresponder-gwa/ar_gwa.php' 
    && $_REQUEST['page'] != 'ar_gwa_add_leads'
    && !($_REQUEST['admin_ar_gwa_add_leads'])) 
   $option .= '<option value="0">'.__("ALL",'argwa').'</option>';
  if($_REQUEST['page']=='ar_gwa_edit_message' && isset($_REQUEST['admin_ar_gwa_send_message'])) $option .= '<option value="0" disabled="disabled" selected="selected">'.__("Select Subscriber List",'argwa').'</option><option value="sendWPMessage">'.__("SEND TO ALL WORDPRESS USERS",'argwa').'</option>';
 if (count($res)>0) {
  foreach($res as $r) {
  $option .= '<option value="'.$r->xID.'" ';
  if(strlen($r->xName)>30) $rr = substr($r->xName,0,30).'...'; else $rr = $r->xName;
  if($listid && ($listid == $r->xID || $_REQUEST['listid'] == $r->xID)) $option .= 'selected';
  $option .= '>'.$rr.'</option>';
  }
 } else {
  if(strlen($res[0]->xName)>30) $rr = substr($res[0]->xName,0,30).'...'; else $rr = $res[0]->xName;
  $option .= '<option value="'.$res[0]->xID.'">'.$rr.'</option>';
 }
if($_REQUEST['listid']=='-1') $optionn = ' selected';
if($_REQUEST['listid']=='-2') $optionnn = ' selected';
#if(class_exists('ar_gwa_bounce'))
$rmvd = '<option value="-2" style="color:#f00"'.$optionnn.'>Removed</option></select>';
if($_REQUEST['page'] == 'ar_gwa_leads' && ((!$_REQUEST['admin_ar_gwa_export_leads'] | $_REQUEST['admin_ar_gwa_export_leads']=='') && (!$_REQUEST['admin_ar_gwa_add_leads'] | $_REQUEST['admin_ar_gwa_add_leads']=='')))
return $option.'<option value="-1" style="color:#f00"'.$optionn.'>Unconfirmed</option>'.$rmvd;
else
return $option.'</select>';
}

function admin_ar_gwa_main() {
global $wpdb,$ctag,$gwa_version_tag,$ar_gwa_debug,$phpmailerDir,$wp_locale;

if($wpdb->get_var("SHOW columns FROM `".$wpdb->prefix."ar_gwa_lists` like 'xPopin'") != 'xPopin') {
$psql="ALTER TABLE `".$wpdb->prefix."ar_gwa_lists` ADD `xPopin` text";
$results = $wpdb->query( $psql );  
$xqry = "UPDATE ".$wpdb->prefix."ar_gwa_lists SET xPopin=xSubscribe";
$wpdb->query($xqry);
}

if($wpdb->get_var("SHOW columns FROM `".$wpdb->prefix."ar_gwa_lists` like 'xSlide'") != 'xSlide') {
$psql="ALTER TABLE `".$wpdb->prefix."ar_gwa_lists` ADD `xSlide` text";
$results = $wpdb->query( $psql );  
$xqry = "UPDATE ".$wpdb->prefix."ar_gwa_lists SET xSlide=xSubscribe";
$wpdb->query($xqry);
}

if($ar_gwa_debug=="ON") $wpdb->show_errors();
if(file_exists(dirname(__FILE__).'/ar_gwa_help.php') & (get_option('ar_gwa_help')!='1')) {
$ar_gwa_help= new ar_gwa_help();
echo $ar_gwa_help->ar_gwa_new_help();
update_option('ar_gwa_help','1');
exit;
}

if($_REQUEST['act']=='main') {
 if(isset($_REQUEST['sched'])) {
  wp_clear_scheduled_hook('ar_gwa_daily_event');
	wp_schedule_event((time()+86400), 'daily', 'ar_gwa_daily_event');
 } else if(isset($_REQUEST['sched2'])) {
  $delay = (($_REQUEST['hr']*(60*60)) + ($_REQUEST['min']*60));
  wp_clear_scheduled_hook('ar_gwa_daily_event');
  $tt = time();
	wp_schedule_event(($tt+$delay), 'daily', 'ar_gwa_daily_event');  
 } else if(isset($_REQUEST['submit']) || isset($_REQUEST['update'])) {
  set_ar_gwa_options(1);
 }
}

$listid = $_REQUEST['listid'];
if(!isset($_REQUEST['listid']))
  $listid = $wpdb->get_var("SELECT xID FROM ".$wpdb->prefix."ar_gwa_lists ORDER BY xName LIMIT 0,1");
$stat = array();
$stat['ttl_leads'] = $wpdb->get_var("SELECT COUNT(lID) FROM ".$wpdb->prefix."ar_gwa_leads WHERE lCnf=1");
$stat['ttl_lists'] = $wpdb->get_var("SELECT COUNT(xID) FROM ".$wpdb->prefix."ar_gwa_lists");
$rec = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."ar_gwa_lists");
foreach($rec as $re) {
$lcnt++;$acnt = $wpdb->get_var("SELECT COUNT(lID) FROM ".$wpdb->prefix."ar_gwa_leads WHERE lLID='".$re->xID."' AND lCnf='1'");
$stat['lst_list'] .= "<strong><a href='?page=ar_gwa_lists&lLID=".$re->xID."&update=1' title='Click for List ".$lcnt." Details'>".sprintf(__("List #%d",'argwa'),$lcnt)."</a></strong>: <a href='?page=ar_gwa_edit_message&listid=".$re->xID."' style='text-decoration:none'>".$re->xName."</a> <a href='?page=ar_gwa_leads&listid=".$re->xID."'>".$acnt."</a><br />";
}
if( round(((((wp_next_scheduled('ar_gwa_daily_event')-time())/60)/60)),1) < 1)
  $ar_color="#ff0000";
else
  $ar_color="#d54e21";
if(isset($_REQUEST['ar_gwa_api_key']) && isset($_REQUEST['ar_gwa_api_submit'])) {
 $ar_gwa_api_key = strip_tags($_REQUEST['ar_gwa_api_key']);
  if(isset($_REQUEST['ar_gwa_cb'])) 
    $ar_gwa_cb = 'checked';
  else
    $ar_gwa_cb = '';//get_option('ar_gwa_cb');
  if(isset($_REQUEST['ar_gwa_delete'])) 
    $ar_gwa_delete = 'checked';
  else
    $ar_gwa_delete = '';
 update_option('ar_gwa_delete',$ar_gwa_delete);    
 update_option('ar_gwa_cb',$ar_gwa_cb,'');
 delete_option('ar_gwa_api_key');
 add_option('ar_gwa_api_key',$ar_gwa_api_key,'');
 $bloginfo = array('url' => get_bloginfo('url'),
                     'name' => mysql_real_escape_string(get_bloginfo('name')));
 $nup=ar_gwa_check($bloginfo['name'],$bloginfo['url']);

  if($wpdb->get_var("show columns FROM ".$wpdb->prefix."ar_gwa_leads like 'lField1'")!='lField1') {
#  if($ar_gwa_debug=="ON") $wpdb->hide_errors();
  $wpdb->query( "ALTER TABLE `".$wpdb->prefix."ar_gwa_leads` ADD `lField1` VARCHAR( 250 ) default NULL ,ADD `lField2` VARCHAR( 250 ) default NULL ,ADD `lField3` VARCHAR( 250 ) default NULL ,ADD `lField4` VARCHAR( 250 ) default NULL ,ADD `lField5` VARCHAR( 250 ) default NULL" );
#  if($ar_gwa_debug=="ON") $wpdb->show_errors();
  }
 } else
  $ar_gwa_api_key = get_option('ar_gwa_api_key');

if(get_option('ar_gwa_popin')) $ar_gwa_popin='checked';  
if(get_option('ar_gwa_footerlist')) $ar_gwa_footerlist='checked';  

if(isset($_REQUEST['ar_gwa_submit_cb'])) {

if(isset($_REQUEST['ar_gwa_popin'])) {
$ar_gwa_popin = 'checked';
update_option('ar_gwa_popin',$ar_gwa_popin);
delete_option('ar_gwa_footerlist');
} else {
unset($ar_gwa_popin);
delete_option('ar_gwa_popin');
}
if(isset($_REQUEST['ar_gwa_footerlist'])) {
$ar_gwa_footerlist = 'checked';
update_option('ar_gwa_footerlist',$ar_gwa_footerlist);
delete_option('ar_gwa_popin');
} else {
unset($ar_gwa_footerlist);
delete_option('ar_gwa_footerlist');
}

#if(isset($_REQUEST['ar_gwa_disable']) || (file_exists(ABSPATH."/wp-content/plugins/GWASplash/GWASplash.php"))) {
if(isset($_REQUEST['ar_gwa_disable']) || (function_exists('admin_splash_gwa_main'))) {
unset($ar_gwa_popin);
delete_option('ar_gwa_popin');
unset($ar_gwa_footerlist);
delete_option('ar_gwa_footerlist');
}

if($_REQUEST['listid']) {
update_option('ar_gwa_popin_list',$_REQUEST['listid']);
}
if($_REQUEST['listid2']) {
update_option('ar_gwa_footer_list',$_REQUEST['listid2']);
}

  if((isset($_REQUEST['ar_gwa_no_spam']))) {
    $ar_gwa_no_spam = 'checked';
    update_option('ar_gwa_no_spam',$ar_gwa_no_spam,'');
  } else { 
    $ar_gwa_no_spam = '';//get_option('ar_gwa_no_spam');
    update_option('ar_gwa_no_spam','','');
  }
  if(isset($_REQUEST['ar_gwa_nospam'])) {
    $ar_gwa_nospam = strip_tags($_REQUEST['ar_gwa_nospam']);
    update_option('ar_gwa_nospam',$ar_gwa_nospam,''); 
  } else {
    $ar_gwa_nospam = '';
    update_option('ar_gwa_nospam',$ar_gwa_nospam,''); 
  }
} else {
   $ar_gwa_no_spam = get_option('ar_gwa_no_spam');
   $ar_gwa_nospam = stripslashes(get_option('ar_gwa_nospam')); 
}
if(get_option('ar_gwa_check'))
$botton_text = __("Unregistered",'argwa');
else
$botton_text = 'PROv'.$gwa_version_tag;

if(isset($_REQUEST['ar_gwa_smtp'])) {
 if(isset($_REQUEST['ar_gwa_smtp_auth'])) {
 update_option('ar_gwa_smtp_auth','checked');
 update_option('ar_gwa_smtp_user',$wpdb->escape($_REQUEST['ar_gwa_smtp_user']));
 update_option('ar_gwa_smtp_pass',$wpdb->escape($_REQUEST['ar_gwa_smtp_pass']));
 if($_REQUEST['ar_gwa_smtp_proto']!='')
 update_option('ar_gwa_smtp_srv',$wpdb->escape($_REQUEST['ar_gwa_smtp_proto']).'://'.$wpdb->escape($_REQUEST['ar_gwa_smtp_srv']));
 else
  update_option('ar_gwa_smtp_srv',$wpdb->escape($_REQUEST['ar_gwa_smtp_srv']));
 update_option('ar_gwa_smtp_port',$wpdb->escape($_REQUEST['ar_gwa_smtp_port']));
 update_option('ar_gwa_smtp_proto',$wpdb->escape($_REQUEST['ar_gwa_smtp_proto']));
 } else {
 update_option('ar_gwa_smtp_auth','unchecked');
 }

 if(isset($_REQUEST['ar_gwa_smtp_auth']) && isset($_REQUEST['ar_gwa_smtp_test'])) {
     if (! class_exists('PHPMailer')){
      include($phpmailerDir.'/class.phpmailer.php'); 
     }   
    $newsletter = new newsletter();
        $mail['method']='smtp';
    $mail['SMTPAuth']=true;
    $mail['Host'] = get_option('ar_gwa_smtp_srv');
    $mail['Username'] = get_option('ar_gwa_smtp_user');
    $mail['Password'] = get_option('ar_gwa_smtp_pass');
    $mail['From'] = $mail['recepientName'] = $mail['recepientMail'] = get_bloginfo('admin_email');
    $mail['FromName'] = 'FreeAutoresponder Plugin';
    $mail['subject'] = 'SMTP successfully enabled.';
    $mail['body'] = "Hi\r\n\r\nSMTP has been enabled for your plugin and this message was delivered using your newly configured relay. Check the message headers to verify this!\r\n\r\nRegards\r\nYour [GWA] Autoresponder Pro Plugin";
    $mails[] = $mail;
    $suc = $newsletter->SendMail($mails);    
    }
    if($suc) {
  echo '<div id="message" class="updated fade"><p>'.$i.__("SMTP tested successfully and was enabled.",'argwa').'</p></div>';
    } else if(isset($_REQUEST['ar_gwa_smtp_test'])) {
         update_option('ar_gwa_smtp_auth','unchecked');
  echo '<div id="message" class="updated fade"><p>'.$i.__("SMTP test FAILED and was NOT ENABLED.",'argwa').'</p></div>';
    }
}

#echo get_option('ar_gwa_smtp_srv');
$wrap = get_option('ar_gwa_wrap');
if(isset($_REQUEST['wsubmit']) && $_REQUEST['ar_gwa_wrap']>0)
update_option('ar_gwa_wrap',$_REQUEST['ar_gwa_wrap']);
else if(!$wrap) {
$wrap = 50;
update_option('ar_gwa_wrap',$wrap);
}
$ar_gwa_smtp_auth = get_option('ar_gwa_smtp_auth');
$ar_gwa_smtp_user = get_option('ar_gwa_smtp_user');
$ar_gwa_smtp_pass = get_option('ar_gwa_smtp_pass');
$ar_gwa_smtp_srv = get_option('ar_gwa_smtp_srv');
$ar_gwa_smtp_srv = preg_replace("/^\w\w\w:\/\//","",$ar_gwa_smtp_srv);
if($ar_gwa_smtp_srv=='') $ar_gwa_smtp_srv = get_option('ar_gwa_smtp_srv');
$ar_gwa_smtp_port = get_option('ar_gwa_smtp_port');
$ar_gwa_smtp_proto = get_option('ar_gwa_smtp_proto');
if(strpos($ar_gwa_smtp_proto,'ls'))
$proto1 = ' selected';
else if(strpos($ar_gwa_smtp_proto,'sl'))
$proto2 = ' selected';
else
$proto0 = ' selected';
$proto = '<select name="ar_gwa_smtp_proto">';
$proto .= '<option value=""'.$proto0.'>----</option>';
if($phpmailerDir=='PHP5') {
$proto .= '<option value="tls"'.$proto1.'>tls://</option>';
$proto .= '<option value="ssl"'.$proto2.'>ssl://</option>';
}
$proto .= '</select>';
if(strpos($ar_gwa_smtp_port,'65'))
$port3 = ' selected';
else if(strpos($ar_gwa_smtp_port,'86'))
$port4 = ' selected';
else if(strpos($ar_gwa_smtp_port,'87'))
$port6 = ' selected';
else if($ar_gwa_smtp_port=='2525')
$port5 = ' selected';
else if(strpos($ar_gwa_smtp_port,'6'))
$port2 = ' selected';
else $port1 = ' selected';
$port = '<select name="ar_gwa_smtp_port">';
$port .= "<option$port1>25</option>";
$port .= "<option$port5>2525</option>";
$port .= "<option$port2>26</option>";
if($phpmailerDir=='PHP5') {
$port .= "<option$port3>465</option>";
$port .= "<option$port4>586</option>";
$port .= "<option$port6>587</option>";
}
$port .= "</select>";
if($phpmailerDir=='PHP4') {
$port .= "<br /><small style='color:#f00;'>To connect by ssl (smtps) upgrade to PHP5.</small>";
}
if($_REQUEST['ar_gwa_wp']=="wp_head" && get_option('ar_gwa_wp')!='wp_head') {
remove_action('template_redirect','ar_gwa_signup');
add_action('wp_head','ar_gwa_signup');
update_option('ar_gwa_wp','wp_head');
} else if($_REQUEST['ar_gwa_wp']=='template_redirect' && get_option('ar_gwa_wp')!='template_redirect'){
remove_action('wp_head','ar_gwa_signup');
add_action('template_redirect','ar_gwa_signup');
update_option('ar_gwa_wp','template_redirect');
} 
if(get_option('ar_gwa_wp')=='wp_head') $wp1='selected'; else $wp2='selected';



if($_REQUEST['ar_gwa_char']=="utf" && get_option('ar_gwa_char')!='UTF-8') {
update_option('ar_gwa_char','UTF-8');
update_option('ar_gwa_enc','8bit');
} else if($_REQUEST['ar_gwa_char']=='iso' && get_option('ar_gwa_char')!='ISO-8859-1'){
update_option('ar_gwa_char','ISO-8859-1');
update_option('ar_gwa_enc','8bit');
} else if($_REQUEST['ar_gwa_char']=='iso2' && get_option('ar_gwa_char')!='ISO-8859-2'){
update_option('ar_gwa_char','ISO-8859-2');
update_option('ar_gwa_enc','8bit');
} else if($_REQUEST['ar_gwa_char']=='win' && get_option('ar_gwa_char')!='Windows-1255'){
update_option('ar_gwa_char','Windows-1255');
update_option('ar_gwa_enc','8bit');
}  else if($_REQUEST['ar_gwa_char']=='gbk' && get_option('ar_gwa_char')!='GB2312'){
update_option('ar_gwa_char','GB2312');
update_option('ar_gwa_enc','7bit');
} else if($_REQUEST['ar_gwa_char']=='jpn' && get_option('ar_gwa_char')!='ISO-2022-JP'){
update_option('ar_gwa_char','ISO-2022-JP');
update_option('ar_gwa_enc','7bit');
}

if(get_option('ar_gwa_char')=='UTF-8') $ch1='selected'; else
if(get_option('ar_gwa_char')=='Windows-1255') $ch3='selected'; else
if(get_option('ar_gwa_char')=='GB2312') $ch4='selected'; else 
if(get_option('ar_gwa_char')=='ISO-8859-2') $ch6='selected'; else 
if(get_option('ar_gwa_char')=='ISO-2022-JP') $ch5='selected'; else $ch2='selected';
#if(isset($_REQUEST['wsubmit'])){
if(isset($_REQUEST['ar_gwa_seal']) & !(preg_match('/Sign-up at/',$_REQUEST['ar_gwa_seal']))){
update_option('ar_gwa_seal',$_REQUEST['ar_gwa_seal']);
} else {
update_option('ar_gwa_seal','');
}
if(get_option('ar_gwa_api_key') && get_option('ar_gwa_check')>2) {
$botton_text = 'BAD KEY VALUE:#'.get_option('ar_gwa_check');
$update_message = __("A valid API key is required for proper functioning of the Pro version.",'argwa').' '."<a href='http://freeautoresponder.biz'>".__("Login to get your key",'argwa').'</a>.<br />';
} else if(get_option('ar_gwa_check')>2) {
$botton_text = __("ENTER API KEY",'argwa');
$update_message = __("A valid API key is required for proper functioning of the Pro version. Pro users can always get your key and the latest version of the plugin by logging in at",'argwa')." <a href='http://freeautoresponder.biz?page=login'>FreeAutoresponder.biz</a><br />";
}
$ver = get_option('ar_gwa_new_ver');

if((int)$ver != 0 && $ver != $gwa_version_tag)
    $update_message .= '<strong style="color:#666">'.__("There is a new version available.",'argwa').' (v'.get_option('ar_gwa_new_ver').')</strong><br /><br />';//.'<br /><a href="'.WP_PLUGIN_URL'./autoresponder-gwa/ar_gwa_update.php?'.$gwa_version_tag.'">';.__("Click here to update now.",'argwa').'</a></strong><br /><br />';
$month = $_REQUEST['ar_gwa_month'];
$year = $_REQUEST['ar_gwa_year'];
if($month=='')
$month = date("n");
if($year=='')
$year = date("Y");
for($i=59;$i>-1;$i--)
$min .= '<option>'.$i.'</option>';
for($i=23;$i>-1;$i--)
$hr .= '<option>'.$i.'</option>';
echo '<div id=""><div class="wrap">';
echo '<table border=0 style="width:100%;min-width:960px;" border="1" cell-padding="0" cell-spacing="0" class="wp-list-table"><tr><td valign="top"><div style="position:relative;float:left;width:50%">';
echo '<form action="#" method="POST"><input type="hidden" name="act" value="main">';
echo '<div style="background-color: rgb(228, 242, 253);-moz-border-radius: 15px;border-radius: 15px;padding:15px;margin-right:10px;">'.argwa_get_note('1').'<strong><span style="color:'.$ar_color.';">';
printf(__("Next Scheduled Mailing in: %2.1f hours.",'argwa'),round(((((wp_next_scheduled('ar_gwa_daily_event')-time())/60)/60)),1));
echo '</span></strong><br />'; $ofs = ((int)get_option('gmt_offset'))*60*60;$stime=(((int)wp_next_scheduled('ar_gwa_daily_event'))+($ofs));$nstime=(((int)wp_next_scheduled('ar_gwa_regular_event'))+($ofs));printf(__('Send Time: %s','argwa'),date('l jS \of F Y h:i:s A',$stime));
echo '</span><br />'.sprintf(__("Current Time: %s",'argwa'),date_i18n('l jS \of F Y h:i:s A')).'<br /><span style="color:'.$ar_color.';">'.sprintf(__("Next Queue RUN: %s",'argwa'),date('l jS \of F Y h:i:s A',$nstime)).'</span><br />'.__("Mail in Queue:",'argwa')."&nbsp;".sprintf("<span style='font-weight:bolder;color:#008000'>%d",$wpdb->get_var("SELECT COUNT(*) newsletterQID FROM ".$wpdb->prefix."ar_gwa_queue"))."&nbsp;".__(' Messages waiting to be sent.','argwa').'</span><br /><input type="submit" name="sched2" value="'.__("Set Send Time",'argwa').'" class="button"> '.__("in",'argwa').' <select name="hr">'.$hr.'</select> '.__("hours",'argwa').' <select name="min">'.$min.'</select> '.__("minutes",'argwa').'.<br /><small><strong>'.__("Send Time",'argwa').'</strong> - '.__("Time new messages are queued each day.",'argwa').'</small><br /></div><br />';
echo '<div style="background-color: rgb(228, 242, 253);-moz-border-radius: 15px;border-radius: 15px;padding:15px;margin-right:10px;margin-top:-10px;">'.argwa_get_note('4').'<div style=""><p style="margin-top:-15px;padding-right:30px;">'.__("Footer will be added to the bottom of every email.",'argwa').' '.__("Great for easy CAN SPAM Compliance.",'argwa').' '.__("Enter the unsubscribe link message for your newsletters here.",'argwa')." ".__("The other messages will be displayed after subscribing.",'argwa').' '.__("Your note will be inserted after the script status output and before existing page content.",'argwa').' '.__('Or click UPDATE on the ','argwa').'<a href="?page=ar_gwa_lists">'.__('Lists Page','argwa').'</a> '.__("for each list.",'argwa').'</p><input type="hidden" name="ar_gwa_submit_cb" value="1"><b>'.__("Enter custom footer.",'argwa').'</b><br /><textarea name="ar_gwa_nospam" cols=48>'.$ar_gwa_nospam.'</textarea><br /><input type="checkbox" name="ar_gwa_no_spam" value="1" '.$ar_gwa_no_spam.'>&nbsp;'.__("Enable custom footer. This overrides all individual list footer settings.",'argwa').'<br /><br /><b>'.__("Enter custom unsubscribe text.",'argwa').'</b><br /><textarea cols=48 name="ar_gwa_unsub">'.stripslashes(stripslashes(get_option('ar_gwa_unsub'))).'</textarea><br /><input onclick="return alert(\'You can have all your email flagged as spam if you do not include a direct unsubscribe link in every message. Be sure you have read and understand the US CAN-SPAM Act.\');" type="checkbox" value="ON" name="ar_gwa_addsub"';
if(get_option('ar_gwa_addsub')==1) echo ' checked';
echo '>&nbsp;'.__("Add unsubscribe link to all messages.",'argwa').'<br /><br /><b>'.__("Enter success response.",'argwa').'</b><br /><textarea cols=48 name="add_lead">'.stripslashes(stripslashes(stripslashes(get_option('ar_gwa_addlead')))).'</textarea><br /><br /><b>'.__("Enter unsubscribe response.",'argwa').'</b><br /><textarea cols=48 name="rmv_lead">'.stripslashes(stripslashes(stripslashes(get_option('ar_gwa_rmvlead')))).'</textarea><br /><br /><b>'.__("Enter subscription failure text.",'argwa').'</b><br /><textarea name="bad_lead" cols=48>'.stripslashes(stripslashes(stripslashes(get_option('ar_gwa_badlead')))).'</textarea><br /><input type="submit" name="update" value="UPDATE" class="button"></div>';
echo '</div>';
#echo '</div>';
if(!(get_option('ar_gwa_popfg_'.get_option('ar_gwa_popin_list'))) && !(get_option('ar_gwa_sldfg_'.get_option('ar_gwa_footer_list')))) {
$msg="<em STYLE='FONT-WEIGHT:BOLD;font-size:8pt'><a href='?page=ar_gwa_lists'>".__("You need to setup your fly-in forms before enabling this option.",'argwa')."</a></EM><br />";
} else if(function_exists('admin_splash_gwa_main')) {
$msg = "<em STYLE='COLOR:#f00; FONT-WEIGHT:BOLD;font-size:8pt'>Disabled!</em> The <a href='options-general.php?page=GWASplash/GWASplash.php'>[GWA] Splash Page Maker plugin</a> is enabled.<br />";
$d = 'disabled';
}
if(!isset($_COOKIE["GWAADMINPOP"])) {
$testbutton = '<input type="submit" class="button" value="'.__("TEST",'argwa').'" name="popintest"  '.$d.'>';
} else {
$testdesc = '<span style="color:#f00;">'.__("For easy testing your fly-in display will appear with each page loaded FOR YOU ONLY until fly-in test is cancelled.",'argwa').'</span>';
echo '<div id="message" class="updated fade" style="width:400px;margin-top:10px;margin-bottom:0px;"><p>'.__("<strong>Fly-in Test Enabled.</strong> Click the button on the FLY-IN HTML tab again to cancel the forced display of your fly-in on your blog.",'argwa')."<br>".$testdesc.'</p></div>';
$testbutton = '<input style="color:#f00;border-color:#f00" type="submit" class="button" value="'.__("CANCEL",'argwa').'" name="poptest">';
}

echo '<div style="margin-top:10px;background-color: rgb(228, 242, 253);-moz-border-radius: 15px;border-radius: 15px;padding:15px;margin-right:10px;">'.argwa_get_note('3').$msg.'<strong>'.__("SELECT LIST FOR FLY-IN AD.",'argwa').'</strong> '.ar_gwa_buildlistselect(get_option('ar_gwa_popin_list')).'<br /><input id="popinlist" type="checkbox" name="ar_gwa_popin" value="checked" '.$ar_gwa_popin.' onfocus="document.getElementById(\'footerlist\').checked=false" '.$d.'> '.__("Display Fly-in to blog visitors on first page loaded.*",'argwa').'<br /><br /><strong>'.__("SELECT LIST FOR FOOTER AD.",'argwa').'</strong> '.ar_gwa_buildlistselect(get_option('ar_gwa_footer_list'),'2').'<br /><input id="footerlist" type="checkbox" name="ar_gwa_footerlist" value="checked" '.$ar_gwa_footerlist.' onfocus="document.getElementById(\'popinlist\').checked=false" '.$d.'> '.__("Display Footer Ad to blog visitors on first page loaded.*",'argwa').'<br /><br />'.__("Update form display on <a href='?page=ar_gwa_lists'>List Details</a> page.",'argwa').'&nbsp;<input type="submit" name="update" value="UPDATE" class="button" '.$d.'>&nbsp;'.$testbutton.'<br><small>* '.__('Only one Ad-Type (Fly-in/Footer Ad) can be active.','argwa').'</small></div></form>';

#echo '</td><td align="left" valign="top" style="padding-left:5px;">';
echo "</div><div style='float:left;'>";


echo '<form action="#" method="POST" name="ARGWA">
<table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse; padding: 10px;" bordercolor="#111111;width:440px;"><tr><td>';
echo '<div style="color:#000;text-align:left;width:400px;">';
echo '<div style="background-color: rgb(228, 242, 253);-moz-border-radius: 15px;border-radius: 15px;padding:15px;margin-right:10px;">'.argwa_get_note('5').__("Total Lists:",'argwa')."&nbsp;".$stat['ttl_lists'].'<br />'.__("Total Leads:",'argwa')."&nbsp;".$stat['ttl_leads'].'<br>'.$stat['lst_list'].'</p></div>';
if(class_exists('ar_gwa_calender')) echo '<div style="background-color: rgb(228, 242, 253);-moz-border-radius: 15px;border-radius: 15px;padding:15px;margin-right:10px;margin-top:10px;">'.admin_ar_gwa_calender($year,$month).'</div>';
echo '<div style="position:relative;float:left;background-color: rgb(228, 242, 253);-moz-border-radius: 15px;border-radius: 15px;padding:15px;margin-right:10px;margin-top:10px;">'.__("Pro API Key:",'argwa').'<br />';
echo '<form method="POST" action="?page=ar_gwa_main"><input type="textbox" name="ar_gwa_api_key" size="28" value="'.$ar_gwa_api_key.'">&nbsp;&nbsp;<input type="submit" value="'.$botton_text.'" class="button" name="ar_gwa_api_submit"><br />'.$update_message;
if(!get_option('ar_gwa_check'))
echo '<input type="checkbox" name="ar_gwa_cb" value="1" '.get_option('ar_gwa_cb').'>&nbsp;<small>'.__("Check this box to include your affiliate link in your subscription forms and at the bottom of all your mailings.",'argwa').'</small><br /><input type="checkbox" name="ar_gwa_delete" value="checked" '.get_option('ar_gwa_delete').'>&nbsp;<small>'.__("DATA SECURITY: <i>You must check this box to delete data when uninstalling this plug-in.</i>",'argwa').'</small>';
echo '</div>';
$spf=stripslashes(get_option('ar_gwa_seal'));if(!$spf || preg_match("/^Sign-up at/",$spf)){$spf_link = "<span style='font-size:11px;'>".'<a href="#" style="text-decoration:none;" onclick="document.getElementById(\'the_div\').style.display=(document.getElementById(\'the_div\').style.display== \'block\')?\'none\':\'block\';" title="Click to add your verification link.">'."Be CANSPAM Compliant</a> with a membership at <a href='http://no-spam-zone.biz' target=\"_nszblank\" title='No-Spam-Zone.biz Membership List Verification Website'>No-Spam-Zone.biz.</a>.</span>";
$spf="Sign-up at No-Spam-Zone.biz to get your verify button code and insert here to add to your subscription form.";} else {
$spf_link = "<span style='font-size:11px;'>Thank you for operating an ethical mailing list.</span>";
}
echo '<div style="position:relative;float:left;background-color: rgb(228, 242, 253);-moz-border-radius: 15px;border-radius: 15px;margin-right:10px;padding:15px;margin-top:10px;width:360px"><a href="#" style="text-decoration:none;" onclick="document.getElementById(\'the_div\').style.display=(document.getElementById(\'the_div\').style.display== \'block\')?\'none\':\'block\';" title="Click to add your verification link.">+</a>&nbsp;'.$spf_link.'</div><div style="position:relative;float:left;background-color: rgb(228, 242, 253);-moz-border-radius: 15px;padding:15px;border-radius: 15px;margin-right:10px;width:360px;margin-top:10px;display:none;" id="the_div"><small style="color:#d54e21;">Do you have everything you need to be sure your Newsletter is FULLY CANSPAM COMPLIANT? Get it all in seconds and start showing every potential subscriber you\'re an ethical newsletter operator today.</small><br /><br /><form method="POST" action="?page=ar_gwa_main">';

echo '<a href="http://no-spam-zone.biz/verify.php?NSZ5LVZUIXFPTMI4FJS6RX89JV5N38VU52QHF8HPNPSQXN4ZTXUYK62NH5GFOJ" target="_blank"><img src="http://no-spam-zone.biz/image/nsz_shieldx.gif" align="right" height="82" width="77" border="0"></a><textarea name="ar_gwa_seal" cols=31 rows=3 style="border:solid 1px #21759b">'.$spf.'</textarea><br /><input type="submit" value="UPDATE" class="button" name="ar_gwa_api_submit">';
echo '</div></div></td></tr></table><input type="hidden" name="act" value="main"></form><!-- [GWA] AutoResponder End -->';
if(!get_option('ar_gwa_check')) {
echo '<div style="background-color: rgb(228, 242, 253);-moz-border-radius: 15px;border-radius: 15px;padding:15px;margin-right:10px;width:360px;margin-top:10px;">'.argwa_get_note('7').'<p align="left" style="margin-top:-14px;"><form method="POST" action=""><input type="checkbox" name="ar_gwa_smtp_auth" value="checked" '.$ar_gwa_smtp_auth.'> '.__("Activate SMTP Relay.",'argwa').' '.__("Send SMTP Test",'argwa').': <input type="checkbox" name="ar_gwa_smtp_test" checked><br /><table border=0><tr><td>'.__("Server:",'argwa').'</td><td>'.$proto.'<input type="text" name="ar_gwa_smtp_srv" size=20 value="'.$ar_gwa_smtp_srv.'">'.':'.$port.'</td></tr>
<tr><td>'.__("Username:",'argwa').'</td><td><input type="text" name="ar_gwa_smtp_user" size=22 value="'.$ar_gwa_smtp_user.'"></td></tr>
<tr><td>'.__("Password:",'argwa').'</td><td><input type="password" name="ar_gwa_smtp_pass" size=22 value="'.$ar_gwa_smtp_pass.'"> <input type="submit" value="SMTP" class="button" name="ar_gwa_smtp"></td></tr></table></form></p></div>';
if($ar_gwa_smtp_auth!='checked')
echo '<div style="width:378px;border: solid 1px #ff00c9;padding:6px; background-color:#ffffe0;margin-top:10px;">'.__("Use SMTP to avoid your host's mail limitations and increase email deliverability.",'argwa')."&nbsp;".'<a href="http://hub.freeautoresponder.biz/smtp.html" target="_new" title="'.__("Opens in new window.",'argwa').'"><em>'.__("Find out more.",'argwa').'</em></a></div>';
echo '<div style="background-color: rgb(228, 242, 253);-moz-border-radius: 15px;border-radius: 15px;padding:15px;margin-right:10px;width:360px;margin-top:10px;"><form action="#" method="POST">'.argwa_get_note('8').'<p align="left" style="margin-top:-14px;"><strong>'.__("Intelligent-Queue Throttle Settings",'argwa').'</strong>&nbsp;<input type="submit" name="submit" value="'.__("Update",'argwa').'" class="button"></p><table border=0><tr><td>'.__("Max script run-time in seconds.",'argwa').' (1-300):</td><td><input type="text" size=2 name="arThrottle" value="'.stripslashes(get_option('ar_gwa_throttle')).'"></td></tr>
<tr><td>'.__("Messages sent per queue run.",'argwa').' (1-100):</td><td><input type="text" size=2 name="arMpr" value="'.stripslashes(get_option('ar_gwa_mpr')).'"></td></tr>
<tr><td>'.__("Pause between queue runs.",'argwa').' (1-60):</td><td><input type="text" size=2 name="arRun" value="'.stripslashes(get_option('ar_gwa_run')).'"></td></tr></table><input type="hidden" name="act" value="main">
</form></div>';
}
echo '<div style="background-color: rgb(228, 242, 253);-moz-border-radius: 15px;border-radius: 15px;padding:15px;margin-right:10px;width:360px;margin-top:10px;">'.argwa_get_note('9').'<form action="#" method="POST"><table border=0>
<tr><td><strong>'.__("Additional Global Settings",'argwa').'</strong>&nbsp;<input type="submit" name="wsubmit" value="'.__("Update",'argwa').'" class="button"></td></tr>';
if(!class_exists('ar_gwa_single') && file_exists(dirname(__FILE__).'/ar_gwa_single.php')) include_once(dirname(__FILE__).'/ar_gwa_single.php');
if(class_exists('ar_gwa_single')) {
$opt = new ar_gwa_single();
$single_opt = "<tr><td>".$opt->admin_ar_gwa_optin()."</td></tr>";
}

echo '<tr><td>'.__("Email Text Wrapping",'argwa').': <input type="text" size="2" value="'.$wrap.'" name="ar_gwa_wrap"><br /><small>'.__("CHAR per line for PLAIN-TEXT emails.",'argwa').'</small><br /></td></tr><tr><td><strong>WP_HOOK*</strong>&nbsp;&nbsp;<select name="ar_gwa_wp"><option '.$wp1.'>wp_head</option><option '.$wp2.'>template_redirect</option></select><br /><small>* '.__("If you have problems with user page redirects after form submission try selecting a different hook above.",'argwa').'</small></td></tr><tr><td><strong>CHAR-SET</strong>&nbsp;&nbsp;<select name="ar_gwa_char"><option value="utf" '.$ch1.'>UTF-8</option><option value="iso" '.$ch2.'>ISO-8859-1</option><option value="iso2" '.$ch6.'>ISO-8859-2</option><option value="win" '.$ch3.'>Windows-1255</option><option value="gbk" '.$ch4.'>GB2312</option><option value="jpn" '.$ch5.'>ISO-2022-JP</option></select>&nbsp<small>('.get_option('ar_gwa_enc').')</small><br /><small>* '.__("If you have problems with special characters in your messages try selecting a different encoding above.",'argwa').'</small></td></tr>'.$single_opt.'</table></form></div>';
echo '</td></tr></table>';
echo '</div>'.$ctag;
}
 
function admin_ar_gwa_messages($msg=NULL) {
global $wpdb,$ar_gwa_debug;
if($ar_gwa_debug=="ON") $wpdb->show_errors();
if(isset($_REQUEST['listid']) && !isset($_REQUEST['RESET'])) $qual = "WHERE mLID='".$_REQUEST['listid']."'";
$arSql = "SELECT * FROM " . $wpdb->prefix . "ar_gwa_msg $qual ORDER BY mDay";
$res = $wpdb->get_results($arSql);
if($res) 
{
	echo '<div id=""><div id=""><div id=""><div class="wrap"><h2>'.__("Manage Messages",'argwa').'</h2>';
  echo $masg;
?>
<form action="?page=ar_gwa_edit_message" method="POST"><?php echo ar_gwa_buildlistselect($_REQUEST['listid']);?><input type="submit" name="SUBMIT" value="FILTER" class="button"></form>
<br class="clear" />
<?php
	echo '<br /><form name="mForm" method="post" action="?page=ar_gwa_edit_message"><input type="submit" class="button" value="'.__("Add New Message",'argwa').'" name="admin_ar_gwa_add_message">&nbsp;&nbsp;<input type="submit" class="button" value="'.__("Send Message",'argwa').'" name="admin_ar_gwa_send_message"></form><p>'.__("Click buttons above to add or send a message. Click message subject to edit. Select messages and click to delete.",'argwa').'</p>'.argwa_get_note('31').'<form method="post" action="?page=ar_gwa_edit_message" id="armsgs-filter"><table>';
?>
<table class="widefat wp-list-table">

	<thead>
	<tr>

	<th scope="col" class="check-column" align="left"><input type="checkbox" onclick="checkAll(document.getElementById('armsgs-filter'));" /></th>
	<th scope="col"><?php _e("List",'argwa');?></th>
	<th scope="col"><?php _e("Day",'argwa');?></th>
	<th scope="col"><?php _e("Subject",'argwa');?></th>
	<th scope="col"><?php _e("Type",'argwa');?></th>
  <?php if(class_exists('ar_gwa_attach'))
    echo '<th scope="col">'.__("Attach",'argwa').'</th>';
    ?>
	</tr>
	</thead>
	<tbody>
	<tr id='leads-1' class='alternate author-self status-publish' valign="top">
<?php	
	foreach($res as $row)
	{
		echo '<tr><td><input type="checkbox" name="mID[]" value="'.$row->mID.'"></td><td align="left">';
		echo ar_gwa_getlistname($row->mLID),' (#'.$row->mID.')</td><td>';
		echo $row->mDay,$row->mDate.'</td><td>';
		echo '<a href="?page=ar_gwa_edit_message&mDay='.$row->mDay.'&mID='.$row->mID.'&listid='.$row->mLID.'" title="'.__("Click to edit message",'argwa').'">'.stripslashes($row->mSubject),'</a></td><td>';
		echo '<strong>'.$row->mType,'</strong></td>';
    if(class_exists('ar_gwa_attach') && isset($row->mAttach) && ($tcx = new ar_gwa_attach))
		echo '<td><strong>'.$tcx->mAttach($row->mAttach),'</strong></td>';
	}
	echo '</tr></table><p>&nbsp;</p>';
	echo '<p><input type="submit" class="button" value="'.__("Delete Checked Above",'argwa').'">';
	echo '<input type="hidden" name="act" value="del"></p>';
	echo '</form>';
?>

<?php
  } else {
  echo '<div id=""><div id=""><div id=""><div class="wrap"><h2>'.__("Manage Messages",'argwa').'</h2>'.__("No Records",'argwa'); ?>
<br class="clear" />
<?php
	echo '<br /><form name="mForm" method="post" action="?page=ar_gwa_edit_message"><input type="submit" class="button" value="'.__("Add New Message",'argwa').'" name="admin_ar_gwa_add_message">&nbsp;&nbsp;<input type="submit" class="button" value="'.__("Send Message",'argwa').'" name="admin_ar_gwa_send_message"></form><p>'.__("Click buttons above to add or send a message. Click message subject to edit. Select messages and click to delete.",'argwa').'</p>';
  }
#echo '</div><!-- wpbody --></div><!-- wpcontent --></div><!-- wpwrap -->';
 }
 
function admin_ar_gwa_add_message() {
global $wpdb,$ctag,$ar_gwa_debug;
if($ar_gwa_debug=="ON") $wpdb->show_errors();
$g_error = array();
if(!$_REQUEST['mBody'])
$_REQUEST['mBody']='';
if(!$_REQUEST['mType'])
$_REQUEST['mType']='';
if(!$_REQUEST['act'])
$_REQUEST['act']='';
if(class_exists('ar_gwa_attach') && ($tcc = new ar_gwa_attach) && isset($_FILES['ar_gwa_filename']))
  $masg = $tcc->ar_gwa_attach_message();
if($_REQUEST['act'] == 'add')
{
	if(!$_REQUEST['mSubject'] || !$_REQUEST['mBody']) { $g_error[''] = 20; }
	if((($_REQUEST['mDay'] < 0 || $_REQUEST['mDay'] > 999) && $_REQUEST['mDate']=='')) { $g_error[] = 22; }
	if(!isset($_REQUEST['listid']) || ($_REQUEST['listid']==0)) { $g_error[] = 24; }  
	if(!isset($_REQUEST['mDate'])){
		$qry = "SELECT * FROM ".$wpdb->prefix."ar_gwa_msg WHERE mDay = '".$_REQUEST['mDay']."' AND mLID = '".$_REQUEST['listid']."'";
		$res = $wpdb->get_results($qry);		
		if($res) { $g_error[] = 21; }
	}	else
	{
		$qry = "SELECT * FROM ".$wpdb->prefix."ar_gwa_msg WHERE mDate = '".$_REQUEST['mDate']."' AND mLID = '".$_REQUEST['listid']."'";
		$res = $wpdb->get_results($qry);		
		if($res) { $g_error[] = 21; }
	}
if(isset($_REQUEST['mTop']) || isset($_REQUEST['mBot'])) {
 $ararg1 = $wpdb->escape($_REQUEST['mTop']);
 $ararg2 = $wpdb->escape($_REQUEST['mBot']);
 if((isset($ararg1) || isset($ararg2))) {
  if(class_exists('ar_gwa_template') && ($tb = new ar_gwa_template))
   list($top,$bot) = $tb->addAction($ararg1,$ararg2);
 }
}
if(!count($g_error))
{
if($_REQUEST['ar_gwa_filename']) $attach = mysql_real_escape_string($_REQUEST['ar_gwa_filename']);		

if(class_exists('ar_gwa_attach')) {
$mattach_field = ",mAttach";
$mattach = ",'$attach'";
}

if(class_exists('ar_gwa_newsletter') && isset($_REQUEST['nlTop'])) {
$mnews_field = ",nlid";
$mnews = ",'{$_REQUEST['nlTop']}'";
}

if($_REQUEST['mDay']!='')
		$qry = "INSERT INTO ".$wpdb->prefix."ar_gwa_msg(mSubject, mBody, mDay, mType, mLID $mattach_field $mnews_field) VALUES('".$wpdb->escape($_REQUEST['mSubject'])."','".$top.$wpdb->escape($_REQUEST['mBody']).$bot."','".$wpdb->escape($_REQUEST['mDay'])."','".$_REQUEST['mType']."','".$_REQUEST['listid']."' $mattach $mnews)";
else if($_REQUEST['mDate']!='')
		$qry = "INSERT INTO ".$wpdb->prefix."ar_gwa_msg(mSubject, mBody, mDate, mType, mLID $mattach_field $mnews_field) VALUES('".$wpdb->escape($_REQUEST['mSubject'])."','".$top.$wpdb->escape($_REQUEST['mBody']).$bot."','".$wpdb->escape($_REQUEST['mDate'])."','".$_REQUEST['mType']."','".$_REQUEST['listid']."' $mattach $mnews)";
    $wpdb->query($qry);
		admin_ar_gwa_messages();
		exit;
	} else {
	ar_gwa_showError($g_error);
	}
} 
if(!file_exists(ABSPATH.'wp-content/plugins/autoresponder-gwa/gwa-xinha.txt')){

if (function_exists('wp_tiny_mce')) wp_tiny_mce( false ,
array(
"editor_selector" => "editorContent",
"plugins" => "spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
"theme_advanced_buttons1" => "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
"theme_advanced_buttons2" => "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
"theme_advanced_buttons3" => "hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen,|,spellchecker",
"extended_valid_elements" => "form[*],div[*],style[*],p[*],table[*],td[*]",
"skin" => "o2k7",
"skin_variant" => "silver",)
);
?>
<script type="text/javascript">
<!--
function toggleEditor(id) {
	if (!tinyMCE.getInstanceById(id))
		tinyMCE.execCommand('mceAddControl', false, id);
	else
		tinyMCE.execCommand('mceRemoveControl', false, id);
}
toggleEditor('editorContent');
-->
</script>
<?php } ?>
<div id="">
<div id="">
<div class="wrap" style="">
<form name="mForm" method="post" action="?page=ar_gwa_edit_message">
<h2><?php _e("Add Message",'argwa');?></h2>
<?php echo '.'.$masg;?>
<?php if($_REQUEST['mDate'] =='' && (class_exists('ar_gwa_calender') && ($tcb = new ar_gwa_calender))) echo '<p>'.$tcb->message_text().'</p>'; ?>
<table align="center">
<tr>
<td><?php _e("LIST",'argwa');?></td>
<td><?php echo ar_gwa_buildlistselect($_REQUEST['listid']) ?> <strong style="color:red"><?php _e("* SELECT LIST *",'argwa');?></strong></td>
</tr>
<?php
if(class_exists('ar_gwa_template') && ($tb = new ar_gwa_template))
   echo $tb->addForm();
if(class_exists('ar_gwa_newsletter') && ($te = new ar_gwa_newsletter)) echo $te->addForm($_REQUEST['listid'],$_REQUEST['nlTop']);

if($_REQUEST['mDate'] !='' && (class_exists('ar_gwa_calender') && ($tcb = new ar_gwa_calender))) {
  echo		'<tr><td>'.__("Date",'argwa').'</td>';
   echo $tcb->addDateForm().'</tr>';
  } else {
?>
	<tr>
		<td><?php _e("Day",'argwa');?></td>
		<td><input type="text" name="mDay" style="width:100px;" maxlength="3" value=""> (0 - 999)</td>
	</tr><?php  
  }
?>
	<tr>
		<td>TYPE</td>
		<td>
		<select name="mType" style="width:100px;" onchange="toggleEditor('editorContent')"/>
<?php if(!file_exists(ABSPATH.'wp-content/plugins/autoresponder-gwa/gwa-xinha.txt')){ ?>
		<option value="text" ><?php _e("PLAIN TEXT",'argwa');?></option>
<?php } ?>
		<option value="html" selected><?php _e("HTML",'argwa');?></option>
		</select>
		</td>
	</tr>
	<tr>
		<td><?php _e("SUBJECT",'argwa');?></td>
		<td><input type="text" name="mSubject" style="width:325px;" maxlength="250" value="<?php echo $_REQUEST['mSubject'];?>"><?php echo argwa_get_note('43');?></td>
	</tr>
<tr>
		<td>&nbsp;</td><td style="background-color:#e4f2fd;border:solid 1px #f00;padding:5px;width:450px;"><?php _e('<strong>We HATE SPAM!</strong> And so does the FTC. Fines for sending spam can be as high as $11,000 per violation! Protect yourself. Know the law.','argwa');?><br><a href="http://www.ftc.gov/bcp/edu/pubs/business/ecommerce/bus61.shtm" title="<?php _e('Opens in a new Window.','argwa');?>" target="_blank"><?php _e('Click here to see the Can-Spam Act.','argwa');?></a></td>
</tr>	
	<tr>
		<td valign="top"><?php _e("BODY",'argwa');?></td>
		<td><textarea id="editorContent" name="mBody" style="width:600px; height:400px;"><?php echo $_REQUEST['mBody'];?></textarea></td>
	</tr>
<tr>
		<td>&nbsp;</td><td style="background-color:#e4f2fd;border:solid 1px #22ff55;padding:5px;width:450px;"><?php _e('<strong>Personalize your Messages!</strong> <span style="color:#f00">*USE ONLY THE TAGS BELOW*</span><br />Use these custom tags when mailing your lists from this page.','argwa');?> <strong style="font-size:9pt;"> <&#63;Name&#63;> <&#63;Email&#63;> <&#63;Unsubscribe&#63;> <&#63;Archive&#63;> <&#63;Field1&#63;> <&#63;Field2&#63;> <&#63;Field3&#63;> <&#63;Field4&#63;> <&#63;Field5&#63;> <?php if(file_exists(dirname(__FILE__).'/ar_gwa_user_edit.php'))echo "<&#63;Update&#63;>";?></strong></td>
</tr><tr><td><br /></td><td><input name="admin_ar_gwa_add_message" type="submit" class="button" value="<?php _e('Add Message','argwa');?>"><?php if(class_exists('ar_gwa_attach')) { echo "&nbsp;<span style='color:#00f;font-weight:bold;'>".__("ATTACH FILE:",'argwa')."</span>&nbsp;".admin_ar_gwa_attach().''; } ?></td></tr></table><input type="hidden" name="act" value="add"></form><div style="margin-left:60px;margin-top:10px;"><?php if(class_exists('ar_gwa_attach') && ($tcc = new ar_gwa_attach)) $tcc->ar_gwa_upload(); ?><?php
}

function admin_ar_gwa_edit_message() {
#print_r($_FILES);exit;
global $wpdb,$ctag,$ar_gwa_debug;
if($_REQUEST['admin_ar_gwa_add_message']!="" || ($_REQUEST['mDate']!='' && $_REQUEST['act'] != 'edit')) admin_ar_gwa_add_message();
elseif($_REQUEST['admin_ar_gwa_send_message']!="" || $_REQUEST['testmessage']!="") admin_ar_gwa_email_leads();
elseif($_REQUEST['admin_ar_gwa_queue']!="") admin_ar_gwa_queue();
elseif($_REQUEST['ar_gwa_run']!="") admin_ar_gwa_run();
else {
if($ar_gwa_debug=="ON") $wpdb->show_errors();
if(class_exists('ar_gwa_attach') && ($tcc = new ar_gwa_attach) && isset($_FILES['ar_gwa_userfile']))  $masg = $tcc->ar_gwa_attach_message();
if($_REQUEST['act'] == 'del')
{
	// delete messages
	$mID = $_REQUEST['mID'];
	for($i = 0; $i < count($mID); $i++)
	{
		$wpdb->query("DELETE FROM " . $wpdb->prefix . "ar_gwa_msg WHERE mID='$mID[$i]'");
	}
  echo '<div id="message" class="updated fade"><p>'.$i.' '.__("Message(s) deleted",'argwa').'</p></div>';

} else if($_REQUEST['act'] == 'edit')
{
#echo 'edit '.$_REQUEST['mDate'];exit;
	if(!$_REQUEST['mSubject'] || !$_REQUEST['mBody']) { $g_error[] = 20; }
	if(($_REQUEST['mDay'] < 0 || $_REQUEST['mDay'] > 999 || !is_numeric($_REQUEST['mDay']) || !$_REQUEST['listid']) && !isset($_REQUEST['mDate'])) { $g_error[] = 22; }
	else if(isset($_REQUEST['mDate'])){
	$qry = "SELECT * FROM ".$wpdb->prefix."ar_gwa_msg WHERE mDate = '{$_REQUEST['mDate']}' AND mID != '{$_REQUEST['mID']}' AND mLID = '{$_REQUEST['listid']}'";
	} else {
	$qry = "SELECT * FROM ".$wpdb->prefix."ar_gwa_msg WHERE mDay = '{$_REQUEST['mDay']}' AND mID != '{$_REQUEST['mID']}' AND mLID = '{$_REQUEST['listid']}'";
	}
  $res = $wpdb->get_results($qry,ARRAY_A);
	if($res) { $g_error[] = 21; }
if(isset($_REQUEST['mTop']) || isset($_REQUEST['mBot'])) {
 $ararg1 = $wpdb->escape($_REQUEST['mTop']);
 $ararg2 = $wpdb->escape($_REQUEST['mBot']);
 if((isset($ararg1) || isset($ararg2))) {
  if(class_exists('ar_gwa_template') && ($tb = new ar_gwa_template))
   list($top,$bot) = $tb->addAction($ararg1,$ararg2);
 }
}
	if(!count($g_error))
	{
    if($_REQUEST['ar_gwa_filename']) $attach = ",mAttach='".$_REQUEST['ar_gwa_filename']."'";
    
    if(class_exists('ar_gwa_newsletter') && isset($_REQUEST['nlTop'])) $mnews = ",nlid='{$_REQUEST['nlTop']}'";    
    if(isset($_REQUEST['mDate'])) {
		$qry="UPDATE ".$wpdb->prefix."ar_gwa_msg SET mSubject='".$wpdb->escape($_REQUEST['mSubject'])."',mBody='".$top.$wpdb->escape($_REQUEST['mBody']).$bot."',mDate='".$wpdb->escape($_REQUEST['mDate'])."',mType='{$_REQUEST['mType']}',mLID='{$_REQUEST['listid']}' $attach $mnews WHERE mID='{$_REQUEST['mID']}'";    
    } else {		
		$qry="UPDATE ".$wpdb->prefix."ar_gwa_msg SET mSubject='".$wpdb->escape($_REQUEST['mSubject'])."',mBody='".$top.$wpdb->escape($_REQUEST['mBody']).$bot."',mDay='".$wpdb->escape($_REQUEST['mDay'])."',mType='{$_REQUEST['mType']}',mLID='{$_REQUEST['listid']}' $attach $mnews WHERE mID='{$_REQUEST['mID']}'";
    }
  $res = $wpdb->query($qry);
  admin_ar_gwa_messages();
  exit;
	}
} else if($_REQUEST['mID'] && $_REQUEST['listid']) { 
  $qry = "SELECT * FROM ".$wpdb->prefix."ar_gwa_msg WHERE mID='{$_REQUEST['mID']}' AND mLID = '{$_REQUEST['listid']}'";
  $row = $wpdb->get_results($qry,ARRAY_A);
 if($row = $row[0])
 {
	$opt = array('text' => '', 'html' => '');
	$opt[$row['mType']] = 'selected';
	
	echo '<div id=""><div id=""><div id=""><div class="wrap"><h2>'.__("Edit Message",'argwa').'</h2>';
  echo $masg;
echo '<form name="mForm" method="post" action="?page=ar_gwa_edit_message">';
	echo '<table align="center">';
if($row['mType']=='html') {
if(!file_exists(ABSPATH.'wp-content/plugins/autoresponder-gwa/gwa-xinha.txt')){
if (function_exists('wp_tiny_mce')) wp_tiny_mce( false ,
array(
"editor_selector" => "editorContent",
"plugins" => "spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
"theme_advanced_buttons1" => "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
"theme_advanced_buttons2" => "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
"theme_advanced_buttons3" => "hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen,|,spellchecker",
"extended_valid_elements" => "form[*],div[*],style[*],p[*],table[*],td[*]",
"skin" => "o2k7",
"skin_variant" => "silver",)
);

	echo '<script type="text/javascript">
<!--
function toggleEditor(id) {
	if (!tinyMCE.getInstanceById(id))
		tinyMCE.execCommand(\'mceAddControl\', false, id);
	else
		tinyMCE.execCommand(\'mceRemoveControl\', false, id);
}';
echo "toggleEditor('editorContent');";
echo "\n"."-->
</script>"."\n\n";
}
}
echo '<tr>
<td>'.__("LIST",'argwa').'</td>
<td>'. ar_gwa_buildlistselect($_REQUEST['listid']) .'</td>
</tr>';
if(class_exists('ar_gwa_template') && ($tb = new ar_gwa_template)) echo $tb->echoWarning(1);
	if($row['mDay']!='')
	echo '<tr><td>'.__("Day",'argwa').'</td>'.'<td><input type="text" name="mDay" style="width:100px;" value="'.$row['mDay'].'"> (0 - 999)</td></tr>';
  else if($row['mDate']!='')
	echo '<tr><td>'.__("Date",'argwa').'</td>'.'<td><input type="text" name="mDate" value="'.$row['mDate'].'">yyyy-mm-dd</td></tr>';
  else
	echo '<tr><td><strong>'.__("ERROR",'argwa').'</strong></td>'.'<td><p style="color:red">Please CLICK MENU LINK TO RELOAD PAGE.</td></tr>';  	
	echo '<tr><td>'.__("Type",'argwa').'</td>';
	echo '<td><select name="mType" style="width:100px;" onchange="toggleEditor(\'editorContent\')">';
	echo '<option value="text" '.$opt['text'].'>'.__("PLAIN TEXT",'argwa').'</option>';
	echo '<option value="html" '.$opt['html'].'>'.__("HTML",'argwa').'</option>';
	echo '</select></td></tr>';

if(class_exists('ar_gwa_template') && ($tb = new ar_gwa_template)) {
	echo '<tr><td colspan=2>'.__("Selecting a header or footer template on this page will<br>add it to the existing message content displayed below.",'argwa').'</td></tr>';
   echo $tb->addForm();
  }
if(class_exists('ar_gwa_newsletter') && ($te = new ar_gwa_newsletter)) echo $te->addForm($_REQUEST['listid'],$row['nlid']);
	
	echo '<tr><td>'.__("Subject",'argwa').'</td>';
	echo '<td><input type="text" name="mSubject" style="width:325px;" maxlength="250" value="'.stripslashes($row['mSubject']).'"></td></tr>';
	?>
	<tr><td>&nbsp;</td>
		<td style="background-color:#e4f2fd;border:solid 1px #f00;padding:5px;width:450px;"><?php _e('<strong>We HATE SPAM!</strong> And so does the FTC. Fines for sending spam can be as high as $11,000 per violation! Protect yourself. Know the law.','argwa');?><br><a href="http://www.ftc.gov/bcp/edu/pubs/business/ecommerce/bus61.shtm" title="<?php _e('Opens in a new Window.','argwa');?>" target="_blank"><?php _e('Click here to see the Can-Spam Act.','argwa');?></a></td>
	</tr>	
	<?php
	echo '<tr><td valign="top">'.__("Body",'argwa').'</td>';
	echo '<td><textarea id="editorContent" name="mBody" style="width:600px; height:400px;">'.stripslashes(htmlentities($row['mBody'])).'</textarea></td></tr>';
	?>
	<tr>
		<td>&nbsp;</td><td style="background-color:#e4f2fd;border:solid 1px #22ff55;padding:5px;width:450px;"><?php _e('<strong>Personalize your Messages!</strong> <span style="color:#f00">*USE ONLY THE TAGS BELOW*</span><br />Use these custom tags when mailing your lists from this page.','argwa');?>  <strong style="font-size:9pt;"> <&#63;Name&#63;> <&#63;Email&#63;> <&#63;Unsubscribe&#63;> <&#63;Archive&#63;> <&#63;Field1&#63;> <&#63;Field2&#63;> <&#63;Field3&#63;> <&#63;Field4&#63;> <&#63;Field5&#63;> <?php if(file_exists(dirname(__FILE__).'/ar_gwa_user_edit.php'))echo "<&#63;Update&#63;>";?></strong></td>
</tr><?php
	echo '<tr><td>&nbsp;</td><td><input type="button" onClick="javascript:{ retu=confirm(\'Current changes will be lost.\');if(retu) this.form.submit(); }" class="button" value="'.__("CANCEL",'argwa').'" name="admin_ar_gwa_add_message">&nbsp;<input type="submit" class="button" value="'.__("Edit Msg",'argwa').'">';
  if(class_exists('ar_gwa_attach')) { echo "&nbsp;<span style='color:#00f;font-weight:bold;'>".__("ATTACH FILE:",'argwa')."</span>&nbsp;".admin_ar_gwa_attach($row['mAttach']).''; } 
  echo '</td></tr></table>';  
	echo '<input type="hidden" name="act" value="edit">';
	echo '<input type="hidden" name="mLID" value="'.$_REQUEST['listid'].'">';
	echo '<input type="hidden" name="mID" value="'.$_REQUEST['mID'].'">';
  echo '</form>';
  echo '<div style="margin-left:60px;margin-top:10px;">';
  if(class_exists('ar_gwa_attach') && ($tcc = new ar_gwa_attach)) $tcc->ar_gwa_upload();
  echo '</div>';
 }
 else { 
  echo ar_gwa_getError(100);
 }
} else {
admin_ar_gwa_messages($msg);
admin_ar_gwa_queue();
}
}
  echo $ctag.'</div></div>';
}

function print_gwaCheck($lst_num) {

$script = "<script type='text/javascript'>// <![CDATA[\n" . 'function gwaCheckForm'.$lst_num.'(form){nam = form.argwa_name.value;namcnt = nam.length;eml = form.argwa_email.value;if(typeof form.argwa_field1!="undefined"){ lField1 = form.argwa_field1.value; Field1 = lField1.length }if(typeof form.argwa_field2!="undefined"){ lField2 = form.argwa_field2.value; Field2 = lField2.length }if(typeof form.argwa_field3!="undefined"){ lField3 = form.argwa_field3.value; Field3 = lField3.length }if(typeof form.argwa_field4!="undefined"){ lField4 = form.argwa_field4.value; Field4 = lField4.length }if(typeof form.argwa_field5!="undefined"){ lField5 = form.argwa_field5.value; Field5 = lField5.length }if(namcnt < 2) {alert("'.__("Sorry, Name field must be 2 characters minimum.",'argwa').'");return false;}if ((typeof form.argwa_field1!="undefined")) { if((Field1 < 2)) {alert("'.__("Sorry, Field 1 must be 2 characters minimum.",'argwa').'");return false;}}if((typeof form.argwa_field2!="undefined")) { if((Field2 < 2)) {alert("'.__("Sorry, Field 2 must be 2 characters minimum.",'argwa').'");return false;}}if((typeof form.argwa_field3!="undefined")) { if((Field3 < 2)) {alert("'.__("Sorry, Field 3 must be 2 characters minimum.",'argwa').'");return false;}}if((typeof form.argwa_field4!="undefined")) { if((Field4 < 2)) {alert("'.__("Sorry, Field 4 must be 2 characters minimum.",'argwa').'");return false;}}if((typeof form.argwa_field5!="undefined")) { if ((Field5 < 2)) {alert("'.__("Sorry, Field 5 must be 2 characters minimum.",'argwa').'");return false;}}return(echeck(eml));}function echeck(str) {var at="@";var dot=".";var lat=str.indexOf(at);var lstr=str.length;var ldot=str.indexOf(dot);if (str.indexOf(at)==-1){alert("Invalid Email Address. ");return false}if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){alert("'.__("Invalid Email Address.",'argwa')."&nbsp;".'");return false}if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){alert("'.__("Invalid Email Address.",'argwa')."&nbsp;".'");return false}if (str.indexOf(at,(lat+1))!=-1){alert("'.__("Invalid Email Address.",'argwa')."&nbsp;".'");return false}if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){alert("'.__("Invalid Email Address.",'argwa')."&nbsp;".'");return false}if (str.indexOf(dot,(lat+2))==-1){alert("'.__("Invalid Email Address.",'argwa')."&nbsp;".'");return false}if (str.indexOf(" ")!=-1){alert("'.__("Invalid Email Address.",'argwa')."&nbsp;".'");return false}return true;} '."\n// ]]></script>";
return $script;
}


function admin_ar_gwa_lists() { 
global $wpdb,$ctag,$ar_gwa_debug;
if($ar_gwa_debug=="ON") $wpdb->show_errors();
$orderby = strip_tags($_REQUEST['orderby']);
$tbl_name = $wpdb->prefix . "ar_gwa_lists";
if(!isset($orderby) || $orderby=='') $orderby = 'xName';
if($_REQUEST['dir']) {
  $dir = 0;
  $orderby .= ' asc';
  } else {
  $dir=1;
  $orderby .= ' desc';  
  }
if($_REQUEST['act'] == 'del')
{
	// delete messages
	$xID = $_REQUEST['lID'];
	$list_count = $wpdb->get_var("SELECT COUNT(xID) FROM ".	$tbl_name);
	if($list_count == count($xID)) $msg = 'Sorry, you must have at least one list?';
  else {
   for($i = 0; $i < count($xID); $i++)
	 {
  	$addr_count = $wpdb->get_var("SELECT COUNT(lID) FROM ".	$wpdb->prefix. "ar_gwa_leads WHERE lLID='{$xID[$i]}'");
		 if($addr_count>0) {
       $msg = sprintf(__("You still have addresses on list ID#%d.",'argwa')."&nbsp;",$xID[$i]).__("Please transfer or delete the addresses before deleting the list.",'argwa'); 
     } else {
    		$wpdb->query("DELETE FROM " . $tbl_name . " WHERE xID='".$xID[$i]."'");
#        delete_option();
delete_option('ar_gwa_unsub_'.$xID[$i]);
delete_option('ar_gwa_confirm_'.$xID[$i]);
delete_option('ar_gwa_footer_'.$xID[$i]);
delete_option('ar_gwa_reg_optin_'.$xID[$i]);
delete_option('ar_gwa_reg_optinb_'.$xID[$i]);
delete_option('ar_gwa_notify_'.$xID[$i]);
delete_option('ar_gwa_captcha_'.$xID[$i]);
delete_option('ar_gwa_sldht_'.$xID[$i]);
     }
    if($msg) break; 
	 }
	if(!$msg) $msg = __("Update successful.",'argwa');
  }	
} else if($_REQUEST['act'] == 'new') {
	$list_count = $wpdb->get_var("SELECT COUNT(xID) FROM ".	$tbl_name);
  $wpdb->query("INSERT INTO ".$tbl_name." (xEmail,xName,xLabel,xPage,xReturn) VALUES('".get_bloginfo('admin_email')."','Default_".($list_count+1)."','".mysql_real_escape_string(get_bloginfo('name'))."','0','0')");
   $lst_num = $wpdb->insert_id;
   if ($lst_num>0) {
   $onclick = 'onclick="return gwaCheckForm'.$lst_num.'(this.form)"';
$subscribe = '<!-- [GWA] AutoResponder Begin --><form name="ARGWA" action="'.get_bloginfo('url').'/index.php" method="post"><table style="border-collapse: collapse; padding: 10px;" border="0" cellspacing="0" cellpadding="0" bordercolor="#111111"><tbody><tr> <td><div><strong>Name:</strong> <input id="argwa_name" name="gwaname" size="20" type="text" /><br /> <strong>Email:</strong> <input id="argwa_email" name="gwaemail" size="20" type="text" /> <br /> <input class="button" '.$onclick.' name="Add" type="submit" value="SUBSCRIBE" /></div></td></tr></tbody></table> <input name="act" type="hidden" value="s_add" /> <input name="listid" type="hidden" value="'.$lst_num.'" /></form><!-- [GWA] AutoResponder End -->';
    $wpdb->query( "UPDATE `".$tbl_name."` set `xSubscribe`='".mysql_real_escape_string($subscribe)."',`xPopin`='".mysql_real_escape_string($subscribe)."',`xSlide`='".mysql_real_escape_string($subscribe)."' WHERE xID='".$lst_num."'" );
    $sql = "INSERT INTO `".$wpdb->prefix."ar_gwa_msg` (`mLID`, `mSubject`, `mBody`, `mDay`, `mType`) VALUES (".$lst_num.",'Welcome', '".mysql_real_escape_string("Hi <?Name?>\r\n\r\nThis is the default welcome message!\r\n\r\nThe webmaster has just installed this Newsletter Plugin for Wordpress from <a href='http://freeautoresponder.biz'>FreeAutoresponder.biz</a>")."', '0', 'html')";
    $results = $wpdb->query( $sql );
    update_option('ar_gwa_widget_num',$list_count+1);
    update_option('ar_gwa_sldht_'.$lst_num,'100');
    update_option('ar_gwa_wheight_'.$lst_num,'300');
    update_option('ar_gwa_wwidth_'.$lst_num,'220');
   $msg = "New list created successfully.";
   }
} else if($_REQUEST['act'] == 'update') {
$op['xName'] = $_REQUEST['xName'];
$op['xEmail'] = $_REQUEST['xEmail'];
//$op['xSubscribe'] = $_REQUEST['name'];
$op['xLabel'] = $_REQUEST['xLabel'];
$op['xPage'] = $_REQUEST['xPage'];
$op['xReturn'] = $_REQUEST['xReturn'];
$op['xConfirm'] = $_REQUEST['xConfirm'];
$op['xHref2'] = $_REQUEST['xHref2'];
$op['xHref3'] = $_REQUEST['xHref3'];
$op['xUnSub'] = $_REQUEST['xUnSub'];
if(preg_match("/^\d+$/",$op['xConfirm']))
$p_response2 = $pcommon = $op['xConfirm'];
else
$p_url2 = $pcommon = $op['xHref2'];
if(preg_match("/^\d+$/",$op['xUnSub']))
$p_response3 = $pcommon3 = $op['xUnSub'];
else
$p_url3 = $pcommon3 = $op['xHref3'];

if(isset($_REQUEST['xHref']) && ($_REQUEST['xReturn']=='')) $op['xReturn'] = $_REQUEST['xHref'];
if(isset($_REQUEST['xHref2']) && ($_REQUEST['xConfirm']=='')) $pcommon = $p_url2 = $_REQUEST['xHref2'];
if(isset($_REQUEST['xHref3']) && ($_REQUEST['xUnSub']=='')) $pcommon3 = $p_url3 = $_REQUEST['xHref3'];
$op['xID'] = $_REQUEST['lLID'];
$oopp = array();
$oopp[] = $op;
update_option('ar_gwa_unsub_'.$op['xID'],$pcommon3);
update_option('ar_gwa_confirm_'.$op['xID'],$pcommon);
update_option('ar_gwa_footer_'.$op['xID'],$_REQUEST["ar_gwa_footer"]);
#update_option('ar_gwa_reg_optin_'.$op['xID'],$_REQUEST["ar_gwa_optin"]);
update_option('ar_gwa_remove_'.$op['xID'],$_REQUEST["ar_gwa_remove"]);
update_option('ar_gwa_drop_'.$op['xID'],$_REQUEST["ar_gwa_drop"]);
update_option('ar_gwa_sing_'.$op['xID'],$_REQUEST["ar_gwa_sing"]);
update_option('ar_gwa_notify_'.$op['xID'],$_REQUEST["ar_gwa_notify"]);
update_option('ar_gwa_captcha_'.$op['xID'],$_REQUEST["ar_gwa_captcha"]);
if($_REQUEST["ar_gwa_captcha"]=='checked')
update_option('ar_gwa_captcha',$_REQUEST["ar_gwa_captcha"]);
update_option_ar_gwa($widget,$oopp);

if(isset($_REQUEST['fShow'])) { update_option('ar_gwa_fShow_'.$op['xID'],'checked'); }
else delete_option('ar_gwa_fShow_'.$op['xID']);
if(isset($_REQUEST['mShow'])) { update_option('ar_gwa_mShow_'.$op['xID'],'checked'); }
else delete_option('ar_gwa_mShow_'.$op['xID']);
if(isset($_REQUEST['sShow'])) { update_option('ar_gwa_sShow_'.$op['xID'],'checked'); }
else delete_option('ar_gwa_sShow_'.$op['xID']);

}
$op['xConfirm'] = get_option('ar_gwa_confirm_'.$_REQUEST['lLID']);
if(preg_match("/^\d+$/",$op['xConfirm']))
$p_response2 = $pcommon = $op['xConfirm'];
else
$p_url2 = $pcommon = $op['xConfirm'];

$op['xUnSub'] = get_option('ar_gwa_unsub_'.$_REQUEST['lLID']);
if(preg_match("/^\d+$/",$op['xUnSub']))
$p_response3 = $pcommon3 = $op['xUnSub'];
else
$p_url3 = $pcommon3 = $op['xUnSub'];
if(! isset($_REQUEST['update']) ) {
if(isset($_REQUEST['listid']) && !isset($_REQUEST['RESET'])) 
  $qual = "WHERE xID='".$_REQUEST['listid']."'";
$arSql = "SELECT * FROM " . $tbl_name . " $qual ORDER BY ".$orderby;
$res = $wpdb->get_results($arSql);
?>
<div id=""> <div id=""><div id=""><div id="">
<div class="wrap">
<?php if(isset($msg)) echo '<div id="message" class="updated fade">'.$msg.'</div>';
echo "<h2 style='width:100%'>".__("Manage Lists",'argwa')."(".count($res).")</h2>";
echo '<div style="width:100%"><form style="display:inline;" action="?page=ar_gwa_lists" method="POST"><p><input type="submit" class="button" value="'.__("CREATE LIST",'argwa').' #'.(count($res)+1).'">';
	echo '<input type="hidden" name="act" value="new"></p>';
	echo '</form>'.argwa_get_note('10').'</div>';
if($res) {
?>
<form action="?page=ar_gwa_lists" method="post" id="lists-filter">
<table class="widefat">
	<thead>
	<tr>
	<th scope="col" class="check-column"><input type="checkbox" onclick="checkAll(document.getElementById('lists-filter'));" /></th>
	<th scope="col"><a href="?page=ar_gwa_lists&orderby=xID&dir=<?php echo $dir;?>"><?php _e("List ID",'argwa');?></a></th>
	<th scope="col"><a href="?page=ar_gwa_lists&orderby=xName&dir=<?php echo $dir;?>"><?php _e("Name",'argwa');?></a></th>
	<th scope="col"><a href="?page=ar_gwa_lists&orderby=xLabel&dir=<?php echo $dir;?>"><?php _e("Label",'argwa');?></a></th>
	<th scope="col"><a href="?page=ar_gwa_lists&orderby=xEmail&dir=<?php echo $dir;?>"><?php _e("Email",'argwa');?></a>
	<th scope="col"><?php _e("Leads",'argwa');?></</th>
	<th scope="col"><?php _e("List Details",'argwa');?></</th>
	</tr>
	</thead>
	<tbody>
	<tr id='post-1' class='alternate author-self status-publish' valign="top">
<?php
	foreach($res as $row)
	{
  $cnt = $wpdb->get_var("SELECT COUNT(lID) FROM ".$wpdb->prefix."ar_gwa_leads WHERE lLID='".$row->xID."' AND lCnf='1'");
		echo '<tr><th scope="row" class="check-column"><input type="checkbox" name="lID[]" value="'.$row->xID.'" /></th>'
				.'<td><abbr title="'.$row->xID.'">'.$row->xID.'</abbr></td>'
				.'<td><abbr title="'.$row->xEmail.'">'.$row->xName.'</abbr></td>'
				.'<td><abbr>'.$row->xLabel.'</abbr></td>'
				.'<td><strong><a class="row-title" href="mailto:'.$row->xEmail.'" title="'.__("Email Lead",'argwa').'">'.$row->xEmail.'</a></strong></td>'
				.'<td>'.$cnt.'</td>'
				.'<td><strong><a href="?page=ar_gwa_lists&lLID='.$row->xID.'&update=1">'.__("Update Link",'argwa').'</a></strong></td>'
				.'</tr>';
  }
  ?>
	</tbody>
<?php
	echo '</table><p>&nbsp;</p>';
	echo '<p><input type="submit" class="button" value="'.__("Delete Checked",'argwa').'">';
	echo '<input type="hidden" name="act" value="del"></p>';
	echo '</form>';
?><?php echo $ctag?>
<div id="ajax-response"></div>
<div class="tablenav">
<br class="clear" />
</div>
<br class="clear" />
</div>
</div><!-- wpbody -->
</div><!-- wpcontent -->
</div><!-- wpwrap -->
<?php
  } else {
  _e("No Records",'argwa');
  echo '</div></div><!-- wpbody --></div></div>';
  }
 } else if(isset($_REQUEST['update'])) {

if(!isset($_REQUEST['lLID']))
  $listid = $wpdb->get_var("SELECT xID FROM ".$wpdb->prefix."ar_gwa_lists ORDER BY xName LIMIT 0,1");
else
$listid = $_REQUEST['lLID'];
$rec = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."ar_gwa_lists WHERE xID='".$_REQUEST['lLID']."'");
$p_display = $rec[0]->xPage;
if(preg_match("/^\d+$/",$rec[0]->xReturn))
$p_response = $rec[0]->xReturn;
else
$p_url = $rec[0]->xReturn;

if(!class_exists('ar_gwa_user_edit') && file_exists(dirname(__FILE__).'/ar_gwa_user_edit.php')) include_once(dirname(__FILE__).'/ar_gwa_user_edit.php');
if(class_exists('ar_gwa_user_edit') && ($aux=new ar_gwa_user_edit())){

if(isset($_REQUEST['xUserInfo'])){ update_option('ar_gwa_ui_'.$listid,$_REQUEST['xUserInfo']);}
if( $_REQUEST['ar_gwa_iu_'.$listid]=='YES'){ update_option('ar_gwa_iu_'.$listid,'checked');} else if( $_REQUEST['ar_gwa_iu_'.$listid]=='NO') {delete_option('ar_gwa_iu_'.$listid);}
for($ry=1;$ry<6;$ry++){
if(isset($_REQUEST['ar_gwa_xf'.$ry])) {$aux->update_field($ry,$listid);}
}}

if(isset($_REQUEST['gact']) && $_REQUEST['gact']=='update') {
$xqry = "UPDATE ".$wpdb->prefix."ar_gwa_lists SET xSubscribe='".mysql_real_escape_string($_REQUEST['subscribe'])."' WHERE xID='".$listid."'";
$wpdb->query($xqry);
} else if(isset($_REQUEST['gact']) && $_REQUEST['gact']=='reset') {
$onclick = 'onclick="return gwaCheckForm'.$listid.'(this.form)"';
$subscribe = '<!-- [GWA] AutoResponder Begin --><form name="ARGWA" action="'.get_bloginfo('url').'/index.php" method="post"><table style="border-collapse: collapse; padding: 10px;" border="0" cellspacing="0" cellpadding="0" bordercolor="#111111"><tbody><tr> <td><div><strong>Name:</strong> <input id="argwa_name" name="gwaname" size="20" type="text" /><br /> <strong>Email:</strong> <input id="argwa_email" name="gwaemail" size="20" type="text" /> <br /> <input class="button" '.$onclick.' name="Add" type="submit" value="SUBSCRIBE" /></div></td></tr></tbody></table> <input name="act" type="hidden" value="s_add" /> <input name="listid" type="hidden" value="'.$listid.'" /></form><!-- [GWA] AutoResponder End -->';

$xqry = "UPDATE ".$wpdb->prefix."ar_gwa_lists SET xSubscribe='".mysql_real_escape_string($subscribe)."' WHERE xID='".$listid."'";
$wpdb->query($xqry);
}
if(isset($_REQUEST['popindisplay'])) {
$xqry = "UPDATE ".$wpdb->prefix."ar_gwa_lists SET xPopin='".mysql_real_escape_string($_REQUEST['popindisplay'])."' WHERE xID='".$listid."'";
$wpdb->query($xqry);
}

if(isset($_REQUEST['sldindisplay'])) {
$xqry = "UPDATE ".$wpdb->prefix."ar_gwa_lists SET xSlide='".mysql_real_escape_string($_REQUEST['sldindisplay'])."' WHERE xID='".$listid."'";
$wpdb->query($xqry);
}

if(isset($_REQUEST['ar_gwa_popfg'])){ update_option('ar_gwa_popfg_'.$listid,$_REQUEST['ar_gwa_popfg']);}
if(isset($_REQUEST['ar_gwa_popbkg'])){update_option('ar_gwa_popbkg_'.$listid,$_REQUEST['ar_gwa_popbkg']);}
if(isset($_REQUEST['ar_gwa_popbor'])){update_option('ar_gwa_popbor_'.$listid,$_REQUEST['ar_gwa_popbor']);}
if(isset($_REQUEST['ar_gwa_border'])){update_option('ar_gwa_border_'.$listid,$_REQUEST['ar_gwa_border']);}
if(isset($_REQUEST['ar_gwa_wheight'])){update_option('ar_gwa_wheight_'.$listid,$_REQUEST['ar_gwa_wheight']);}
if(isset($_REQUEST['ar_gwa_wwidth'])){update_option('ar_gwa_wwidth_'.$listid,$_REQUEST['ar_gwa_wwidth']);}
if(isset($_REQUEST['ar_gwa_sldfg'])){ update_option('ar_gwa_sldfg_'.$listid,$_REQUEST['ar_gwa_sldfg']);}
if(isset($_REQUEST['ar_gwa_sldbkg'])){update_option('ar_gwa_sldbkg_'.$listid,$_REQUEST['ar_gwa_sldbkg']);}
if(isset($_REQUEST['ar_gwa_sldbor'])){update_option('ar_gwa_sldbor_'.$listid,$_REQUEST['ar_gwa_sldbor']);}
if(isset($_REQUEST['ar_gwa_sldht'])){update_option('ar_gwa_sldht_'.$listid,$_REQUEST['ar_gwa_sldht']);}
if(isset($_REQUEST['ar_gwa_sborder'])){update_option('ar_gwa_sborder_'.$listid,$_REQUEST['ar_gwa_sborder']);}

$fShow = get_option("ar_gwa_fShow_".$listid);
$mShow = get_option("ar_gwa_mShow_".$listid);
$sShow = get_option("ar_gwa_sShow_".$listid);

$opb = get_option('ar_gwa_border_'.$listid);
for($i=0;$i<6;$i++) {
if($opb==$i){
$optb .= "<option selected>$i</option>";
} else {
$optb .= "<option>$i</option>";
}
}

$opc = get_option('ar_gwa_sborder_'.$listid);
for($i=0;$i<6;$i++) {
if($opc==$i){
$optc .= "<option selected>$i</option>";
} else {
$optc .= "<option>$i</option>";
}
}
$borderwidth = '<select name="ar_gwa_border">'.$optb.'</select>';
$borderwidth2 = '<select name="ar_gwa_sborder">'.$optc.'</select>';

$qry = "SELECT xSubscribe FROM ".$wpdb->prefix."ar_gwa_lists WHERE xID='".$listid."'";
$subscribe = stripslashes(preg_replace("/{id}/",$listid,$wpdb->get_var($qry)));
$qry = "SELECT xPopin FROM ".$wpdb->prefix."ar_gwa_lists WHERE xID='".$listid."'";
$popindisplay = stripslashes(preg_replace("/{id}/",$listid,$wpdb->get_var($qry)));
$qry = "SELECT xSlide FROM ".$wpdb->prefix."ar_gwa_lists WHERE xID='".$listid."'";
$sldindisplay = stripslashes(preg_replace("/{id}/",$listid,$wpdb->get_var($qry)));

$extern = __("Use External URL",'argwa');
	echo '<div id=""><div class="wrap">';
?>
<?php if(!file_exists(ABSPATH.'wp-content/plugins/autoresponder-gwa/gwa-xinha.txt')) { 

if (function_exists('wp_tiny_mce')) wp_tiny_mce( false ,
array(
"editor_selector" => "subcribe",
"plugins" => "spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
"theme_advanced_buttons1" => "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
"theme_advanced_buttons2" => "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
"theme_advanced_buttons3" => "hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen,|,spellchecker",
"extended_valid_elements" => "form[*],div[*],style[*],p[*],table[*],td[*]",
"skin" => "o2k7",
"skin_variant" => "silver",)
);
?>
<script type="text/javascript">
<!--
function toggleEditor(id) {
	if (!tinyMCE.getInstanceById(id))
		tinyMCE.execCommand('mceAddControl', false, id);
	else
		tinyMCE.execCommand('mceRemoveControl', false, id);
}
toggleEditor('editorContent');
toggleEditor('subscribe');
toggleEditor('sldindisplay');
toggleEditor('popindisplay');
toggleEditor('ar_gwa_footer');
-->
</script>
<?php } ?>
  <h2 style="display:inline;width:100%"><?php _e("List Details",'argwa'); ?> (<?php _e("List:",'argwa')."&nbsp;"; echo $rec[0]->xName; ?>)</h2><br /><br /><form name="mForm" method="post" action="?page=ar_gwa_lists&update=2">
  <div align="center" style="text-align:left">
  <table border="0" cell-padding="15" style="width:725px;background-color: rgb(228, 242, 253);-moz-border-radius: 15px;border-radius: 15px;padding:15px;">
    <tr>
      <td height="19"><b><?php _e("Newsletter Name",'argwa'); ?>:</b></td>
      <td height="19"><input style="border:solid 1px #21759b" type="text" name="xName" size="49" value="<?php echo $rec[0]->xName;?>"><?php echo argwa_get_note('33');?></td>
    </tr>
   <tr>
      <td height="19"><b><?php _e("Subscription Form Label",'argwa'); ?>:</b></td>
      <td height="19"><input style="border:solid 1px #21759b" type="text" name="xLabel" size="49" value="<?php echo $rec[0]->xLabel;?>"></td>
    </tr>
     <tr>
      <td height="17"><b>&quot;From:&quot; <?php _e("Email Address",'argwa'); ?>:</b></td>
      <td height="17"><input style="border:solid 1px #21759b" type="text" name="xEmail" size="49" value="<?php echo $rec[0]->xEmail;?>"></td>
    </tr>
         <tr>
      <td height="17"><b><?php _e("Shortcode for this List",'argwa'); ?>:</b></td>
      <td height="17"><strong  style='color:#000'><input style="border:solid 1px #21759b" type="text" name="XXX" size="49" value="[GWAR listid=<?php echo $listid;?>]"></strong></td>
    </tr>    <tr>
      <td height="4"></td>
      <td height="4"><br /><input class="button" type="submit" value="<?php _e("Submit",'argwa'); ?>" name="B1"><input class="button" type="reset" value="<?php _e("Reset",'argwa'); ?>" name="B2"><br /><?php _e("All changes made on page will be submitted.",'argwa'); ?></td>
    </tr></table><br />
    
    <?php 
    if(!class_exists('ar_gwa_user_edit') && file_exists(dirname(__FILE__).'/ar_gwa_user_edit.php')) include_once(dirname(__FILE__).'/ar_gwa_user_edit.php');
  if(class_exists('ar_gwa_user_edit') && ($aux=new ar_gwa_user_edit())){ ;?>

   <table border="0"  cell-padding="15" style="background-color: rgb(228, 242, 253);width:725px;-moz-border-radius: 15px;border-radius: 15px;padding:15px;" width="725">  
  
  <tr><td height="25"><strong style="color:#f00">*<a title="<?php _e("Part of Subscriber User-Info Edit extension.",'argwa');?>" name="dd"><?php _e("User-Info Edit Page",'argwa'); ?></a>*:</strong></td><td height="25"><?php echo argwa_get_note('34');?><?php if(!($xui = get_option('ar_gwa_ui_'.$listid))) { ?><small style="color:#f00"><?php _e("Must select page to display with the shortcode as User-Info page.",'argwa'); ?></small><?php }?><br /><?php wp_dropdown_pages(array('depth' => 0, 'child_of' => 0, 'selected' => $xui, 'echo' => 1,'name' => 'xUserInfo', 'show_option_none' => __("Select a Page",'argwa'))); ?><br /><?php echo ''.__("Display Additional Fields on Update page:",'argwa').' <input type="radio" name="ar_gwa_iu_'.$listid.'" value="YES" '.get_option('ar_gwa_iu_'.$listid).'> Yes <input type="radio" name="ar_gwa_iu_'.$listid.'" value="NO">No<br /><small>* '.__("Check to collect extra fields on the user update page.",'argwa').'</small></td></tr>';
  for($o=1;$o<6;$o++){?><tr><td height="25"><strong style="color:#f00"><a title="Enter a description/label for this field shown on the User-Info Page Only." name="dd"><?php _e("Extra Data Field",'argwa');echo "#".$o;?></a></strong>:</td><td height="25"><input style="border:solid 1px #21759b" name="ar_gwa_xf<?php echo $o;?>" type="text" size="55" value="<?php echo $aux->get_field($o,$listid); ?>"></td></tr>
<?php } ?><tr>
      <td height="4"></td>
      <td height="4"><br /><input class="button" type="submit" value="<?php _e("Submit",'argwa'); ?>" name="B1"><input class="button" type="reset" value="<?php _e("Reset",'argwa'); ?>" name="B2"><br /><?php _e("All changes made on page will be submitted.",'argwa'); ?></td></tr><?php echo '</table><br />';}; ?><table border="0"  cell-padding="15" style="background-color: rgb(228, 242, 253);width:725px;-moz-border-radius: 15px;border-radius: 15px;padding:15px;" width="725"><tr><td height="25"><strong><?php _e("Subscription Response",'argwa'); ?>:</strong></td>
      <td height="25"><?php wp_dropdown_pages(array('depth' => 0, 'child_of' => 0, 'selected' => $p_response, 'echo' => 1,'name' => 'xReturn', 'show_option_none' => $extern)); ?><br><small><?php _e("Select page to display or enter an external URL below.",'argwa'); ?></small><?php echo argwa_get_note('35');?></td>
    </tr><tr><td height="19"><?php _e("External URL for above",'argwa'); ?>:</td><td height="19"><input style="border:solid 1px #21759b" type="text" name="xHref" size="49" value="<?php echo $p_url;?>"><br /><small><?php _e("Select Use External URL above. URL MUST START WITH",'argwa'); ?> http://</small></td>
    </tr>     <tr>
      <td height="4"></td>
      <td height="4"><br /><input class="button" type="submit" value="<?php _e("Submit",'argwa'); ?>" name="B1"><input class="button" type="reset" value="<?php _e("Reset",'argwa'); ?>" name="B2"><br /><?php _e("All changes made on page will be submitted.",'argwa'); ?></td>
    </tr>
</table><br />
  <table border="0"  cell-padding="15" width="725" style="width:725px;background-color: rgb(228, 242, 253);-moz-border-radius: 15px;border-radius: 15px;padding:15px;">
    <tr>
      <td height="25"><strong><?php _e("Confirm Link Response",'argwa'); ?>:</strong></td>
      <td height="25"><?php wp_dropdown_pages(array('depth' => 0, 'child_of' => 0, 'selected' => $p_response2, 'echo' => 1,'name' => 'xConfirm', 'show_option_none' => $extern)); ?><br><small><?php _e("Select page to display or enter an external URL below.",'argwa'); ?></small><?php echo argwa_get_note('36');?></td>
    </tr>
    <tr>
      <td height="19"><?php _e("External URL for above",'argwa'); ?>:</td>
      <td height="19"><input style="border:solid 1px #21759b" type="text" name="xHref2" size="49" value="<?php echo $p_url2;?>"><br /><small><?php _e("Select Use External URL above. URL MUST START WITH",'argwa'); ?> http://</small></td>
    </tr>    <tr>
      <td height="4"></td>
      <td height="4"><br /><input class="button" type="submit" value="<?php _e("Submit",'argwa'); ?>" name="B1"><input class="button" type="reset" value="<?php _e("Reset",'argwa'); ?>" name="B2"><br /><?php _e("All changes made on page will be submitted.",'argwa'); ?></td>
    </tr>
</table><br />
  <table border="0" cell-padding="15" style="background-color: rgb(228, 242, 253);width:725px;-moz-border-radius: 15px;border-radius: 15px;padding:15px;" width="725">
    <tr>
      <td height="25"><strong><?_e("Unsubscribe Response",'argwa'); ?>:</strong></td>
      <td height="25"><?php wp_dropdown_pages(array('depth' => 0, 'child_of' => 0, 'selected' => $p_response3, 'echo' => 1,'name' => 'xUnSub', 'show_option_none' => $extern)); ?><br><small><?php _e("Select page to display or enter an external URL below.",'argwa'); ?></small><?php echo argwa_get_note('37');?></td>
    </tr>
    <tr>
      <td height="19"><?php _e("External URL for above",'argwa'); ?></td>
      <td height="19"><input style="border:solid 1px #21759b" type="text" name="xHref3" size="49" value="<?php echo $p_url3;?>"><br /><small><?php _e("Select Use External URL above. URL MUST START WITH",'argwa'); ?> http://</small></td>
    </tr>    <tr>
      <td height="4"></td>
      <td height="4"><br /><input class="button" type="submit" value="<?php _e("Submit",'argwa'); ?>" name="B1"><input class="button" type="reset" value="<?php _e("Reset",'argwa'); ?>" name="B2"><br /><?php _e("All changes made on page will be submitted.",'argwa'); ?></td>                                  
    </tr>
</table><br />
  <table cell-padding="15" border="0" style="background-color: rgb(228, 242, 253);width:725px;-moz-border-radius: 15px;border-radius: 15px;padding:15px;" width="725">
    <tr>
      <td height="55" valign="top"><b><?_e("Newsletter Options",'argwa'); ?>:</b></td>
      <td height="55"><?php echo argwa_get_note('38');?>
      <?php
      if(!class_exists('ar_gwa_single') && file_exists(dirname(__FILE__).'/ar_gwa_single.php')) include_once(dirname(__FILE__).'/ar_gwa_single.php');
if(class_exists('ar_gwa_single') && $hpt = new ar_gwa_single()) {
echo $hpt->single_sub($rec[0]->xID);
}?><input type="checkbox" name="ar_gwa_drop" value="checked"  <?php echo get_option('ar_gwa_drop_'.$rec[0]->xID);?> > 
      <?php _e("Unsubscribe new addresses from all other lists.",'argwa'); ?><br><br />
            <input type="checkbox" name="ar_gwa_remove" value="checked"  <?php echo get_option('ar_gwa_remove_'.$rec[0]->xID);?> > 
      <?php _e("Delete on unsubscribe (otherwise set as REMOVED)",'argwa'); ?><br><small><?php _e("Set as 'REMOVED' to block address from future IMPORT only.<br />View and delete these using FILTER on the",'argwa')."&nbsp;"; ?><a href='?page=ar_gwa_leads'><?php _e("Leads Page.",'argwa'); ?></a></small><br />
<?php
if($_REQUEST['ar_gwa_optin']=='X') { 
update_option('ar_gwa_reg_optinb_'.$rec[0]->xID,'');
update_option('ar_gwa_reg_optin_'.$rec[0]->xID,'');
} else if($_REQUEST['ar_gwa_optin']=='selected') {
update_option('ar_gwa_reg_optinb_'.$rec[0]->xID,'checked');
update_option('ar_gwa_reg_optin_'.$rec[0]->xID,'');
} else if($_REQUEST['ar_gwa_optin']=='checked') {
update_option('ar_gwa_reg_optin_'.$rec[0]->xID,'checked');
update_option('ar_gwa_reg_optinb_'.$rec[0]->xID,'');
}
if(!(get_option('ar_gwa_reg_optinb_'.$rec[0]->xID)) && (!(get_option('ar_gwa_reg_optin_'.$rec[0]->xID)))) $ropt = 'checked';
?><br />
<div style="border: dashed 1px #ccc;">

<input type="radio" name="ar_gwa_optin" value="X"  <?php echo $ropt;?> >&nbsp;<?php _e("Do not subscribe new users on Registration Page",'argwa'); ?><br>

<input type="radio" name="ar_gwa_optin" value="checked"  <?php echo get_option('ar_gwa_reg_optin_'.$rec[0]->xID);?> >&nbsp;<?php _e("Display Opt-in Checkbox on User Registration Page",'argwa'); ?><br>

<input type="radio" name="ar_gwa_optin" value="selected"  <?php echo get_option('ar_gwa_reg_optinb_'.$rec[0]->xID);?> >&nbsp;<?php _e("Automatically subscribe new blog users to this list!",'argwa'); ?></div><br />
      <input type="checkbox" name="ar_gwa_notify" value="checked" <?php echo get_option('ar_gwa_notify_'.$rec[0]->xID);?> > <?php _e("Send Admin an Email on Subscription Confirmations.",'argwa'); ?><br><br />
      <input type="checkbox" name="ar_gwa_captcha" value="checked" <?php echo get_option('ar_gwa_captcha_'.$rec[0]->xID);?> > <?php _e("Use jCap CAPTCHA Human Verification.",'argwa'); ?><br /><small><?php _e("When this option is checked CAPTCHA MUST BE SUBMITTED with form. Also controls loading of the required js files. If the CAPTCHA images fail to load verify that the javascript files are being included in your page header.",'argwa'); ?> <strong style="color:red"><?php _e("Additional code insertion in the form html is required.",'argwa'); ?></strong> <?php _e("See the",'argwa'); ?><br /><a href="?page=ar_gwa_help"><?php _e("HELP Page",'argwa'); ?></a> <?php _e("for details",'argwa'); ?>.</small>       
      </td>
    </tr>    <tr>
      <td height="4"></td>
      <td height="4"><br /><input class="button" type="submit" value="<?php _e("Submit",'argwa'); ?>" name="B1"><input class="button" type="reset" value="<?php _e("Reset",'argwa'); ?>" name="B2"><br /><?php _e("All changes made on page will be submitted.",'argwa'); ?></td>
    </tr>
</table><br />
  <table border="0" style="background-color: rgb(228, 242, 253);;-moz-border-radius: 15px;border-radius: 15px;padding:15px;width:725px" width="725">
    <tr>
      <td height="5" valign="top"><strong><?php _e("Subscription Form",'argwa');?>:</strong><br />
            		<select name="mType" style="width:100px;" onchange="toggleEditor('subscribe')" />
		<option value="html" selected><?php _e("HTML",'argwa');?>
		<?php if(!file_exists(ABSPATH.'wp-content/plugins/autoresponder-gwa/gwa-xinha.txt')) { ?>
		<option value="text"><?php _e("PLAIN TEXT",'argwa'); } ?></select><br /><br><input type="checkbox" name="mShow" value="<?php echo $listid;?>" <?php echo $mShow;?>>&nbsp;<?php _e("Display list name label.",'argwa');?>
</td>
      <td height="5"><?php echo argwa_get_note('39');?><textarea rows="15" name="subscribe" id="subscribe" cols="42"><?php echo $subscribe;?></textarea><br /><input type="radio" name="gact" value="none" checked>&nbsp;<?php _e("None",'argwa'); ?>&nbsp;<input type="radio" name="gact" value="update">&nbsp;<?php _e("Update",'argwa'); ?>&nbsp;<?php _e("Form",'argwa'); ?>&nbsp;<input type="radio" name="gact" value="reset">&nbsp;<?php _e("Reset",'argwa'); ?>&nbsp;<?php _e("Form",'argwa'); ?></td>
    </tr>
    <tr>
      <td height="4"></td>
      <td height="4"><br /><input class="button" type="submit" value="<?php _e("Submit",'argwa'); ?>" name="B1"><input class="button" type="reset" value="<?php _e("Reset",'argwa'); ?>" name="B2"><br /><?php _e("All changes made on page will be submitted.",'argwa'); ?></td>
    </tr>
  </table>
<br />
  <table border="0" style="background-color: rgb(228, 242, 253);;-moz-border-radius: 15px;border-radius: 15px;padding:15px;width:725px;" cell-padding="15" width="725">
    <tr>
      <td height="5" valign="top"><strong><?php _e("Fly-in Form Display",'argwa');?>:</strong><br />
      		<select name="mType" style="width:100px;" onchange="toggleEditor('popindisplay')" />
		<option value="html" selected><?php _e("HTML",'argwa');?>
<?php if(!file_exists(ABSPATH.'wp-content/plugins/autoresponder-gwa/gwa-xinha.txt')) { ?>
		<option value="text"><?php _e("PLAIN TEXT",'argwa');?>
<?php } ?>
		</select><br /><br><input type="checkbox" name="fShow" value="<?php echo $listid;?>" <?php echo $fShow?>>&nbsp;<?php _e("Display list name label.",'argwa');?></td>
      <td height="5"><?php echo argwa_get_note('40');?>
      <textarea rows="5" name="popindisplay" cols="42" id="popindisplay" style="width:300px;"><?php echo $popindisplay;?></textarea>
      <br /><input type="button" value="<?php _e("Fly-in Window Height",'argwa');?>">&nbsp;<input type="text" name="ar_gwa_wheight" size="3" value="<?php echo get_option('ar_gwa_wheight_'.$listid);?>">px
      <br /><input type="button" value="<?php _e("Fly-in Window Width",'argwa');?>">&nbsp;<input type="text" name="ar_gwa_wwidth" size="3" value="<?php echo get_option('ar_gwa_wwidth_'.$listid);?>">px
      <br /><input type="button" value="<?php _e("Fly-in Border Width",'argwa');?>"><?php echo $borderwidth;?>
      <br /><input type="button" onclick="showColorGrid3('popbg','pbor')" value="<?php _e("Fly-in Border ColorPicker",'argwa');?>"><input type="text" size="8" id="popbg" name="ar_gwa_popbor" value="<?php echo get_option('ar_gwa_popbor_'.$listid); ?>"><input type="text" size="3" id="pbor" style="background-color:<?php echo get_option('ar_gwa_popbor_'.$listid); ?>">
      <br /><input type="button" onclick="showColorGrid3('popbkg','pbkgs')" value="<?php _e("Fly-in Background ColorPicker",'argwa');?>"><input type="text" size="8" id="popbkg" name="ar_gwa_popbkg" value="<?php echo get_option('ar_gwa_popbkg_'.$listid); ?>"><input type="text" size="3" id="pbkgs" style="background-color:<?php echo get_option('ar_gwa_popbkg_'.$listid); ?>">
      <br /><input type="button" onclick="showColorGrid3('popfg','pfgs')" value="<?php _e("Fly-in Font ColorPicker",'argwa');?>"><input type="text" size="8" id="popfg" name="ar_gwa_popfg" value="<?php echo get_option('ar_gwa_popfg_'.$listid); ?>"><input type="text" size="3" id="pfgs" style="background-color:<?php echo get_option('ar_gwa_popfg_'.$listid); ?>">
      </td>
    </tr>
    <tr>
      <td height="4"></td>
      <td height="4"><br /><input class="button" type="submit" value="<?php _e("Submit",'argwa'); ?>" name="B1"><input class="button" type="reset" value="<?php _e("Reset",'argwa'); ?>" name="B2"><br /><?php _e("All changes made on page will be submitted.",'argwa'); ?></td>
    </tr>
    </table><br />      <div style="" id="colorpicker301" class="colorpicker301"></div>
  <table border="0" style="background-color: rgb(228, 242, 253);-moz-border-radius: 15px;border-radius: 15px;padding:15px;width:725px;" width="725">
    <tr>
      <td height="5" valign="top"><strong><?php _e("Slide-in Footer Display",'argwa');?>:</strong><br />
      		<select name="mType" style="width:100px;" onchange="toggleEditor('sldindisplay')" />
		<option value="html" selected><?php _e("HTML",'argwa');?>
<?php if(!file_exists(ABSPATH.'wp-content/plugins/autoresponder-gwa/gwa-xinha.txt')) { ?>
		<option value="text"><?php _e("PLAIN TEXT",'argwa');?>
<?php } ?>
		</select><br /><br><input type="checkbox" name="sShow" value="<?php echo $listid;?>" <?php echo $sShow?>>&nbsp;<?php _e("Display list name label.",'argwa');?></td>
      <td height="5"><?php echo argwa_get_note('41');?>
      <textarea rows="5" name="sldindisplay" cols="42" id="editorContent"><?php echo $sldindisplay;?></textarea>
      <br /><input type="button" value="<?php _e("Slide-in Footer Height",'argwa');?>">&nbsp;<input type="text" size="3" name="ar_gwa_sldht" value="<?php echo get_option('ar_gwa_sldht_'.$listid); ?>">px
      <br /><input type="button" value="<?php _e("Slide-in Border Width",'argwa');?>"><?php echo $borderwidth2;?>
      <br /><input type="button" onclick="showColorGrid3('sldbg','sbor')" value="<?php _e("Slide-in Border ColorPicker",'argwa');?>"><input type="text" size="8" id="sldbg" name="ar_gwa_sldbor" value="<?php echo get_option('ar_gwa_sldbor_'.$listid); ?>"><input type="text" size="3" id="sbor" style="background-color:<?php echo get_option('ar_gwa_sldbor_'.$listid); ?>">
      <br /><input type="button" onclick="showColorGrid3('sldbkg','sbkgs')" value="<?php _e("Slide-in Background ColorPicker",'argwa');?>"><input type="text" size="8" id="sldbkg" name="ar_gwa_sldbkg" value="<?php echo get_option('ar_gwa_sldbkg_'.$listid); ?>"><input type="text" size="3" id="sbkgs" style="background-color:<?php echo get_option('ar_gwa_sldbkg_'.$listid); ?>">
      <br /><input type="button" onclick="showColorGrid3('sldfg','sfgs')" value="<?php _e("Slide-in Font ColorPicker",'argwa');?>"><input type="text" size="8" id="sldfg" name="ar_gwa_sldfg" value="<?php echo get_option('ar_gwa_sldfg_'.$listid); ?>"><input type="text" size="3" id="sfgs" style="background-color:<?php echo get_option('ar_gwa_sldfg_'.$listid); ?>">
      </td>
    </tr><tr>
      <td height="4"></td>
      <td height="4"><br /><input class="button" type="submit" value="<?php _e("Submit",'argwa'); ?>" name="B1"><input class="button" type="reset" value="<?php _e("Reset",'argwa'); ?>" name="B2"><br /><?php _e("All changes made on page will be submitted.",'argwa'); ?></td>
    </tr>
</table><br />
  <table border="0" style="background-color: rgb(228, 242, 253);;-moz-border-radius: 15px;border-radius: 15px;padding:15px;width:725px;" width="725">
    <tr>
      <td height="5" valign="top"><strong><?php _e("Common List Footer",'argwa');?>:</strong><br />
      		<select name="mType" style="width:100px;" onchange="toggleEditor('ar_gwa_footer')" />
		<option value="html" selected><?php _e("HTML",'argwa');?>
		<?php if(!file_exists(ABSPATH.'wp-content/plugins/autoresponder-gwa/gwa-xinha.txt')) { ?>
		<option value="text"><?php _e("PLAIN TEXT",'argwa');?>
		<?php } ?>
		</select>
</td>
<td height="5"><?php echo argwa_get_note('42');?><textarea rows="5" name="ar_gwa_footer" id="ar_gwa_footer" cols="42"><?php echo get_option('ar_gwa_footer_'.$rec[0]->xID);?></textarea></td></tr>    <tr>
      <td height="4"></td><td height="4"><br /><input class="button" type="submit" value="<?php _e("Submit",'argwa'); ?>" name="B1"><input class="button" type="reset" value="<?php _e("Reset",'argwa'); ?>" name="B2"><br /><?php _e("All changes made on page will be submitted.",'argwa'); ?></td> </tr></table></center></div><input type="hidden" name="act" value="update"><input type="hidden" name="lLID" value="<?php echo $rec[0]->xID; ?>"></form><?php echo '</div></div>';
 }
}

function admin_ar_gwa_queue() { 
global $wpdb,$ctag,$ar_gwa_debug;
if($ar_gwa_debug=="ON") $wpdb->show_errors();
$orderby = strip_tags($_REQUEST['orderby']);
$tbl_name = $wpdb->prefix . "ar_gwa_queue";
if(!isset($orderby) || $orderby=='') $orderby = 'SendDate';
if($_REQUEST['dir']) {
  $dir = 0;
  $orderby .= ' asc';
  } else {
  $dir=1;
  $orderby .= ' desc';  
  }
if($_REQUEST['act'] == 'del')
{
	// delete messages
	$xID = $_REQUEST['lID'];
   for($i = 0; $i < count($xID); $i++)
	 {
		$wpdb->query("DELETE FROM " . $tbl_name . " WHERE newsletterQID='$xID[$i]'");
	 }
	$msg = __("Update successful.",'argwa');
}	

$arSql = "SELECT * FROM " . $tbl_name . " ORDER BY ".$orderby;
$res = $wpdb->get_results($arSql);
if($res) {
#<div id="">
#<div class="wrap">
?><div>
<?php if(isset($msg)) echo '<div id="message" class="updated fade"><p>'.$msg.'</p></div>';?>
<form action="?page=ar_gwa_edit_message" method="post" id="lists-filter">
<h2 style='display:inline;float:left;'><?php printf(__("Manage Queue (%d)",'argwa'),count($res));?></h2><?php echo argwa_get_note('32');?> 
<table class="widefat">
	<thead>
	<tr>
	<th scope="col" class="check-column"><input type="checkbox" onclick="checkAll(document.getElementById('lists-filter'));" /></th>
	<th scope="col"><a href="?page=ar_gwa_queue&orderby=recipientEmail&dir=<?php echo $dir;?>"><?php _e("Email",'argwa');?></a></th>
	<th scope="col"><a href="?page=ar_gwa_queue&orderby=subject&dir=<?php echo $dir;?>"><?php _e("Subject",'argwa');?></a></th>
	<th scope="col"><a href="?page=ar_gwa_queue&orderby=SendDate&dir=<?php echo $dir;?>"><?php _e("Date/Time Queued",'argwa');?></a></th>
	</tr>
	</thead>
	<tbody>
	<tr id='post-1' class='alternate author-self status-publish' valign="top">
<?php
	foreach($res as $row)
	{	
//    $row->xID = ar_gwa_getlistname($row->xID);
	echo '<tr><th scope="row" class="check-column"><input type="checkbox" name="lID[]" value="'.$row->newsletterQID.'" /></th>'
		.'<td><abbr title="'.$row->recepientName.'">'.$row->recepientMail.' ('.$row->recepientName.')</abbr></td>'
		.'<td><abbr title="'.stripslashes(stripslashes($row->subject)).'">'.stripslashes(stripslashes($row->subject)).'</abbr></td><td>'.date('Y-m-d H:i:s',$row->SendDate).'</td></tr>';
  }
  ?>
	</tbody>
<?php
	echo '</table><p>&nbsp;</p>';
	echo '<p><input type="submit" class="button" value="'.__("Delete Checked Above",'argwa').'" name="admin_ar_gwa_queue">&nbsp;&nbsp;<input type="submit" style="color:red;font-weight:bold;" class="button" name="ar_gwa_run" value="'.__("FLUSH QUEUE - SEND MAIL NOW",'argwa').'">';
	echo '<input type="hidden" name="act" value="del"></p>';
	echo '</form>';
?>
</div>
<br class="clear" />
<?php
#</div><!-- wpcontent -->
#</div><!-- wpwrap -->
  } else {
 # echo '<div id=""><div class="wrap"><h2>'.__("Manage Queue",'argwa').'</h2>'.__("No Records",'argwa').'</div></div>';
 echo '<h2>'.__("Manage Queue",'argwa').'</h2>'.argwa_get_note('32').__("No Records",'argwa');
  }
}

function admin_ar_gwa_leads($er=NULL) { 
global $wpdb,$ctag,$ar_gwa_debug;
if($ar_gwa_debug=="ON") $wpdb->show_errors();
if($_REQUEST['admin_ar_gwa_add_leads']!="") {
admin_ar_gwa_add_leads($er);
} else if($_REQUEST['admin_ar_gwa_export_leads']!="") {
admin_ar_gwa_export_leads();
} else {
$orig_order_by = $orderby = strip_tags($_REQUEST['orderby']);
if(!isset($orderby) || $orderby=='') $orderby = 'lName';
if($_REQUEST['dir']) {
  $dir = 0;
  $orderby .= ' desc';
  } else {
  $dir=1;
  $orderby .= ' asc';  
  }
if($_REQUEST['act'] == 'del')
{
	// delete messages
	$lID = $_REQUEST['lID'];
	for($i = 0; $i < count($lID); $i++)
	{
		$wpdb->query("DELETE FROM " . $wpdb->prefix . "ar_gwa_leads WHERE lID='$lID[$i]'");
	}	
}
#print_r($_REQUEST);
$list_num = (int)$_REQUEST['list_num'];
if($list_num<1) $list_num = 25;
$this_start_num = $start_num = (int)$_REQUEST['start_num'];
if($_REQUEST['SUBMIT']=='FILTER') $this_start_num = $start_num = 0;
$finish_num = $start_num+$list_num;
if($_REQUEST['listid']=='-1') {
$qual = 'WHERE lCnf != 1 AND lCnf != 2';
}else if($_REQUEST['listid']=='-2') {
$qual = 'WHERE lCnf = 2';
}else {
$qual = 'WHERE lCnf = 1';
}
if((isset($_REQUEST['listid']) && (int)$_REQUEST['listid']>0)) $qual .= " AND lLID='".$_REQUEST['listid']."'";
$arCnt = "SELECT COUNT(lID) FROM " . $wpdb->prefix . "ar_gwa_leads $qual";
$lCnt = $wpdb->get_var($arCnt);
if($list_num>=(int)$lCnt) { $list_num=$lCnt;$finish_num=$lCnt; }
$arNum = "SELECT COUNT(*) FROM " . $wpdb->prefix . "ar_gwa_leads ".$qual;
$rev = $wpdb->get_var($arNum);
#echo $arNum.$rev.$list_num;
if($_REQUEST['ar_gwa_fwd'] && $rev>=$list_num) $start_num = $start_num+$list_num;
else if($_REQUEST['ar_gwa_back']) $start_num = $start_num-$list_num;
if($start_num<0 || $start_num<$list_num) $start_num=0;
if($_REQUEST['listid']=='-1') {
$qual = 'WHERE lCnf like "ar%"';
$list_num = $lCnt;
}else if($_REQUEST['listid']=='-2') {
$qual = 'WHERE lCnf = 2';
} else {
$qual = 'WHERE lCnf = 1';
}
if((isset($_REQUEST['listid']) && $_REQUEST['listid']>0)) $qual .= " AND lLID='".$_REQUEST['listid']."'";
if(isset($_REQUEST['ar_gwa_search']) && $skey=$_REQUEST['ar_gwa_lead_search']) $qual .= " AND lName like \"%$skey%\" OR lEmail like \"%$skey%\"";
$arSql = "SELECT * FROM " . $wpdb->prefix . "ar_gwa_leads $qual ORDER BY ".$orderby." LIMIT $start_num,$list_num";
$res = $wpdb->get_results($arSql);
if(($start_num) == 0) $no_back=1;
$prev_start_num = $start_num - $list_num;
$back='?page=ar_gwa_leads&orderby='.$orig_order_by.'&listid='.$_REQUEST['listid'].'&start_num='.$prev_start_num.'&list_num='.$list_num;
if(($start_num+$list_num) >= $lCnt) $no_fwd=1;
$fwd='?page=ar_gwa_leads&orderby='.$orig_order_by.'&listid='.$_REQUEST['listid'].'&start_num='.($start_num+$list_num).'&list_num='.$list_num; # added +$listnum for $fwd ??
if($lCnt>0)
  $pNum = ($lCnt/$list_num);
  for($i=0;$i<(int)$pNum;$i++) {
    $start_num = $list_num * $i;
    if($start_num == $this_start_num) $color = 'color:#f00;text-decoration:none;';
     else $color='color:#00f;text-decoration:underline;';
    $pLink .= '<a href="?page=ar_gwa_leads&orderby='.$orig_order_by.'&listid='.$_REQUEST['listid'].'&start_num='.$start_num.'&list_num='.$list_num.'" style="font-size:11pt;font-weight:bolder;'.$color.'">'.($i+1).'</a>'."&nbsp;&nbsp;";
  }
?>
<div id=""> <div id=""><div id=""><div id="">
<div class="wrap"> 
<h2 style="float:left;"><?php _e("Manage Leads",'argwa');?> (<?php _e("Showing",'argwa');?> <?php echo count($res); ?> of <?php echo $lCnt?> :: <?php echo $this_start_num?> - <?php echo $finish_num?>)</h2><div style="float:none;height:70px;"><br /><form action="?page=ar_gwa_leads" method="POST"><strong style="font-size:13pt;"><?php _e("Search",'argwa');?>:</strong> <input type="text" name="ar_gwa_lead_search" value="<?php echo $skey?>" class="input">&nbsp;<input type="submit" name="ar_gwa_search" class="button" value="GO"><input type="hidden" name="listid" value="<?php echo $_REQUEST['listid'];?>"></form><?php echo argwa_get_note('30');?></div>
<form action="?page=ar_gwa_leads" method="POST"><?php echo ar_gwa_buildlistselect($_REQUEST['listid']);?><input type="submit" name="SUBMIT" value="FILTER" class="button"><h3 style="display:inline">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<?php _e("Pagination:",'argwa');?></h3>&nbsp;<?php _e("List",'argwa');?>&nbsp;<input type="textbox" size="2" name="list_num" value="<?php echo $list_num;?>">&nbsp;<?php _e("Records",'argwa');?>. <?php _e("Pages",'argwa');?>: <?php if(!$no_back) { ?><a href="<?php echo $back?>" style="text-decoration:none;font-weight:bolder;">&lt;&lt;</a><?php } ?>&nbsp;<?php echo $pLink;?>&nbsp;<?php if(!$no_fwd) { ?><a href="<?php echo $fwd?>"  style="text-decoration:none;font-weight:bolder;">&gt;&gt;</a><?php } ?><input type="hidden" name="start_num" value="<?php echo $start_num;?>">
<input type="hidden" name="dir" value="<?php echo $_REQUEST['dir']?>">
</form>
<form action="?page=ar_gwa_leads" method="post" id="leads-filter">
<input type="hidden" name="listid" value="<?php echo $_REQUEST['listid'];?>">
<table class="widefat">
	<thead>
	<tr>
	<th scope="col" class="check-column"><input type="checkbox" onclick="checkAll(document.getElementById('leads-filter'));" /></th>
	<th scope="col"><a href="?page=ar_gwa_leads&orderby=lLID&dir=<?php echo $dir;?>&listid=<?php echo $_REQUEST['listid'];?>&start_num=<?php echo $start_num?>&list_num=<?php echo $list_num?>"><?php _e("List",'argwa');?></a></th>
	<th scope="col" width="120"><a href="?page=ar_gwa_leads&orderby=lName&dir=<?php echo $dir;?>&listid=<?php echo $_REQUEST['listid'];?>&start_num=<?php echo $start_num?>&list_num=<?php echo $list_num?>"><?php _e("Name",'argwa');?></a></th>
	<th scope="col" width="200"><a href="?page=ar_gwa_leads&orderby=lEmail&dir=<?php echo $dir;?>&listid=<?php echo $_REQUEST['listid'];?>&start_num=<?php echo $start_num?>&list_num=<?php echo $list_num?>"><?php _e("Email",'argwa');?></a></th>
	<th scope="col" width="70"><a href="?page=ar_gwa_leads&orderby=lMOut&dir=<?php echo $dir;?>&listid=<?php echo $_REQUEST['listid'];?>&start_num=<?php echo $start_num?>&list_num=<?php echo $list_num?>"><?php _e("Msg Out",'argwa');?></th>
	<th scope="col"><a href="?page=ar_gwa_leads&orderby=lDateEntry&dir=<?php echo $dir;?>&listid=<?php echo $_REQUEST['listid'];?>&start_num=<?php echo $start_num?>&list_num=<?php echo $list_num?>"><?php _e("Entry Date",'argwa');?></th>
	<th scope="col"><a href="?page=ar_gwa_leads&orderby=lDateOut&dir=<?php echo $dir;?>&listid=<?php echo $_REQUEST['listid'];?>&start_num=<?php echo $start_num?>&list_num=<?php echo $list_num?>"><?php _e("Date Out",'argwa');?></th>
	</tr>
	</thead>
	<tbody>
	<tr id='post-1' class='alternate author-self status-publish' valign="top">
<?php
if($res) {
	foreach($res as $row)
	{	
$ooid = $row->lID;
$link = '<a title="'.__("Show/Hide",'argwa').'" href="javascript:(void);" onclick="if(document.getElementById(\'gwatable'.$ooid.'\').style.display==\'inline\') document.getElementById(\'gwatable'.$ooid.'\').style.display=\'none\'; else document.getElementById(\'gwatable'.$ooid.'\').style.display=\'inline\';">View Info</a>';
    $row->lLID = ar_gwa_getlistname($row->lLID);
		echo '<tr><th scope="row" class="check-column"><input type="checkbox" name="lID[]" value="'.$row->lID.'" /></th>'
				.'<td><abbr title="'.$row->lLID.'">'.$row->lLID.'</abbr></td>'
				.'<td id="tdname'.$ooid.'"><input  onblur="sss = confirm(\''.__("Confirm changes?",'argwa').'\');if(sss==true)ar_gwa_name_update(document.getElementById(\'argwaleadname'.$ooid.'\'),'.$ooid.');return false;" type="text" name="lLead" id="argwaleadname'.$ooid.'" value="'.$row->lName.'" size="12"><br />'.$link.'</td>'
#				.'<td><abbr title="'.$row->lEmail.'">'.$link.'</abbr></td>'
				.'<td id="tdemail'.$ooid.'"><input  onblur="sss = confirm(\''.__("Confirm changes?",'argwa').'\');if(sss==true)ar_gwa_email_update(document.getElementById(\'argwaleademail'.$ooid.'\'),'.$ooid.',\''.$row->lEmail.'\');return false;" type="text" name="lEmail" id="argwaleademail'.$ooid.'" value="'.$row->lEmail.'" size="22"></td>'
				.'<td id="tdday'.$ooid.'"><input  onblur="sss = confirm(\''.__("Confirm changes?",'argwa').'\');if(sss==true)ar_gwa_day_update(document.getElementById(\'argwaleadday'.$ooid.'\'),'.$ooid.',\''.$row->lEmail.'\');return false;" type="text" name="lMOut" id="argwaleadday'.$ooid.'" value="'.$row->lMOut.'" size="3"></td>'
				.'<td id="tdentry'.$ooid.'">'.$row->lDateEntry.'</td>'
				.'<td>'.$row->lDateOut.'</td></tr>';
echo '<tr><td colspan=7><table style="display:none;" id="gwatable'.$row->lID.'" width="100%"><tr><td><textarea style="display:none;" id="fieldOne'.$ooid.'" onblur="sss = confirm(\''.__("Confirm changes?",'argwa').'\');if(sss==true)ar_gwa_fields_update('.$ooid.',document.getElementById(\'fieldOne'.$ooid.'\'),document.getElementById(\'fieldTwo'.$ooid.'\'),document.getElementById(\'fieldThree'.$ooid.'\'),document.getElementById(\'fieldFour'.$ooid.'\'),document.getElementById(\'fieldFive'.$ooid.'\'));return false;" rows=1 cols=10>
'.$row->lField1.'
</textarea><br />'.$row->lField1.'&nbsp;(<a title="Edit" href="javascript:(void)" onclick="if(document.getElementById(\'fieldOne'.$ooid.'\').style.display==\'inline\') document.getElementById(\'fieldOne'.$ooid.'\').style.display=\'none\'; else document.getElementById(\'fieldOne'.$ooid.'\').style.display=\'inline\';">+</a>)
</td><td>
<textarea style="display:none;" id="fieldTwo'.$ooid.'" onblur="sss = confirm(\''.__("Confirm changes?",'argwa').'\');if(sss==true)ar_gwa_fields_update('.$ooid.',document.getElementById(\'fieldOne'.$ooid.'\'),document.getElementById(\'fieldTwo'.$ooid.'\'),document.getElementById(\'fieldThree'.$ooid.'\'),document.getElementById(\'fieldFour'.$ooid.'\'),document.getElementById(\'fieldFive'.$ooid.'\'));return false;" rows=1 cols=10>
'.$row->lField2.'
</textarea><br />'.$row->lField2.'&nbsp;(<a title="Edit" href="javascript:(void)" onclick="if(document.getElementById(\'fieldTwo'.$ooid.'\').style.display==\'inline\') document.getElementById(\'fieldTwo'.$ooid.'\').style.display=\'none\'; else document.getElementById(\'fieldTwo'.$ooid.'\').style.display=\'inline\';">+</a>)
</td><td>
<textarea style="display:none;" id="fieldThree'.$ooid.'" onblur="sss = confirm(\''.__("Confirm changes?",'argwa').'\');if(sss==true)ar_gwa_fields_update('.$ooid.',document.getElementById(\'fieldOne'.$ooid.'\'),document.getElementById(\'fieldTwo'.$ooid.'\'),document.getElementById(\'fieldThree'.$ooid.'\'),document.getElementById(\'fieldFour'.$ooid.'\'),document.getElementById(\'fieldFive'.$ooid.'\'));return false;" rows=1 cols=10>
'.$row->lField3.'
</textarea><br />'.$row->lField3.'&nbsp;(<a title="Edit" href="javascript:(void)" onclick="if(document.getElementById(\'fieldThree'.$ooid.'\').style.display==\'inline\') document.getElementById(\'fieldThree'.$ooid.'\').style.display=\'none\'; else document.getElementById(\'fieldThree'.$ooid.'\').style.display=\'inline\';">+</a>)
</td><td>
<textarea style="display:none;" id="fieldFour'.$ooid.'" onblur="sss = confirm(\''.__("Confirm changes?",'argwa').'\');if(sss==true)ar_gwa_fields_update('.$ooid.',document.getElementById(\'fieldOne'.$ooid.'\'),document.getElementById(\'fieldTwo'.$ooid.'\'),document.getElementById(\'fieldThree'.$ooid.'\'),document.getElementById(\'fieldFour'.$ooid.'\'),document.getElementById(\'fieldFive'.$ooid.'\'));return false;" rows=1 cols=10>'.$row->lField4.'</textarea><br />'.$row->lField4.'&nbsp;(<a title="Edit" href="javascript:(void)" onclick="if(document.getElementById(\'fieldFour'.$ooid.'\').style.display==\'inline\') document.getElementById(\'fieldFour'.$ooid.'\').style.display=\'none\'; else document.getElementById(\'fieldFour'.$ooid.'\').style.display=\'inline\';">+</a>)</td><td><textarea style="display:none;" id="fieldFive'.$ooid.'" onblur="sss = confirm(\''.__("Confirm changes?",'argwa').' '.$row->lEmail.'?\');if(sss==true)ar_gwa_fields_update('.$ooid.',document.getElementById(\'fieldOne'.$ooid.'\'),document.getElementById(\'fieldTwo'.$ooid.'\'),document.getElementById(\'fieldThree'.$ooid.'\'),document.getElementById(\'fieldFour'.$ooid.'\'),document.getElementById(\'fieldFive'.$ooid.'\'));return false;" rows=1 cols=10>'.$row->lField5.'</textarea><br />'.$row->lField5.'&nbsp;(<a title="Edit" href="javascript:(void)" onclick="if(document.getElementById(\'fieldFive'.$ooid.'\').style.display==\'inline\') document.getElementById(\'fieldFive'.$ooid.'\').style.display=\'none\'; else document.getElementById(\'fieldFive'.$ooid.'\').style.display=\'inline\';">+</a>)</td></tr></table></td></tr>';				
  }
} else {
 echo '<tr><td colspan=7 align="center">'.__("No Records",'argwa').'</td></tr>';
}
  ?>
	</tbody></table>
<?php
	echo '</table><CENTER>'.__("Pages",'argwa').':'.$pLink.'</CENTER>';
	echo '<p><input type="submit" class="button" value="'.__("Delete Checked",'argwa').'">';
	echo '&nbsp;<input type="submit" class="button" value="'.__("Import Leads",'argwa').'" name="admin_ar_gwa_add_leads">';
	echo '&nbsp;<input type="submit" class="button" value="'.__("Export Leads",'argwa').'" name="admin_ar_gwa_export_leads">';
	echo '<input type="hidden" name="act" value="del"></p>';
	echo '</form>';
?><?php echo $ctag?>
<div id="ajax-response"></div>
</div>
<?php
 }
?>
</div><!-- wpbody -->
</div><!-- wpcontent -->
</div><!-- wpwrap --> 
<?php
}

function admin_ar_gwa_add_leads($er=NULL) {
global $wpdb,$ctag,$ar_gwa_debug,$phpmailerDir,$ar_gwa_enc,$ar_gwa_enc2;
$trx = new ar_gwa_internationalized();
if($ar_gwa_debug=="ON") $wpdb->show_errors();
if(($_REQUEST['lEmail']=="" && $_REQUEST['lName']=="" && ($_REQUEST['addresses']!='' && preg_match("/\n/",$_REQUEST['addresses'])) && $_REQUEST['act']=="add")) { 
 if(!preg_match("/,/",$_REQUEST['addresses']) || !$_REQUEST['listid']) { 
 $g_error[] = 23; ar_gwa_showError($g_error);
 } else {
  $lines2 = array();
  $lines = preg_split("/\n/",$_REQUEST['addresses']);
  $dups=0;
  foreach($lines as $ttline) {
if($ttline[0]!='' && $ttline[1]!=''){
  $tttline = preg_split("/,/",$ttline);
  $tttline[1] = preg_replace("/\s+/",'',$tttline[1]);
  $tttline[1] = preg_replace("/\n+/",'',$tttline[1]);
unset($llid);if($tttline[1]!='' && $tttline[0]!='') $llid = $wpdb->get_var("SELECT lID FROM ".$wpdb->prefix."ar_gwa_leads WHERE lEmail LIKE '%".$tttline[1]."%' AND lLID='".$_REQUEST['listid']."'");
    if($llid>0) {
      $dups++; 
}    else if(isset($ttline)){
      $lines2[] = $ttline;  
}
}
}
if(count($lines2)>0 && (!$_REQUEST['confirm_leads'])) {
  foreach($lines2 as $tline) {
   $qry = "INSERT INTO ".$wpdb->prefix."ar_gwa_leads (lLID,lName,lEmail,lField1,lField2,lField3,lField4,lField5,lDateEntry,lDateOut,lMOut,lCnf,lIP,lDNS) VALUES ";
   $line = preg_split("/,/",$tline);
   if($line[0]!='' && $line[1]!='') {
  $to = mysql_real_escape_string(str_replace("\r\n", "", trim($line[0])));
  $name = mysql_real_escape_string(trim($line[1]));
  if($line[2]!='')
  $field1 = mysql_real_escape_string($line[2]);
  if($line[3]!='')
  $field2 = mysql_real_escape_string($line[3]);
  if($line[4]!='')
  $field3 = mysql_real_escape_string($line[4]);
  if($line[5]!='')
  $field4 = mysql_real_escape_string($line[5]);
  if($line[6]!='')
  $field5 = mysql_real_escape_string($line[6]);

    $qry .= "('".$_REQUEST['listid']."','".$to."','".$name."','".$field1."','".$field2."','".$field3."','".$field4."','".$field5."',current_date, current_date, '-1','1','','')";
#    $qry = substr($qry, 0, -2);
    $wpdb->query($qry);
		$ms = new MailProcess();
		if( $ms->setLead($wpdb->insert_id) && $ms->setMsg(0,$_REQUEST['listid']))
		{
		 if(isset($_POST['sendwelcome'])) {
		  $ms->mailLead(0,$wpdb->insert_id);
     } else {
      $subq = "lMOut='0', ";
	  	$qry = "UPDATE ".$wpdb->prefix."ar_gwa_leads SET $subq lDateOut=current_date WHERE lID='".$wpdb->insert_id."'";
      $wpdb->query($qry);     
     }
    }
    } // end if line 1...    
   } 
  } else if(count($lines2)>0) {
  $listid = $_REQUEST['listid'];
//send cnofirn
 foreach($lines2 as $tline) {
 $to='';$name='';
   $line = preg_split("/,/",$tline);
   if($line[0]!='' && $line[1]!='') {
  $name = mysql_real_escape_string(trim($line[0]));
  $to = mysql_real_escape_string(str_replace("\r\n", "", trim($line[1])));
      $dt = date('Y-m-d H:i:s');
    $ip = $_SERVER['REMOTE_ADDR'];
    $dns = gethostbyaddr($ip);
    $i_url = get_bloginfo('url').'/index.php';
  if($line[2]!='')
  $field1 = mysql_real_escape_string($line[2]);
  if($line[3]!='')
  $field2 = mysql_real_escape_string($line[3]);
  if($line[4]!='')
  $field3 = mysql_real_escape_string($line[4]);
  if($line[5]!='')
  $field4 = mysql_real_escape_string($line[5]);
  if($line[6]!='')
  $field5 = mysql_real_escape_string($line[6]);

  $pword='ar';
  $vals = "ABCDEFGHIJKLMNOPQRSTUVWXYZabchefghjkmnpqrstuvwxyz0123456789";           
  while (strlen($pword) < 21) {
                mt_getrandmax();  // Returns the maximum value that can be returned by a call  rand
                $num = rand(1,strlen($vals));
                $tmp = substr($vals, $num+4, 1);
                $pword = $pword . $tmp;
                $tmp ="";
  }
    $lCnf = $pword;
#    $to = "$lEmail";
    $from = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix."ar_gwa_lists WHERE xID='$listid'");
    $subj = html_entity_decode(sprintf($trx->gwa_intn('conf_subj'),$from->xName)."\r\n",ENT_NOQUOTES,'UTF-8');
    $msg = sprintf($trx->gwa_intn('conf_subj'),$from->xName)."\r\n";
    $msg .= "\r\n".$trx->gwa_intn('click_here')."-> ".$i_url."?r=$lCnf\r\n\r\n";
    $msg .= sprintf($trx->gwa_intn('signup_detail'),$ip,$dns,$dt);
    $msg .= sprintf($trx->gwa_intn('disclaimer'),get_bloginfo('url'));
    $nicename = $from->xName;
    if(get_option('ar_gwa_smtp_auth')!='checked') {
    if($wwrap = get_option('ar_gwa_wrap')) $msg = wordwrap($msg,$wwrap,"\r\n");
    $suc = mail($to,$subj,$msg."\r\n","From: $nicename <{$from->xEmail}>"."\r\n"."Mime-Version: 1.0\nContent-Type: text/plain; charset=$ar_gwa_enc\nContent-Transfer-Encoding: $ar_gwa_enc2\n",'-f'.$from->xEmail);    
#    $suc = mail($to,$subj,$msg,"From: $nicename <{$from->xEmail}>"."\r\n"."Mime-Version: 1.0\r\nContent-Type: text/plain; charset=$ar_gwa_enc\r\nContent-Transfer-Encoding: $ar_gwa_enc2\r\n",'-f'.$from->xEmail);
    if(!$suc) $suc = mail($to,$subj,$msg."\r\n","From: $nicename <{$from->xEmail}>"."\r\n"."Mime-Version: 1.0\nContent-Type: text/plain; charset=$ar_gwa_enc\nContent-Transfer-Encoding: $ar_gwa_enc2\n");
    } else {
    $mail['method']='smtp';
    $mail['Host'] = get_option('ar_gwa_smtp_srv');
    $mail['Username'] = get_option('ar_gwa_smtp_user');
    $mail['Password'] = get_option('ar_gwa_smtp_pass');
    $mail['From'] = $from->xEmail;
    $mail['FromName'] = $nicename;
    $mail['recepientMail'] = $to;
    $mail['recepientName'] = $name;
    $mail['subject'] = $subj;
    $mail['body'] = $msg;
    $mails[] = $mail;
    if (! class_exists('PHPMailer'))
      include($phpmailerDir.'/class.phpmailer.php');    
    $newsletter = new newsletter;
    $suc = $newsletter->SendMail($mails);    
    }
     $qry = "INSERT INTO ".$wpdb->prefix."ar_gwa_leads (lLID,lName,lEmail,lField1,lField2,lField3,lField4,lField5,lDateEntry,lDateOut,lMOut,lCnf,lIP,lDNS) VALUES ";
    $qry .= "('".$_REQUEST['listid']."','$name','$to','".$field1."','".$field2."','".$field3."','".$field4."','".$field5."',current_date, current_date, '-1','$lCnf','','')";
    $wpdb->query($qry);    
  }
 } // end forch
  }
 }
 $success = count($lines2);
}
else if ($_REQUEST['lEmail'] && $_REQUEST['lName'])
{
  $listid = $_REQUEST['listid'];
	$qry = "SELECT * FROM ".$wpdb->prefix."ar_gwa_leads WHERE lEmail='".$_REQUEST['lEmail']."' AND lLID='".$_REQUEST['listid']."'";
	if($wpdb->get_results($qry) && $er==0) { $g_error[] = 10; }
	else if($er==1) { $g_error[] = 9; }
	if(!count($g_error))
	{	
	if(!$_REQUEST['confirm_leads']) {
		// insert lead
		$qry = "INSERT INTO ".$wpdb->prefix."ar_gwa_leads(lLID, lName, lEmail, lDateEntry, lDateOut, lMOut,lCnf,lIP,lDNS) VALUES('".$_REQUEST['listid']."','".mysql_real_escape_string($_REQUEST['lName'])."', '".mysql_real_escape_string($_REQUEST['lEmail'])."' ,current_date, current_date, '-1','1','','')";
		$wpdb->query($qry);
		$ms = new MailProcess();
		if( $ms->setLead($wpdb->insert_id) && $ms->setMsg(0,$_REQUEST['listid']))
		{
		 if(isset($_POST['sendwelcome'])) {
		  $ms->mailLead(0,$wpdb->insert_id);
     } else {
      $subq = "lMOut='0', ";
	  	$qry = "UPDATE ".$wpdb->prefix."ar_gwa_leads SET $subq lDateOut=current_date WHERE lID='".$wpdb->insert_id."'";
      $wpdb->query($qry);     
     }
    admin_ar_gwa_leads(1);
    } else
		_e('Missed','argwa').' '.$wpdb->insert_id.' '.__("Leads",'argwa');
	 } else {
    $dt = date('Y-m-d H:i:s');
    $ip = $_SERVER['REMOTE_ADDR'];
    $dns = gethostbyaddr($ip);
    $i_url = get_bloginfo('url').'/index.php';
  if($line[2]!='')
  $field1 = mysql_real_escape_string($line[2]);
  if($line[3]!='')
  $field2 = mysql_real_escape_string($line[3]);
  if($line[4]!='')
  $field3 = mysql_real_escape_string($line[4]);
  if($line[5]!='')
  $field4 = mysql_real_escape_string($line[5]);
  if($line[6]!='')
  $field5 = mysql_real_escape_string($line[6]);

  $pword='ar';
  $vals = "ABCDEFGHIJKLMNOPQRSTUVWXYZabchefghjkmnpqrstuvwxyz0123456789";           
  while (strlen($pword) < 21) {
                mt_getrandmax();  // Returns the maximum value that can be returned by a call  rand
                $num = rand(1,strlen($vals));
                $tmp = substr($vals, $num+4, 1);
                $pword = $pword . $tmp;
                $tmp ="";
  }
    $lCnf = $pword;
    $to = mysql_real_escape_string($_REQUEST['lEmail']);
    $name = mysql_real_escape_string($_REQUEST['lName']);
    $from = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix."ar_gwa_lists WHERE xID='$listid'");
    $subj = html_entity_decode(sprintf($trx->gwa_intn('conf_subj'),$from->xName)."\r\n",ENT_NOQUOTES,'UTF-8');
    $msg = sprintf($trx->gwa_intn('conf_subj'),$from->xName)."\r\n";
    $msg .= "\r\n".$trx->gwa_intn('click_here')."-> ".$i_url."?r=$lCnf\r\n\r\n";
    $msg .= sprintf($trx->gwa_intn('signup_detail'),$ip,$dns,$dt);
    $msg .= sprintf($trx->gwa_intn('disclaimer'),get_bloginfo('url'));
    $nicename = $from->xName;
    if(get_option('ar_gwa_smtp_auth')!='checked') {
    if($wwrap = get_option('ar_gwa_wrap')) $msg = wordwrap($msg,$wwrap,"\r\n");
    $suc = mail($to,$subj,$msg."\r\n","From: $nicename <{$from->xEmail}>"."\r\n"."Mime-Version: 1.0\nContent-Type: text/plain; charset=$ar_gwa_enc\nContent-Transfer-Encoding: $ar_gwa_enc2\n",'-f'.$from->xEmail);
#    $suc = mail($to,$subj,$msg,"From: $nicename <{$from->xEmail}>"."\r\n"."Mime-Version: 1.0\r\nContent-Type: text/plain; charset=$ar_gwa_enc\r\nContent-Transfer-Encoding: $ar_gwa_enc2\r\n",'-f'.$from->xEmail);
    if(!$suc) mail($to,$subj,$msg."\r\n","From: $nicename <{$from->xEmail}>"."\r\n"."Mime-Version: 1.0\nContent-Type: text/plain; charset=$ar_gwa_enc\nContent-Transfer-Encoding: $ar_gwa_enc2\n");
    } else {
    $mail['method']='smtp';
    $mail['Host'] = get_option('ar_gwa_smtp_srv');
    $mail['Username'] = get_option('ar_gwa_smtp_user');
    $mail['Password'] = get_option('ar_gwa_smtp_pass');
    $mail['From'] = $from->xEmail;
    $mail['FromName'] = $nicename;
    $mail['recepientMail'] = $to;
    $mail['recepientName'] = $name;
    $mail['subject'] = $subj;
    $mail['body'] = $msg;
    $mails[] = $mail;
    if (! class_exists('PHPMailer'))
      include($phpmailerDir.'/class.phpmailer.php');    
    $newsletter = new newsletter;
    $suc = $newsletter->SendMail($mails);    
    }
     $qry = "INSERT INTO ".$wpdb->prefix."ar_gwa_leads (lLID,lName,lEmail,lField1,lField2,lField3,lField4,lField5,lDateEntry,lDateOut,lMOut,lCnf,lIP,lDNS) VALUES ";
    $qry .= "('".$_REQUEST['listid']."','$name','$to','".$field1."','".$field2."','".$field3."','".$field4."','".$field5."',current_date, current_date, '-1','$lCnf','','')";
    $wpdb->query($qry);
	 }
  } else {
   ar_gwa_showError($g_error);
#    admin_ar_gwa_leads();
  } 
} else if((is_array($_REQUEST['copy2']) || isset($_REQUEST['submit_export_list'])) && isset($_REQUEST['listid']) && ($listid = $_REQUEST['listid'])) {
  $dups=0;
#  print "here";
  
#print_r($_REQUEST);
  foreach($_REQUEST['copy2'] as $ttline) {
#print_r($ttline);
  $tttline = preg_split("/,/",$ttline);
  $tttline[1] = preg_replace("/\s+$/",'',$tttline[1]);
  $tttline[1] = preg_replace("/\n+$/",'',$tttline[1]);
    if(!($wpdb->query("SELECT * FROM ".$wpdb->prefix."ar_gwa_leads WHERE lEmail='".$tttline[1]."' AND lLID='".$_REQUEST['listid']."'"))) {
      $lines2[] = $ttline;  
   } else $dups++; 
  }
if(count($lines2)>0) {
  foreach($lines2 as $tline) {
     $qry = "INSERT INTO ".$wpdb->prefix."ar_gwa_leads (lLID,lName,lEmail,lField1,lField2,lField3,lField4,lField5,lDateEntry,lDateOut,lMOut,lCnf,lIP,lDNS) VALUES ";
   $line = preg_split("/,/",$tline);
  if($line[0]!='' && $line[1]!='') {
$qury ="SELECT * FROM ".$wpdb->prefix."ar_gwa_leads WHERE lEmail='".$line[1]."' AND lLID='".$_REQUEST['olistid']."'";
$rww = $wpdb->get_row($qury,ARRAY_A);
  if($rww['lField1']!='')
  $field1 = mysql_real_escape_string($rww['lField1']);
  if($rww['lField2']!='')
  $field2 = mysql_real_escape_string($rww['lField2']);
  if($rww['lField3']!='')
  $field3 = mysql_real_escape_string($rww['lField3']);
  if($rww['lField4']!='')
  $field4 = mysql_real_escape_string($rww['lField4']);
  if($rww['lField5']!='')
  $field5 = mysql_real_escape_string($rww['lField5']);
    $qry .= "('".$_REQUEST['listid']."','".mysql_real_escape_string($line[0])."','".mysql_real_escape_string($line[1])."','".$field1."','".$field2."','".$field3."','".$field4."','".$field5."',current_date, current_date, '-1','1','','')";
}
    $wpdb->query($qry);
		$ms = new MailProcess();
		if( $ms->setLead($wpdb->insert_id) && $ms->setMsg(0,$_REQUEST['listid']))
		{
		 if(isset($_POST['sendwelcome'])) {
		  $ms->mailLead(0,$wpdb->insert_id);
     } else {
      $subq = "lMOut='0', ";
	  	$qry = "UPDATE ".$wpdb->prefix."ar_gwa_leads SET $subq lDateOut=current_date WHERE lID='".$wpdb->insert_id."'";
      $wpdb->query($qry);     
     }
    }    
   } 
  }

}  else if($_REQUEST['act']=="add"){
 $g_error[] = 12; 
 ar_gwa_showError($g_error);
}
?>
<script type="text/javascript">
function gwaCheckCount() {
if(document.getElementById('gwawelcome').checked & document.getElementById('gwaconfirm').checked) {
alert("<?php _e("You cannot send both Confirm and Welcome messages?",'argwa');?>");
return false;
}
if(!document.getElementById('gwaaddresses').value && !document.getElementById("gwaemail").value) {
alert("No leads to import?");
return false;
} else {
var temp = new Array();
var gwab = document.getElementById('gwaaddresses').value;
gwatemp = gwab.split("\n");
var gwac = gwatemp.length;
if(gwac>100) {
alert("<?php _e("Maximum Import of 100 Leads at a time.",'argwa');?>"+"\n"+"<?php _e("You have attempted to import",'argwa');?>"+" "+gwac+" "+"<?php _e("leads.",'argwa');?>");
return false;
}
}
return confirm('<?php _e("Did you select the correct list? Cancel and check now!",'argwa');?>');
}
</script><div id=""> <div id=""><div id=""><div id=""><div><div class="wrap"><form method="post" action="?page=ar_gwa_leads" onsubmit="return gwaCheckCount()">
<h2><?php _e("Add Lead",'argwa');?></h2><input type="hidden" name="act" value="add"><?php
if($success>0) echo '<div id="message" class="updated fade">
  <p>'.sprintf(__("Successfully added %d addresses.",'argwa'),$success).'</p>
  </div>';
if($dups>0) echo '<div id="message" class="error fade"><p>'.sprintf(__("There were %d duplicates that were already on the list.",'argwa'),$dups).'</p></div>';
?>
<table align="center">
	<tr>
		<td><?php _e("LIST",'argwa');?>:&nbsp;&nbsp;&nbsp;<?php echo ar_gwa_buildlistselect($_REQUEST['listid']); ?> <strong style="color:red"><?php _e("* SELECT LIST *",'argwa');?></strong></td>
	</tr>
	<tr>
		<td><?php _e("NAME",'argwa');?>: <input id="gwaname" type="text" name="lName" maxlength="250" style="width:270px;"></td>

	</tr>
	<tr>
		<td><?php _e("EMAIL",'argwa');?>: <input id="gwaemail" type="text" name="lEmail" maxlength="250" style="width:270px;"></td>
	</tr>
	<tr>
		<td><input type="submit" class="button" value="<?php _e("Add New Lead",'argwa');?>" name="admin_ar_gwa_add_leads"></td>
	</tr>
  <tr>
  <td>
<p><input id="gwawelcome" type="checkbox" name="sendwelcome" value="on"> <?php _e("Send first email as if members just subscribed.",'argwa');?></p>
<p><input id="gwaconfirm" type="checkbox" name="confirm_leads" value="on"> <?php _e("Send confirm link (click request) to subscribe.",'argwa');?></p>
<h3><?php _e("Bulk Import Form",'argwa');?></h3><p><?php _e("COPY&PASTE your email address list in the '.csv' format.",'argwa')?><br /><?php _e("Each line must end with a single carriage return.",'argwa')?><br /><?php _e("Separate name followed by their email with a comma.",'argwa')?><br /><?php _e("You must enter at least one name & address per line.",'argwa')?><br /><?php _e("You MAY enter 5 additional fields on the same line also separated by comma.",'argwa');?><br /><?php _e("Add single addresses with additional data fields below.",'argwa');?><br /><?php _e("End each line below with a carriage return (press enter.)",'argwa');?><br /><?php _e("DUPLICATES WILL BE PRUNED FROM YOUR LIST.",'argwa');?><br /><span style="color:#f00"><?php _e("MAXIMUM OF 100 LEADS CAN BE IMPORTED AT ONCE.",'argwa');?></span>
</p>
<textarea id="gwaaddresses" name="addresses" cols=80 rows=25></textarea><br />
<input type="submit" class="button" value="<?php _e("Add New Lead",'argwa');?>" name="admin_ar_gwa_add_leads" onClick="return confirm('Did you select the correct list? Cancel and check now!');">
</td></tr></table>
</form><br /><?php echo $ctag?>
			</div>
			</div>

<?php
 }

function gwa_user_has_role( $user_id,$roles_to_check=array() ) {
  if( ! $roles_to_check ) return FALSE;
  if( ! $user_id )  return FALSE;
  $user = new WP_User( $user_id );
  foreach($roles_to_check as $role) { if(in_array( $role, $user->roles, FALSE )) return true;  }
}
 
function admin_ar_gwa_email_leads() {
global $wpdb,$ctag,$ar_gwa_debug,$phpmailerDir,$wp_roles;
if($ar_gwa_debug=="ON") $wpdb->show_errors();
if(isset($_REQUEST['testmessage']) && isset($_REQUEST['listid']) && ($_REQUEST['listid']>0)) {
//SEND TEST MESSAGE TO ADMIN
 $_REQUEST['act']='';
     $from = $wpdb->get_row("SELECT * FROM `".$wpdb->prefix."ar_gwa_lists` WHERE xID='{$_REQUEST['listid']}'");
 if($_REQUEST['tmAddress'])
  $to = $_REQUEST['tmAddress'];
 else
  $to = $from->xEmail;//get_bloginfo('email');
     $subj = $_REQUEST['mSubject'];
     $msg = $_REQUEST['mBody'];
    if($_REQUEST['mType']=='html')
    $mail['ContentType'] = 'text/html';
    $checked = get_option('ar_gwa_smtp_auth');
    if(isset($_REQUEST['mTop']) || isset($_REQUEST['mBot'])) {
    $ararg1 = $wpdb->escape($_REQUEST['mTop']);
    $ararg2 = $wpdb->escape($_REQUEST['mBot']);
    if((isset($ararg1) || isset($ararg2))) {
    if(class_exists('ar_gwa_template') && ($tb = new ar_gwa_template))
    list($top,$bot) = $tb->addAction($ararg1,$ararg2);
    }}
    if($checked=='checked') {
    $mail['method']='smtp';
    $mail['SMTPAuth']=true;
    } else {
    $mail['method']='mail';
    }
    $mail['Host'] = get_option('ar_gwa_smtp_srv');
    $mail['Username'] = get_option('ar_gwa_smtp_user');
    $mail['Password'] = get_option('ar_gwa_smtp_pass');
    $mail['From'] = $from->xEmail;
    $mail['FromName'] = $from->xEmail;
    $mail['recepientMail'] = $to;
    $mail['recepientName'] = $to;
    $mail['subject'] = $subj;
    $mail['body'] = $top.$msg.$bot;
    $mails[] = $mail;
    if (! class_exists('PHPMailer'))
      include($phpmailerDir.'/class.phpmailer.php');    
    $newsletter = new newsletter;
    $suc = $newsletter->SendMail($mails);    
if($suc) echo '<div id="message" class="updated fade"><p>'.$i.__("Test message sent to",'argwa').' '.$to.'</p></div>'; else echo '<div id="message" class="updated fade"><p>'.$i.__("FAILED sending test message sent to",'argwa').' '.$to.'</p></div>';
}
if($_REQUEST['act']!=filter) {
if(!file_exists(ABSPATH.'wp-content/plugins/autoresponder-gwa/gwa-xinha.txt')){
$sendWPRoles = $wp_roles->get_names(); foreach($sendWPRoles as $x=>$y) {$sendWPRole .= '<option value="'.$x.'">'.$y.'</option>';}
if (function_exists('wp_tiny_mce')) wp_tiny_mce( false ,
array(
"editor_selector" => "editorContent",
"plugins" => "spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
"theme_advanced_buttons1" => "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
"theme_advanced_buttons2" => "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
"theme_advanced_buttons3" => "hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen,|,spellchecker",
"extended_valid_elements" => "form[*],div[*],style[*],p[*],table[*],td[*]",
"skin" => "o2k7",
"skin_variant" => "silver",)
);
?>
<script type="text/javascript">
<!--
function toggleEditor(id) {
	if (!tinyMCE.getInstanceById(id))
		tinyMCE.execCommand('mceAddControl', false, id);
	else
		tinyMCE.execCommand('mceRemoveControl', false, id);
}
toggleEditor('editorContent');
-->
</script><?php } ?><div><div><div><div class="wrap"><h2><?php _e("Email Leads",'argwa');?></h2><form name="form1" method="post" action="?page=ar_gwa_edit_message" onSubmit="return validate();">
<h3><?php _e("FILTER LEADS",'argwa');?></h3>
<table align="center">
	<tr>
		<td width=140><strong style="color:red;font-size:12pt;"><?php _e("SELECT",'argwa')?><br><?php _e("MAIL LIST",'argwa');?>:</strong></td><td><?php echo ar_gwa_buildlistselect($_REQUEST['listid']); ?></td><td>&nbsp;</td>
</tr><tr>
<td colspan=2><div id="sendWPRole" style="display:none;width:530px;"><?php _e('Select MULTIPLE using [CTRL] key.','argwa');?>&nbsp;<select style="height:100px;overflow:auto;" class="sendWPRole" size=5 name="sendWPRole[]" multiple="MULTIPLE" /><?php echo $sendWPRole;?></select></div><br />
<?php _e("Only email leads added either before and/or after the dates entered below. Leave blank to email entire list.",'argwa');?>
</td><td>&nbsp;</td></tr>
<tr>
		<td><?php _e("Added after",'argwa');?></td>
		<td width="290"><input type="text" name="fADate" style="width:80px;" maxlength="10" value="<?php echo $_REQUEST['fADate']; ?>"> yyyy-mm-dd</td>
		<td width="90"></td>
	</tr>
	<tr>
		<td><?php _e("Added before",'argwa');?></td>
		<td><input type="text" name="fBDate" style="width:80px;" maxlength="10" value="<?php echo $_REQUEST['fBDate']; ?>"> yyyy-mm-dd</td>
		<td></td>
	</tr>
</table>
<h3><?php _e("MESSAGE",'argwa');?></h3>
<table align="center">
<?php
if(class_exists('ar_gwa_template') && ($tb = new ar_gwa_template)) {
   echo $tb->addForm();
  }
if(class_exists('ar_gwa_newsletter') && ($te = new ar_gwa_newsletter)) {
   echo $te->addForm();
  }
if($_REQUEST['mType']!='text'){
$slect = 'selected';
} else {
$select = 'selected';
unset($slect);
}
?>	<tr>
		<td><?php _e("TYPE",'argwa');?></td>
		<td>
		<select name="mType" style="width:100px;" onchange="toggleEditor('editorContent')" />
		<option value="html" selected><?php _e("HTML",'argwa');?>
<?php if(!file_exists(ABSPATH.'wp-content/plugins/autoresponder-gwa/gwa-xinha.txt')){ ?> 
		<option value="text"><?php _e("PLAIN TEXT",'argwa');?>
<?php } ?>
		</select>
		</td>
	</tr>
	<tr>
		<td><?php _e("SUBJECT",'argwa');?></td>
		<td><input type="text" name="mSubject" style="width:325px;" maxlength="254" value="<?php echo $_REQUEST['mSubject']; ?>"><?php echo argwa_get_note('44');?></td>
	</tr>
		<tr><td>&nbsp;</td>
		<td style="background-color:#e4f2fd;border:solid 1px #f00;padding:5px;width:450px;"><?php _e('<strong>We HATE SPAM!</strong> And so does the FTC. Fines for sending spam can be as high as $11,000 per violation! Protect yourself. Know the law.','argwa');?><br><a href="http://www.ftc.gov/bcp/edu/pubs/business/ecommerce/bus61.shtm" title="<?php _e('Opens in a new Window.','argwa');?>" target="_blank"><?php _e('Click here to see the Can-Spam Act.','argwa');?></a></td>
	</tr>

	<tr>
		<td valign="top"><?php _e("BODY",'argwa');?></td>
		<td><textarea id="editorContent" name="mBody" style="width:600px; height:400px;"><?php echo htmlentities($_REQUEST['mBody']); ?></textarea></td>
	</tr>
<tr>
		<td>&nbsp;</td><td style="background-color:#e4f2fd;border:solid 1px #22ff55;padding:5px;width:450px;"><?php _e('<strong>Personalize your Messages!</strong> <span style="color:#f00">*USE ONLY THE TAGS BELOW*</span><br />Use these custom tags when mailing your lists from this page.','argwa');?>  <strong style="font-size:9pt;"> <&#63;Name&#63;> <&#63;Email&#63;> <&#63;Unsubscribe&#63;> <&#63;Archive&#63;> <&#63;Field1&#63;> <&#63;Field2&#63;> <&#63;Field3&#63;> <&#63;Field4&#63;> <&#63;Field5&#63;> <?php if(file_exists(dirname(__FILE__).'/ar_gwa_user_edit.php'))echo "<&#63;Update&#63;>";?></strong></td>
</tr>
	<tr>
		<td>&nbsp;</td>
		<td><input type="submit" class="button" value="<?php _e("Send Test Message",'argwa');?>" name="testmessage">&nbsp;<input type="text" name="tmAddress" style="width:155px;" maxlength="254" value="<?php echo $to; ?>">&nbsp;<input type="submit" class="button" value="<?php _e("Send Mass Mailing >>",'argwa');?>" name="admin_ar_gwa_send_message" onclick="return confirm('<?php _e("SENDING MESSAGE NOW. Are you sure?",'argwa');?>')"><br /><small><?php _e("Enter an email address above for testing or leave blank to send a test message<br />to the <strong>From:</strong> address for this list. Click <strong>Send Mass Mailing</strong> to blast your list!",'argwa');?></small></td></tr><tr><td>&nbsp;</td><td><?php   if(class_exists('ar_gwa_attach')) { echo "&nbsp;<span style='color:#00f;font-weight:bold;'>".__("ATTACH FILE:",'argwa')."</span>&nbsp;".admin_ar_gwa_attach($row['mAttach']).''; } ?></td></tr>
</table>
<script type="text/javascript">
 function toggle($i) {
   if($i==1) { document.getElementById('sendWPRole').style.display = ''} else { document.getElementById('sendWPRole').style.display = 'none'}
 }
</script>
<input type="hidden" name="act" value="filter">
</form></div>
<?php
 } else if($_REQUEST['listid']=='sendWPMessage'){
	$after  = $_REQUEST['fADate'];
	$before = $_REQUEST['fBDate'];

	if(!$after)
	{
		$qry = "SELECT user_registered FROM ".$wpdb->prefix."users ORDER BY user_registered LIMIT 0,1";
  	$after = $wpdb->get_var($qry);
	}
	
	if(!$before) 
	{
		$before = $wpdb->get_var("SELECT current_date");
	}
	
	echo '<div id=""><div class="wrap"><h2>'.__("Email Leads",'argwa').'</h2>.';
echo '<form action="#" method="POST">'.ar_gwa_buildlistselect($_REQUEST['listid']).' <input type="submit" name="SUBMIT" value="FILTER" class="button"></form>';
if(isset($_REQUEST['mTop']) || isset($_REQUEST['mBot'])) {
 $ararg1 = $wpdb->escape($_REQUEST['mTop']);
 $ararg2 = $wpdb->escape($_REQUEST['mBot']);
 if((isset($ararg1) || isset($ararg2))) {
  if(class_exists('ar_gwa_template') && ($tb = new ar_gwa_template))
   list($top,$bot) = $tb->addAction($ararg1,$ararg2);
  }
}	
	$qry = "SELECT * FROM ".$wpdb->prefix."users WHERE user_registered >= '$after' AND user_registered <= '$before'";
#echo $qry;
	$res = $wpdb->get_results($qry,ARRAY_A);
	if($res)
	{
	$stime = time();
		// vars
		$ms 		= new MailProcess(); 
    $lEmailed 	= 0; 
		$aMsg		= array('mType' => $wpdb->escape($_REQUEST['mType']), 'mSubject' =>$wpdb->escape($_REQUEST['mSubject']), 'mBody' => $top.$wpdb->escape($_REQUEST['mBody']).$bot);
		
		// Newsleteer
		if(class_exists('ar_gwa_newsletter'))
		if(isset($_REQUEST['nlTop']) && ($_REQUEST['nlTop']!=0))
    $aMsg['mBody'] = str_replace("{CONTENT}", $aMsg['mBody'], $wpdb->get_var("SELECT content FROM `".$wpdb->prefix."ar_gwa_newsletter` WHERE id='{$_REQUEST['nlTop']}'"));
    //
      
		if($_REQUEST['ar_gwa_filename']) $aMsg['mAttach'] = $_REQUEST['ar_gwa_filename']; 

	if($ar_gwa_debug=="ON") {
	   echo '<form>Address Array:<br><textarea cols=100 rows=10>';
     print_r($res);
	   echo '</textarea></form>';
	}
		foreach($res as $row) 
		{
      if(gwa_user_has_role( $row['ID'],$_REQUEST['sendWPRole'])) {
			if($ms->setWPLead($row['ID']) && $ms->setMsg2($aMsg))
			{
				$ms->mailWPLead();
				++$lEmailed;
      }			
     }			
		}
	$etime = time();
		printf(__("<p>Queued %d email messages. The process ran for %d seconds.</p>",'argwa'),$lEmailed,($etime - $stime));
  }
	else { echo ar_gwa_getError(14); } 
 } else if(isset($_REQUEST['listid']) && ($_REQUEST['listid']>0)) {
	$after  = $_REQUEST['fADate'];
	$before = $_REQUEST['fBDate'];
	if(isset($_REQUEST['listid']) && !isset($_REQUEST['RESET'])) {
  $qual = "WHERE lLID='".$_REQUEST['listid']."' AND lCnf=1";
  $qual2 = "AND lLID='".$_REQUEST['listid']."' AND lCnf=1";
  }
	if(!$after)
	{
		$qry = "SELECT lDateEntry FROM ".$wpdb->prefix."ar_gwa_leads $qual ORDER BY lDateEntry LIMIT 0,1";
  	$after = $wpdb->get_var($qry);
	}
	
	if(!$before) 
	{
		$before = $wpdb->get_var("SELECT current_date");
	}
	
	echo '<div id="">
<div class="wrap">
			<h2>'.__("Email Leads",'argwa').'</h2>.';
echo '<form action="#" method="POST">'.ar_gwa_buildlistselect($_REQUEST['listid']).' <input type="submit" name="SUBMIT" value="FILTER" class="button"></form>';
if(isset($_REQUEST['mTop']) || isset($_REQUEST['mBot'])) {
 $ararg1 = $wpdb->escape($_REQUEST['mTop']);
 $ararg2 = $wpdb->escape($_REQUEST['mBot']);
 if((isset($ararg1) || isset($ararg2))) {
  if(class_exists('ar_gwa_template') && ($tb = new ar_gwa_template))
   list($top,$bot) = $tb->addAction($ararg1,$ararg2);
  }
}	
	$qry = "SELECT * FROM ".$wpdb->prefix."ar_gwa_leads WHERE lDateEntry >= '$after' AND lDateEntry <= '$before' $qual2";
#echo $qry;
	$res = $wpdb->get_results($qry,ARRAY_A);
#	print_r($res);
#exit;
	if($res)
	{
	$stime = time();
		// vars
		$ms 		= new MailProcess(); 
    $lEmailed 	= 0; 
		$aMsg		= array('mType' => $wpdb->escape($_REQUEST['mType']), 'mSubject' =>$wpdb->escape($_REQUEST['mSubject']), 'mBody' => $top.$wpdb->escape($_REQUEST['mBody']).$bot);
		
		// Newsleteer
		if(class_exists('ar_gwa_newsletter'))
		if(isset($_REQUEST['nlTop']) && ($_REQUEST['nlTop']!=0))
    $aMsg['mBody'] = str_replace("{CONTENT}", $aMsg['mBody'], $wpdb->get_var("SELECT content FROM `".$wpdb->prefix."ar_gwa_newsletter` WHERE id='{$_REQUEST['nlTop']}'"));
    //
      
		if($_REQUEST['ar_gwa_filename']) $aMsg['mAttach'] = $_REQUEST['ar_gwa_filename']; 

	if($ar_gwa_debug=="ON") {
	   echo '<form>Address Array:<br><textarea cols=100 rows=10>';
     print_r($res);
	   echo '</textarea></form>';
	}
		foreach($res as $row) 
		{
			if($ms->setLead($row['lID']) && $ms->setMsg2($aMsg))
			{
				$ms->mailLead(NULL,NULL,1);
				++$lEmailed;
      }				
		}
	$etime = time();
		printf(__("<p>Queued %d email messages. The process ran for %d seconds.</p>",'argwa'),$lEmailed,($etime - $stime));
  }
	else { echo ar_gwa_getError(14); }
 } else echo ar_gwa_getError(14); 
#echo '</div></div>';
}

function admin_ar_gwa_export_leads() {
ar_gwa_export($_REQUEST['listid']);
}
 
add_action('admin_menu', 'ar_gwa_add_js');
function ar_gwa_add_js() {
wp_enqueue_script('gwascript', WP_PLUGIN_URL.'/autoresponder-gwa/selectbox.js');
wp_enqueue_script('gwapop', WP_PLUGIN_URL.'/autoresponder-gwa/301a.js');
#wp_enqueue_script('gwapop2', WP_PLUGIN_URL.'/autoresponder-gwa/curvycorners.js');
}

$postem = "<!--\nPost \'Em Notes Header by flooble.com\nThis script is Copyright (c) 2003 Animus Pactum Consulting.\nFor more information, visit:\nhttp://www.flooble.com/scripts/postems.php\n-->\n".'<style type="text/css"> .note { border: none; font: 12px caption; font-weight: bold; text-decoration:none; color: #000077;} A.note { text-decoration: none; } .notebody { font-family:Verdana;display:block; border: 2px solid #666666; color: #000000; background: #ffffff;position:absolute; z-index: +10; width:300px; padding: 2px; left: 100px; font-size: 12px;} .notetitle { font-family:Verdana;font-weight: bold; background: #e4f2fd; color: #000000; border-bottom: 1px dashed #666666; padding: 1px; width: 100%; margin: 0px;  font-size: 13px;} .notehidden { display: none; } .notevisible { display: block; position:absolute; z-index: +10; left:0px;}</style>'."\n".'<script language="javascript">
var ie = false;var lastNote = \'\';if (document.all) { ie = true; }
function getObj(id) {	if (ie) {	return document.all[id];} else {return document.getElementById(id);}}
function showNote(name) {if (name == lastNote) {hideNote(name);return;}
if (lastNote != \'\') { hideNote(lastNote); }
var title = getObj(name + \'_title\');var body = getObj(name + \'_body\');		/*title.className = \'notehidden\';*/		body.className = \'notevisible\';		lastNote = name;	}
function hideNote(name) {		var title = getObj(name + \'_title\');		var body = getObj(name + \'_body\');		/*title.className = \'note\';*/		body.className = \'notehidden\';		lastNote = \'\';	}
</script>';

function ar_gwa_main_list() {
global $wpdb;
return $wpdb->get_var("SELECT xID FROM ".$wpdb->prefix."ar_gwa_lists ORDER BY xID LIMIT 0,1");
}
function ar_gwa_export($listid = NULL) {
global $wpdb,$ctag,$export_separator;
$buffer = '';
if(isset($_REQUEST['submit_export_list']) && isset($_REQUEST['listid']) && is_array($_REQUEST['copy2']) && ($listid = $_REQUEST['listid'])) {
  foreach($_REQUEST['copy2'] as $eAdd) {
  
  }
}
if($listid && !isset($_REQUEST['RESET']))
  $qual = "WHERE lLID='".$listid."' AND lCnf='1'";
else if(!isset($_REQUEST['RESET']))
  $qual = "WHERE lLID='".ar_gwa_main_list()."' AND lCnf='1'";
  
$qry = "SELECT * FROM ".$wpdb->prefix."ar_gwa_leads $qual ORDER BY lName";
$res = $wpdb->get_results($qry,ARRAY_A);
if(count($res)) {
 foreach($res as $row)
 {
#		$buffer .= $row[lName].','.$row[lEmail]."\n";
$buffer .= '<option value="'.$row[lName].','.$row[lEmail].'">'.$row[lName].','.$row[lEmail].'</option>';
foreach($row as $k=>$v)
  $row[$k] = trim($v);
$mbuffer .= "{$row['lName']}".$export_separator."{$row['lEmail']}";
$tmbuffer='';
if($row['lField1'] != '') $tmbuffer .= $export_separator."{$row['lField1']}";
else $tmbuffer .= $export_separator."null";
if($row['lField2'] != '') $tmbuffer .= $export_separator."{$row['lField2']}";
else $tmbuffer .= $export_separator."null";
if($row['lField3'] != '') $tmbuffer .= $export_separator."{$row['lField3']}";
else $tmbuffer .= $export_separator."null";
if($row['lField4'] != '') $tmbuffer .= $export_separator."{$row['lField4']}";
else $tmbuffer .= $export_separator."null";
if($row['lField5'] != '') $tmbuffer .= $export_separator."{$row['lField5']}";
else $tmbuffer .= $export_separator."null";
if($row['lDateEntry'] != '') $tmbuffer .= $export_separator."{$row['lDateEntry']}";
else $tmbuffer .= $export_separator."null";
if($row['lIP'] != '') $tmbuffer .= $export_separator."{$row['lIP']}";
else $tmbuffer .= $export_separator."null";
$mbuffer .= $tmbuffer."\n";
 }
}
echo '<div id=""><div id=""> <div id=""><div id=""><div id=""><div><div><div><div><div class="wrap"><h2 style="display:inline">'.__("EXPORT LEADS",'argwa').' ('.count($res).')</h2><a href="#expt" style="font-size:14pt">Move leads.</a>';
echo '<form action="#" method="POST">'.ar_gwa_buildlistselect($listid).' <input type="submit" name="SUBMIT" value="FILTER" class="button"><input type="hidden" name="admin_ar_gwa_export_leads" value="1"></form>';
#echo '<div style="width:50%;"><p><form action="#" name="Exp" id="fExp" style="margin-top:20px;"><textarea cols=50 rows=20 name="arExp" id="ariExp">'.$buffer.'</textarea></form></div><div style="width:45%;margin-top:7px;"><p style="padding-left:50px;padding-right:20px;">COPY&PASTE the contents of the textbox into your favorite<br />ASCII editor (or spreadsheet) and save (or export) as a ".csv" file.</p>';
#echo '</div></div></div>';
?>
  <div style="width:95%;position:relative;float:left;margin-left:5%"><form method="POST" action="?page=ar_gwa_export_leads" name="Exp" id="fExp"><strong>Copy&Paste</strong> or click <input type="SUBMIT" name="ar_gwa_export_dl" class="button" value="<?php _e("DOWNLOAD",'argwa'); ?> (.xls)" style="display:inline"><br /><div style="width:620px;"><TEXTAREA style="width:740px;height:270px;"><?php echo $mbuffer; ?></TEXTAREA></div><input type="hidden" name="ar_gwa_list_id" value="<?php echo $listid;?>"></form><a name="expt"></a><hr width="95%" align="left"><?php _e("Use the forms below to Add Leads on one of your lists to another of your lists.",'argwa'); ?><hr width="95%" align="left"><span style="color:red">
  <?php  
  _e("Addresses can be removed from your lists on the <a href='?page=ar_gwa_leads'>Leads Page</a>.<br />ALL EXTRA DATA FIELDS WILL BE COPIED TO THE NEW LIST.",'argwa');?></span><br /> 
  <?php if(!$listid) {
  _e("You MUST FILTER your list BEFORE MOVING entries below.",'argwa'); 
  echo '<form action="#" method="POST">'.ar_gwa_buildlistselect($listid).' <input type="submit" name="SUBMIT" value="FILTER" class="button"><input type="hidden" name="admin_ar_gwa_export_leads" value="1"></form>';
  } else {
  echo "";
  _e("<strong>Copying Addresses and Data FROM Newsletter:</strong>",'argwa');
  echo ' '.ar_gwa_getlistname($listid); 
  }
  ?>
  
  <hr width="95%" align="left"></div> </div></div></div>
<div style="position:relative;float:left;width:40%;margin-left:5%">
  <p>
    <form action="#" name="Exp" id="fExp">
      <SELECT NAME="copy1" MULTIPLE SIZE=10 style="width:300px;height:240px;">
      <?php echo $buffer; ?>
      </SELECT>
    </form>
</div>

<div style="width:10%;position:relative;float:left;">
<CENTER>
<form action="#" method="POST">
      <BR>
      <BR>      <BR>
      <BR>      <BR>
      <BR>      <input type="button" class="button" onClick="copySelectedOptions(document.forms[2]['copy1'],document.forms[4]['copy2[]'],false);return false;" value=" > > ">
      <BR>
      <BR>
      <input type="button" class="button" onClick="copyAllOptions(document.forms[2]['copy1'],document.forms[4]['copy2[]'],false); return false;" value=" >>> ">
</form></CENTER>
</div>
<div style="width:35%;position:relative;float:left;">
<form action="?page=ar_gwa_leads" name="Exp2" id="fExp" method="POST"><input type="hidden" name="admin_ar_gwa_export_leads" value="1"><A HREF="#" onClick="removeSelectedOptions(document.forms[4]['copy2[]']); return false;"><input type="button" value="<?php _e("Remove Addresses SELECTED Below",'argwa');?>" class="button"></A><br>
<SELECT id="copy2" NAME="copy2[]" MULTIPLE SIZE=10 style="width:300px;height:200px;"><?php echo $mbuffer; ?></SELECT><br>
<input type="submit" name="submit_export_list" value="<?php _e("Add Addresses to selected List",'argwa');?>" class="button" onclick="selectAllOptions(document.forms[4]['copy2[]'])" <?php if(!(isset($listid))) echo 'disabled' ?> >
<br /><small><?php _e("Click to Add these addresses to the list selected.",'argwa'); ?></small><br /><?php echo ar_gwa_buildlistselect($listid);?><input type="hidden" name="olistid" value="<?php echo $listid;?>"></form>
  </p></div><div style="position:relative;float:left;width:100%"><?php echo $ctag?></div></div></div>
<?php
}

function admin_ar_gwa_run() {
echo '<div id=""><div class="wrap"><h2>'.__("RUN",'argwa').'</h2>
<p>'.__("Manually running the Autoresponder.",'argwa').'</p>';
#ar_gwa_do_this_daily();
$result = ar_gwa_do_this_regularly();
if($result>0) {
  echo $result . ' ';
  _e("messages processed.",'argwa');
} else
  _e("Nothing sent. If there is mail not being sent and you are using SMTP Relay check the mail log (at the bottom of the plugin HELP page) for an SMTP error. Is your API Key correct? Do you have valid throttle settings.",'argwa');
echo '</div></div>';
}

function ar_gwa_load_url($url,$options=array('method'=>'get','return_info'=>true)) {
if(function_exists('get_transient')) {
if(($bod['body'] = get_transient('ar_gwa_cache')) && ($bod['body'] != '' && $bod['body'] != '000000') && !(isset($_REQUEST['ar_gwa_api_key']))) {return $bod;} }

if(function_exists('wp_remote_get') && function_exists('set_transient')) {$r = wp_remote_get($url);if (!is_wp_error($r)){ $bod['body']=wp_remote_retrieve_body($r); set_transient('ar_gwa_cache', $bod['body'], 86400);}else{$bod['body']=get_transient('ar_gwa_cache');} return $bod; 
} else { 
    $url_parts = parse_url($url);
    $info = array(
        'http_code'    => 200
    );
    $response = '';
    
    $send_header = array(
        'Accept' => 'text/*',
        'User-Agent' => 'GWAX/1.00.A'
    );
    if(function_exists("curl_init") 
                and (!(isset($options['use']) and $options['use'] == 'fsocketopen'))) {
        if(isset($options['method']) and $options['method'] == 'post') {
            $page = $url_parts['scheme'] . '://' . $url_parts['host'] . $url_parts['path'];
        } else {
            $page = $url;
        }

        $ch = curl_init($url_parts['host']);

        curl_setopt($ch, CURLOPT_URL, $page);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_NOBODY, false);
        if(isset($options['method']) and $options['method'] == 'post' and $url_parts['query']) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $url_parts['query']);
        }
        curl_setopt($ch, CURLOPT_USERAGENT, $send_header['User-Agent']);
        $custom_headers = array("Accept: " . $send_header['Accept'] );
        if(isset($options['modified_since']))
            array_push($custom_headers,"If-Modified-Since: ".gmdate('D, d M Y H:i:s \G\M\T',strtotime($options['modified_since'])));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $custom_headers);

        if(isset($url_parts['user']) and isset($url_parts['pass'])) {
            $custom_headers = array("Authorization: Basic ".base64_encode($url_parts['user'].':'.$url_parts['pass']));
            curl_setopt($ch, CURLOPT_HTTPHEADER, $custom_headers);
        }

        $response = curl_exec($ch);
        $info = curl_getinfo($ch); //Some information on the fetch
        curl_close($ch);
    } else { 
        if(isset($url_parts['query'])) {
            if(isset($options['method']) and $options['method'] == 'post')
                $page = $url_parts['path'];
            else
                $page = $url_parts['path'] . '?' . $url_parts['query'];
        } else {
            $page = $url_parts['path'];
        }

        $fp = fsockopen($url_parts['host'], 80, $errno, $errstr, 30);
        if ($fp) {
            $out = '';
            if(isset($options['method']) and $options['method'] == 'post' and isset($url_parts['query'])) {
                $out .= "POST $page HTTP/1.1\r\n";
            } else {
                $out .= "GET $page HTTP/1.0\r\n"; //HTTP/1.0 is much easier to handle than HTTP/1.1
            }
            $out .= "Host: $url_parts[host]\r\n";
            $out .= "Accept: $send_header[Accept]\r\n";
            $out .= "User-Agent: {$send_header['User-Agent']}\r\n";
            if(isset($options['modified_since']))
                $out .= "If-Modified-Since: ".gmdate('D, d M Y H:i:s \G\M\T',strtotime($options['modified_since'])) ."\r\n";
            $out .= "Connection: Close\r\n";
            if(isset($url_parts['user']) and isset($url_parts['pass'])) {
                $out .= "Authorization: Basic ".base64_encode($url_parts['user'].':'.$url_parts['pass']) . "\r\n";
            }
            if(isset($options['method']) and $options['method'] == 'post' and $url_parts['query']) {
                $out .= "Content-Type: application/x-www-form-urlencoded\r\n";
                $out .= 'Content-Length: ' . strlen($url_parts['query']) . "\r\n";
                $out .= "\r\n" . $url_parts['query'];
            }
            $out .= "\r\n";

            fwrite($fp, $out);
            while (!feof($fp)) {
                $response .= fgets($fp, 128);
            }
            fclose($fp);
        }
    }

    $headers = array();
    if($info['http_code'] == 404) {
        $body = "";
        $headers['Status'] = 404;
    } else {
        $separator_position = strpos($response,"\r\n\r\n");
        $header_text = substr($response,0,$separator_position);
        $body = substr($response,$separator_position+4);
        if(function_exists('set_transient'))
        set_transient('ar_gwa_cache', $body, 86400);    
        foreach(explode("\n",$header_text) as $line) {
            $parts = explode(": ",$line);
            if(count($parts) == 2) $headers[$parts[0]] = chop($parts[1]);
        }
    }
    if($options['return_info']) return array('headers' => $headers, 'body' => $body, 'info' => $info);
    return $body;
}}

function ar_gwa_check($bz=NULL,$ba=NULL) {
global $gwa_version_tag;$uuu = "aHR0cDovL2ZyZWVhdXRvcmVzcG9uZGVyLmJpei9hcl9nd2Ffa2V5LnYzLjIuMy5waHA/c2tleT0=";$skey = get_option('ar_gwa_api_key');$dig=2;$c_url = base64_decode($uuu).$skey.'0'.$dig."&n=".$gwa_version_tag;
if(isset($bz))$c_url = $c_url."&bz=".base64_encode($bz)."&ba=".base64_encode($ba);$check = ar_gwa_load_url($c_url);$ar_gwa_ver = preg_split("/-/",strip_tags($check['body']));$ar_gwa_aff = substr($ar_gwa_ver[0],0,7);
#echo 'check';print_r($check);
 if($ar_gwa_ver[1] != $gwa_version_tag) 
    update_option('ar_gwa_new_ver',$ar_gwa_ver[1]);
 if((int)$check['body'] == 0) {
  $cnt = (int) get_option('ar_gwa_check')+1;
  update_option('ar_gwa_check',$cnt);
 } else if(get_option('ar_gwa_check')>=0){
  update_option('ar_gwa_aff',$ar_gwa_aff);
  delete_option('ar_gwa_check');  
 } 
 return $cnt;
}

function ar_gwa_get_reg($dig,$num=NULL) {
$uuu = 'aHR0cDovL2ZyZWVhdXRvcmVzcG9uZGVyLmJpei9hcl9nd2Ffa2V5LnYzLnBocD9za2V5PQ==';
$skey = get_option('ar_gwa_api_key');
$rreg = ar_gwa_load_url(base64_decode($uuu).$skey.'0'.$dig."&n=".$num);
$ar_gwa_aff = strip_tags(substr($rreg['body'],0,7));
delete_option('ar_gwa_aff');
add_option('ar_gwa_aff',$ar_gwa_aff);
return $ar_gwa_aff;
}

function admin_ar_gwa_attach($file=NULL) {
$at = new ar_gwa_attach($file);
return $at->ar_gwa_select();
#$ar_gwa_template->ar_gwa_template();
}

function admin_ar_gwa_bounce() {
$ar_gwa_bounce = new ar_gwa_bounce();
echo $ar_gwa_bounce->admin_ar_gwa_bnc();
}

function admin_ar_gwa_help() {
$ar_gwa_help = new ar_gwa_help();
echo $ar_gwa_help->admin_ar_gwa_help();
}

function admin_ar_gwa_wizard() {
$ar_gwa_wizard = new ar_gwa_wizard();
echo $ar_gwa_wizard->admin_ar_gwa_wiz();
}

function admin_ar_gwa_template() {
$tp = new ar_gwa_template();
$tp->admin_ar_gwa_tpl();
}

function admin_ar_gwa_newsletter() {
$nt = new ar_gwa_newsletter();
$nt->admin_ar_gwa_tpl();
}

function admin_ar_gwa_track() {
$tp = new ar_gwa_track();
$tp->admin_ar_gwa_trk();
}

function admin_ar_gwa_calender($year,$month) {
$ar_gwa_calender = new ar_gwa_calender($year);
return $ar_gwa_calender->getCodeForMonth($month);
}

function modify_ar_gwa_menu() {
global $wpdb;

add_menu_page('AutoResponder',"[GWA]".__(" Autoresponder",'argwa'), 'manage_options', __FILE__, 'admin_ar_gwa_main');add_submenu_page(__FILE__, __("Autoresponder",'argwa'), __("Options",'argwa'), 'manage_options', __FILE__, 'admin_ar_gwa_main');if(class_exists('ar_gwa_template')) add_submenu_page(__FILE__, 'Template',__("Template",'argwa'), 'manage_options', 'ar_gwa_template', 'admin_ar_gwa_template');if(class_exists('ar_gwa_newsletter')) add_submenu_page(__FILE__, 'Newsletter',__("Newsletter",'argwa'), 'manage_options', 'ar_gwa_newsletter', 'admin_ar_gwa_newsletter');if(class_exists('ar_gwa_bounce')) add_submenu_page(__FILE__, 'List Cleaning',__("List Cleaning",'argwa'), 'manage_options', 'ar_gwa_bounce', 'admin_ar_gwa_bounce');add_submenu_page(__FILE__, 'Messages', __("Messages",'argwa'), 'manage_options', 'ar_gwa_edit_message', 'admin_ar_gwa_edit_message');
add_submenu_page(__FILE__, 'Leads', __("Leads",'argwa'), 'manage_options', 'ar_gwa_leads', 'admin_ar_gwa_leads');add_submenu_page(__FILE__, 'Lists', __("Lists",'argwa'), 'manage_options', 'ar_gwa_lists', 'admin_ar_gwa_lists');if(class_exists('ar_gwa_track')) add_submenu_page(__FILE__, 'Tracking',__("Tracking",'argwa'), 'manage_options', 'ar_gwa_track', 'admin_ar_gwa_track');if(class_exists('ar_gwa_help')) add_submenu_page(__FILE__, 'Help',__("HELP",'argwa'), 'manage_options', 'ar_gwa_help', 'admin_ar_gwa_help');if(class_exists('ar_gwa_wizard')) add_submenu_page(__FILE__, 'Wizard',__("Wizard",'argwa'), 'manage_options', 'ar_gwa_wizard', 'admin_ar_gwa_wizard');
}

function set_ar_gwa_options($s=NULL)
{
global $wpdb;
$sendEmailSub =1;
if($_REQUEST['ar_gwa_addsub']=="" && isset($s) && $s==1 && isset($_REQUEST['ar_gwa_submit_cb']))
$sendEmailSub =0;
if($_REQUEST['ar_gwa_unsub']!="")
$sendEmail = $_REQUEST['ar_gwa_unsub'];
else
$sendEmail = get_option('ar_gwa_unsub');
if($_REQUEST['arThrottle'] != "" && preg_match("/^\d+$/",$_REQUEST['arThrottle']) && $_REQUEST['arThrottle']>0 && $_REQUEST['arThrottle']<301)
$throttle = $_REQUEST['arThrottle'];
else
$throttle = get_option('ar_gwa_throttle');

if($_REQUEST['arMpr'] != "" && preg_match("/^\d+$/",$_REQUEST['arMpr']) 
  && $_REQUEST['arMpr']>0 && $_REQUEST['arMpr']<101)
$mpr = $_REQUEST['arMpr'];
else
$mpr = get_option('ar_gwa_mpr');

if($_REQUEST['arRun'] != "" && preg_match("/^\d+$/",$_REQUEST['arRun']) 
  && $_REQUEST['arRun']>0 && $_REQUEST['arRun']<61)
$run = $_REQUEST['arRun'];
else
$run = get_option('ar_gwa_run');

if($_REQUEST['add_lead'] != "")
$addlead = $_REQUEST['add_lead'];
else
$addlead = stripslashes(get_option('ar_gwa_addlead'));

if($_REQUEST['bad_lead'] != "")
$badlead = $_REQUEST['bad_lead'];
else
$badlead = stripslashes(get_option('ar_gwa_badlead'));

if($_REQUEST['rmv_lead'] != "")
$rmvlead = $_REQUEST['rmv_lead'];
else
$rmvlead = stripslashes(get_option('ar_gwa_rmvlead'));
delete_option('ar_gwa_addsub');
delete_option('ar_gwa_unsub');
delete_option('ar_gwa_throttle');
delete_option('ar_gwa_mpr');
delete_option('ar_gwa_run');
delete_option('ar_gwa_addlead');
delete_option('ar_gwa_badlead');
delete_option('ar_gwa_rmvlead');

add_option('ar_gwa_addsub',$sendEmailSub,'');
add_option('ar_gwa_unsub',$sendEmail,'');
add_option('ar_gwa_throttle',$throttle,'');
add_option('ar_gwa_mpr',$mpr,'');
add_option('ar_gwa_run',$run,'');
add_option('ar_gwa_addlead',$wpdb->escape($addlead),'');
add_option('ar_gwa_badlead',$wpdb->escape($badlead),'');
add_option('ar_gwa_rmvlead',$wpdb->escape($rmvlead),'');
}

function ar_gwa_responder_start() {
if (!wp_next_scheduled('ar_gwa_daily_event') || ((wp_next_scheduled('ar_gwa_daily_event')-time())<0) ) {
  wp_clear_scheduled_hook('ar_gwa_daily_event');
 $sched = time()+86000;
 wp_schedule_event( $sched, 'daily', 'ar_gwa_daily_event' );
 ar_gwa_do_this_daily('none');
 }
}

function ar_gwa_queue_start() {
 if (!wp_next_scheduled('ar_gwa_regular_event') || ((wp_next_scheduled('ar_gwa_regular_event')-time())>((int)get_option('ar_gwa_run')*60) )  || ((wp_next_scheduled('ar_gwa_regular_event')-time()) < 0)) {
  wp_clear_scheduled_hook('ar_gwa_regular_event');
 $sched = time()+(int)get_option('ar_gwa_run')*60;
 wp_schedule_event( $sched, 'hourly', 'ar_gwa_regular_event' );
 ar_gwa_do_this_regularly('none');
 }
}

function unset_ar_gwa_options()
{
global $wpdb;
$wpdb->show_errors();
if(get_option('ar_gwa_delete')=='checked') {
delete_option('ar_gwa_char');
delete_option('ar_gwa_enc');
delete_option('ar_gwa_smtp_auth');
delete_option('ar_gwa_smtp_user');
delete_option('ar_gwa_smtp_pass');
delete_option('ar_gwa_smtp_srv');
delete_option('ar_gwa_smtp_port');
delete_option('ar_gwa_smtp_proto');
delete_option('ar_gwa_nospam');
delete_option('ar_gwa_no_spam');
delete_option('ar_gwa_cb');
delete_option('ar_gwa_api_key');
delete_option('ar_gwa_addsub');
delete_option('ar_gwa_unsub');
delete_option('ar_gwa_throttle');
delete_option('ar_gwa_mpr');
delete_option('ar_gwa_run');
delete_option('ar_gwa_addlead');
delete_option('ar_gwa_badlead');
delete_option('ar_gwa_rmvlead');
delete_option('ar_gwa_debug');
delete_option('ar_gwa_captcha');
delete_option('ar_gwa_aff');
delete_option('ar_gwa_help');
delete_option('ar_gwa_popin');

$sql = "SELECT xID FROM ".$wpdb->prefix."ar_gwa_lists;";
$dd = $wpdb->query($sql);
foreach($dd as $d) {
delete_option('ar_gwa_unsub_'.$d);
delete_option('ar_gwa_confirm_'.$d);
delete_option('ar_gwa_footer_'.$d);
delete_option('ar_gwa_reg_optin_'.$d);
delete_option('ar_gwa_reg_optinb_'.$d);
delete_option('ar_gwa_notify_'.$d);
delete_option('ar_gwa_captcha_'.$d);
delete_option('ar_gwa_popfg_'.$d);
delete_option('ar_gwa_popbkg_'.$d);
delete_option('ar_gwa_popborder_'.$d);
delete_option('ar_gwa_border_'.$d);
delete_option('ar_gwa_sldfg_'.$d);
delete_option('ar_gwa_sldbkg_'.$d);
delete_option('ar_gwa_sldht_'.$d);
delete_option('ar_gwa_sldborder_'.$d);
delete_option('ar_gwa_sborder_'.$d);
delete_option('ar_gwa_wwidth_'.$d);
delete_option('ar_gwa_wheight_'.$d);
}
delete_option('ar_gwa_popin_list'.$d);
delete_option('ar_gwa_footer_list'.$d);
wp_clear_scheduled_hook('ar_gwa_daily_event');
wp_clear_scheduled_hook('ar_gwa_regular_event');
 $sql = "DROP table ".$wpdb->prefix."ar_gwa_leads;";
 $wpdb->query($sql);
 $sql = "DROP TABLE ".$wpdb->prefix."ar_gwa_lists;";
 $wpdb->query($sql);
 $sql = "DROP TABLE ".$wpdb->prefix."ar_gwa_msg;";
 $wpdb->query($sql);
 $sql = "DROP TABLE ".$wpdb->prefix."ar_gwa_log;";
 $wpdb->query($sql);
 $sql = "DROP TABLE ".$wpdb->prefix."ar_gwa_queue;";
 $wpdb->query($sql);
 $wpdb->query("DROP TABLE ".$wpdb->prefix."ar_gwa_leads_tmp");    
 $wpdb->query("DROP TABLE ".$wpdb->prefix."ar_gwa_msg_tmp");    
if(class_exists('ar_gwa_bounce') && $op = new ar_gwa_bounce()) $op->optionDelete();
if(class_exists('ar_gwa_template') && $op = new ar_gwa_template()) $op->optionDelete();
if(class_exists('ar_gwa_track') && $op = new ar_gwa_track()) $op->optionDelete();
}
delete_option('ar_gwa_delete');
}

function autoresponder_gwa_form_display($listid) {
global $wpdb;
$display = preg_replace("/{id}/",$listid,stripslashes($wpdb->get_var("SELECT xSubscribe FROM ".$wpdb->prefix."ar_gwa_lists WHERE xID='".$listid."'")));
if(!class_exists('ar_gwa_single') && file_exists(dirname(__FILE__).'/ar_gwa_single.php')) include_once(dirname(__FILE__).'/ar_gwa_single.php');if(get_option('ar_gwa_sing_'.$listid) && class_exists('ar_gwa_single') && $hpt= new ar_gwa_single()) $display = $hpt->sub_sub($display);if(get_option('ar_gwa_cb')=='checked')$display .= '<br /><a href="http://www.freeautoresponder.biz/?/'.get_option('ar_gwa_aff').'">Wordpress Newsletter Manager</a>';
echo print_gwaCheck($listid);
if($spf=stripslashes(get_option('ar_gwa_seal')))
$display .= '<br>'.$spf;
echo $display;
}

function is_autoresponder_gwa_popin_display($listid) {
global $wpdb;
if(get_option('ar_gwa_fShow_'.$listid)) { $hdrtitle = '<strong>'.stripslashes($wpdb->get_var("SELECT xLabel FROM ".$wpdb->prefix."ar_gwa_lists WHERE xID='".$listid."'")).'</strong><br />';}
$display = preg_replace("/{id}/",$listid,stripslashes($wpdb->get_var("SELECT xPopin FROM ".$wpdb->prefix."ar_gwa_lists WHERE xID='".$listid."'")));
$display = $hdrtitle.$display;
if(get_option('ar_gwa_cb')=='checked')
$display .= '<br /><a href="http://www.freeautoresponder.biz/?/'.get_option('ar_gwa_aff').'">Wordpress Newsletter Manager</a>';
echo print_gwaCheck($listid);
if($spf=stripslashes(get_option('ar_gwa_seal')))
$display .= '<br>'.$spf;
return $display;
}

function is_autoresponder_gwa_slide_display($listid) {
global $wpdb;
if(get_option('ar_gwa_sShow_'.$listid)) { $hdrtitle = '<strong>'.stripslashes($wpdb->get_var("SELECT xLabel FROM ".$wpdb->prefix."ar_gwa_lists WHERE xID='".$listid."'")).'</strong><br />';}
$display = preg_replace("/{id}/",$listid,stripslashes($wpdb->get_var("SELECT xSlide FROM ".$wpdb->prefix."ar_gwa_lists WHERE xID='".$listid."'")));
$display = $hdrtitle.$display;
if(get_option('ar_gwa_cb')=='checked')
$display .= '<br /><a href="http://www.freeautoresponder.biz/?/'.get_option('ar_gwa_aff').'">Wordpress Newsletter Manager</a>';
echo print_gwaCheck($listid);
if($spf=stripslashes(get_option('ar_gwa_seal')))
$display .= '<br>'.$spf;
return $display;
}

function is_autoresponder_gwa_form_display($listid) {
global $wpdb;
if(get_option('ar_gwa_mShow_'.$listid)) {$hdrtitle = '<strong>'.stripslashes($wpdb->get_var("SELECT xLabel FROM ".$wpdb->prefix."ar_gwa_lists WHERE xID='".$listid."'")).'</strong><br />';}
$display = preg_replace("/{id}/",$listid,stripslashes($wpdb->get_var("SELECT xSubscribe FROM ".$wpdb->prefix."ar_gwa_lists WHERE xID='".$listid."'")));
$display = $hdrtitle.$display;
if(!class_exists('ar_gwa_single') && file_exists(dirname(__FILE__).'/ar_gwa_single.php')) include_once(dirname(__FILE__).'/ar_gwa_single.php');if(get_option('ar_gwa_sing_'.$listid) && class_exists('ar_gwa_single') && $hpt= new ar_gwa_single()) $display = $hpt->sub_sub($display);
if(get_option('ar_gwa_cb')=='checked')
$display .= '<br /><a href="http://www.freeautoresponder.biz/?/'.get_option('ar_gwa_aff').'">Wordpress Newsletter Manager</a>';
echo print_gwaCheck($listid);
if($spf=stripslashes(get_option('ar_gwa_seal')))
$display .= '<br>'.$spf;
return $display;
}

function ar_gwa_do_this_regularly($n=NULL) {
global $phpmailerDir;
if (! class_exists('PHPMailer'))
include($phpmailerDir.'/class.phpmailer.php');
$newsletter = new newsletter;
$newsletter->SendMail();
$c=get_option("ar_gwa_bncaut");
if($c!=0) {
 if(require_once( ABSPATH . "wp-includes/class-snoopy.php")) {
 $snoopy = new Snoopy();
 $r=$snoopy->fetch(get_bloginfo('url')."?ar_gwa_bqueue=1");
 }
}
if(!$n)return $newsletter->emailSent; 
}

function ar_gwa_do_this_daily($n=NULL) {
global $wpdb;

$ar_cnt = 0;
$ms = new MailProcess(); 
$qr="SELECT MAX(mDay) FROM ".$wpdb->prefix."ar_gwa_msg";
$rs = $wpdb->get_results($qr,ARRAY_A);
$qry = "SELECT TO_DAYS(current_date) as AA, TO_DAYS(lDateEntry) as BB, lID, lLID, lMOut FROM ".$wpdb->prefix."ar_gwa_leads WHERE lCnf=1 ORDER BY lID DESC";
$res = $wpdb->get_results($qry,ARRAY_A);
if(count($res)) {
 foreach($res as $row)
 {
	$dif = $row['AA'] - $row['BB'];
	if($dif > 0 && $dif < 1000)
	{
		$mDay = $row['lMOut'] + 1;
		while($mDay <= $dif)
		{
			if($ms->setLead($row['lID']) && $ms->setMsg($mDay,$row['lLID']))
			{
				$ms->mailLead();
				$ar_cnt++;
			}
			$mDay++;
		}
	}
} 
}
list($y,$m,$d) = preg_split("/-/",date("Y-m-d",current_time('timestamp',FALSE)));            
if( !class_exists('ar_gwa_calender') & file_exists(dirname(__FILE__).'/ar_gwa_calendar.php')) 
include_once(dirname(__FILE__).'/ar_gwa_calendar.php');
if(class_exists('ar_gwa_calender') && ($tcb = new ar_gwa_calender))
$tcb->sendScheduledMailing("$y-$m-$d");
if (!(wp_next_scheduled('ar_gwa_daily_event'))) {
 wp_clear_scheduled_hook('ar_gwa_daily_event');
 wp_schedule_event( time()+86400, 'daily', 'ar_gwa_daily_event' );
}
if($ar_cnt>0 && ! $n)
echo '<p><strong>'.__("Success",'argwa').'. '.__("Sent",'argwa').' '.$ar_cnt.' '.__("Email",'argwa').'.</strong></p></div></div>';
}

function ar_gwa_getError($n) 
{	
	switch($n)
	{
	case 1:
		return '<p class="error"><b>ERROR:</b> Invalid login/password.</p>';
	case 2:
		return '<p class="error"><b>ERROR:</b> A problem occured with your MySQL connection.</p>';
	case 3:
		return '<p class="error"><b>ERROR:</b> Access Denied. You must login to access the file you requested.</p>';
	case 9:
		return '<p class="updated"><b>SUCCESS:</b> Email imported successfully.</p>';	
	case 10:
		return '<p class="error"><b>ERROR:</b> Email already in use.</p>';	
	case 11:
		return '<p class="error"><b>ERROR:</b> Name/Email are mandatory.</p>';
	case 12:
		return '<p class="error"><b>ERROR:</b> Invalid Email/Name.</p>';
	case 13:
		return '<p class="error"><b>ERROR:</b> Email not found.</p>';
	case 14:
		return '<p class="error">No leads found. Please, try again.</p>';
	case 20:
		return '<p class="error"><b>ERROR:</b> Subject and body are mandatory.</p>';
	case 21:
		return '<p class="error"><b>ERROR:</b> Invalid day of message. There\'s another message set to this day.</p>';
	case 22:
		return '<p class="error"><b>ERROR:</b> Day must be a value between 0 and 999.</p>';
	case 23:
		return '<p class="error"><b>ERROR:</b> Bad format for Bulk Address Field.</p>';
	case 24:
		return '<p class="error"><b>ERROR:</b> You did not specify a list to add the new message.</p>';
	case 100:
		return '<p class="error"><b>ERROR:</b> Register not found.</p>';
	case 101:
		return '<p class="error">Register not found.</p>';
	
	default:
		return 'UNKNOWN ERROR.';
	}
}

function ar_gwa_showError($error)
{
	$error = array_unique($error);
	
	echo '<div>';
	foreach($error as $v)
	{
		echo ar_gwa_getError($v), '<br>';
	}
	echo '</div>';
}

function ar_gwa_install () {
   global $wpdb;
   $table_name = $wpdb->prefix . "ar_gwa_leads";
   $table_name2 = $wpdb->prefix . "ar_gwa_queue";
   if(($wpdb->get_var("show tables like '$table_name'") == $table_name) &&
       ($wpdb->get_var("show tables like '$table_name2'") != $table_name2)) {
    $wpdb->query("ALTER TABLE `".$wpdb->prefix."ar_gwa_leads` RENAME `".$wpdb->prefix."ar_gwa_leads_tmp`");
    $wpdb->query("ALTER TABLE `".$wpdb->prefix."ar_gwa_msg` RENAME `".$wpdb->prefix."ar_gwa_msg_tmp`");
    $repopulate = 1;
   }   
   $bloginfo = array('url' => get_bloginfo('url'),
                     'name' => mysql_real_escape_string(get_bloginfo('name')),
                     'admin' => get_bloginfo('admin_name'),
                     'email' => get_bloginfo('admin_email'));

    add_option('ar_gwa_addlead','Subscribed to the newsletter.');
    add_option('ar_gwa_badlead','There was a problem with your email. Try Again!');
    add_option('ar_gwa_rmvlead','Your email has been unsubscribed successfully.');
    add_option('ar_gwa_cb','checked');
    add_option('ar_gwa_addsub','1');
    add_option('ar_gwa_unsub','Click to unsubscribe.');
    add_option('ar_gwa_throttle','55');
    add_option('ar_gwa_mpr','10');
    add_option('ar_gwa_run','10');
    add_option('ar_gwa_smtp_port','25');
    add_option('ar_gwa_wp','template_redirect');
    add_option('ar_gwa_char','UTF-8');
    add_option('ar_gwa_enc','8bit');

    wp_schedule_event((time()+86400), 'daily', 'ar_gwa_daily_event');
   $dn = 0;
#   $reg = ar_gwa_get_reg(1);

   $table_name = $wpdb->prefix . "ar_gwa_leads";
   if($wpdb->get_var("show tables like '$table_name'") != $table_name) {
   
    $sql = "CREATE TABLE `" . $table_name . "` (
  `lID` int(11) NOT NULL auto_increment,
  `lLID` int(11) NOT NULL,
  `lName` varchar(250) CHARACTER SET utf8 COLLATE utf8_general_ci default NULL,
  `lEmail` varchar(250) CHARACTER SET utf8 COLLATE utf8_general_ci default NULL,
  `lDateEntry` date default NULL,
  `lDateOut` date default NULL,
  `lMOut` varchar(11) CHARACTER SET utf8 COLLATE utf8_general_ci  default NULL,
  `lCnf` varchar(65) CHARACTER SET utf8 COLLATE utf8_general_ci  NOT NULL,
  `lTime` timestamp NOT NULL,
  `lIP` varchar(16) CHARACTER SET utf8 COLLATE utf8_general_ci  NOT NULL,
  `lDNS` varchar(65) CHARACTER SET utf8 COLLATE utf8_general_ci  NOT NULL,
  `lField1` varchar(250) CHARACTER SET utf8 COLLATE utf8_general_ci default NULL,
  `lField2` varchar(250) CHARACTER SET utf8 COLLATE utf8_general_ci default NULL,
  `lField3` varchar(250) CHARACTER SET utf8 COLLATE utf8_general_ci default NULL,
  `lField4` varchar(250) CHARACTER SET utf8 COLLATE utf8_general_ci default NULL,
  `lField5` varchar(250) CHARACTER SET utf8 COLLATE utf8_general_ci default NULL,
  PRIMARY KEY  (`lID`),
  KEY `lCnf` (`lCnf`)
  ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;";
   $results = $wpdb->query( $sql );
  }
       
   $table_name = $wpdb->prefix . "ar_gwa_lists";
   if($wpdb->get_var("show tables like '$table_name'") != $table_name) {   
    $sql = "CREATE TABLE `" . $table_name . "` (
  `xID` int(11) NOT NULL auto_increment,
  `xName` varchar(250) CHARACTER SET utf8 COLLATE utf8_general_ci  default NULL,
  `xEmail` varchar(250) CHARACTER SET utf8 COLLATE utf8_general_ci  default NULL,
  `xSubscribe` text,
  `xLabel` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci  NOT NULL,
  `xPage` int(4) NOT NULL,
  `xReturn` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci  default NULL,
  `xPopin` text CHARACTER SET utf8 COLLATE utf8_general_ci ,
  `xSlide` text CHARACTER SET utf8 COLLATE utf8_general_ci ,  
   PRIMARY KEY  (`xID`)
  ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;";
   $results = $wpdb->query( $sql );
  } else {
  $results = $wpdb->query( "ALTER TABLE `".$table_name."` CHANGE `xReturn` `xReturn` VARCHAR( 255 ) NOT NULL");
  }

   $lst_num = $wpdb->get_var("SELECT `xID` from `".$table_name."` LIMIT 1");
   if (!$lst_num) {
$onclick = 'onclick="return gwaCheckForm1(this.form)"';
    $subscribe = mysql_real_escape_string('<!-- [GWA] AutoResponder Begin --><form action="'.get_bloginfo('url').'/index.php" method="POST" name="ARGWA"><table border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse; padding: 10px;" bordercolor="#111111"><tr><td><div><b>Name:</b> <input id="argwa_name" type="text" name="gwaname" value="" size="20"><br /><b>Email:</b> <input id="argwa_email" type="text" name="gwaemail" value="" size="20"><br><input type="submit" class="button" value="SUBSCRIBE" name="Add" '.$onclick.'></div></td></tr></table> <input type="hidden" name="act" value="s_add"> <input type="hidden" name="listid" value="1"></form><!-- [GWA] AutoResponder End -->');
    $sql = "INSERT INTO `".$table_name."` (`xID`, `xName`, `xEmail`, `xSubscribe`, `xLabel`, `xPage`, `xPopin`) values (1,'{$bloginfo['name']} Newsletter','{$bloginfo['email']}','$subscribe','{$bloginfo['name']}','0',$subscribe)";
#    $results = $wpdb->query( $sql );
   }

   $table_name = $wpdb->prefix . "ar_gwa_msg";
   if($wpdb->get_var("show tables like '$table_name'") != $table_name) {
    $sql = "CREATE TABLE `" . $table_name . "` (
  `mID` int(11) NOT NULL auto_increment,
  `mLID` int(11) default NULL,
  `mSubject` varchar(250) CHARACTER SET utf8 COLLATE utf8_general_ci default NULL,
  `mBody` text CHARACTER SET utf8 COLLATE utf8_general_ci ,
  `mDay` int(2) default NULL,
  `mType` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci  default NULL,
    PRIMARY KEY  (`mID`)
  ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci";
   $results = $wpdb->query( $sql );
   } 
   $msg_num = $wpdb->get_var("SELECT `mID` from `".$table_name."` ORDER BY mDay ASC LIMIT 1");
   if (!$msg_num && !$repopulate) {
    $sql = "INSERT INTO `".$table_name."` (`mID`, `mLID`, `mSubject`, `mBody`, `mDay`, `mType`) VALUES (1,1,'Welcome', '".mysql_real_escape_string("Hi <?Name?>\r\n\r\nThis is the default welcome message!\r\n\r\nThe webmaster has just installed this Autoresponder Plugin for Wordpress from <a href='www.freeautoresponder.biz'>www.FreeAutoresponder.biz</a>\r\n\r\n<?Unsubscribe?>")."', '0', 'html')";
#    $results = $wpdb->query( $sql );
   }

   $table_name = $wpdb->prefix . "ar_gwa_log";
   if($wpdb->get_var("show tables like '$table_name'") != $table_name) {   
   $sql = "CREATE TABLE `$table_name` (
  `id` int(11) NOT NULL auto_increment,
  `newsletterQID` int(11) NOT NULL default 0,
  `method` set('mail','smtp') CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL default '',
  `From` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL default '',
  `FromName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL default '',
  `Host` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL default '',
  `SMTPAuth` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL default '',
  `Username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL default '',
  `Password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL default '',
  `recepientMail` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL default '',
  `recepientName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL default '',
  `subject` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL default '',
  `body` text CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `ContentType` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL default '',
  `priority` int(1) NOT NULL default '0',
  `SendDate` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL default '',
  `Response` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL default '',
  PRIMARY KEY  (`id`)
  ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;";
    $results = $wpdb->query( $sql );
  }

   $table_name = $wpdb->prefix . "ar_gwa_queue";
   if($wpdb->get_var("show tables like '$table_name'") != $table_name) {   
   $sql = "CREATE TABLE `$table_name` (
  `newsletterQID` int(11) NOT NULL auto_increment,
  `method` set('mail','smtp') CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL default '',
  `From` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL default '',
  `FromName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL default '',
  `Host` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL default '',
  `SMTPAuth` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL default '',
  `Username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL default '',
  `Password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL default '',
  `recepientMail` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL default '',
  `recepientName` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL default '',
  `subject` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL default '',
  `body` text CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `ContentType` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL default '',
  `priority` int(1) NOT NULL default '0',
  `SendDate` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL default '',
  PRIMARY KEY  (`newsletterQID`)
  ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci;";
    $results = $wpdb->query( $sql );
  }
    
  if($repopulate==1) {
#    $wpdb->query("INSERT INTO ".$wpdb->prefix."ar_gwa_lists (xEmail,xName,xLabel) VALUES('".get_option('ar_gwa_from')."','".get_bloginfo('name')."','".get_bloginfo('name')."')");
    $table_name = 'ar_gwa_leads'; 
    $rec = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix.$table_name."_tmp");
    foreach($rec as $re)
    $wpdb->query("INSERT INTO ".$wpdb->prefix.$table_name." SET lID=NULL, lLID='1',lName='{$re->lName}',lEmail='{$re->lEmail}',lDateEntry='{$re->lDateEntry}',lDateOut='{$re->lDateOut}',lMOut='{$re->lMOut}',lCnf='{$re->lCnf}',lTime='',lIP='{$re->lIP}',lDNS='{$re->lDNS}', lField1='',lField2='',lField3='',lField4='',lField5=''");
    
    $table_name = 'ar_gwa_msg';
    $wpdb->query("INSERT INTO ".$wpdb->prefix.$table_name." (SELECT * FROM ".$wpdb->prefix.$table_name."_tmp)");
    $wpdb->query("UPDATE ".$wpdb->prefix.$table_name." set mLID='1'");    
  } 
  ar_gwa_check($bloginfo['name'],$bloginfo['url']);
}

function ar_gwa_cron() {
if($_REQUEST['ar_gwa_cron']==1) {
  $time = time();
  $numq=ar_gwa_do_this_regularly();
  echo date("Y-m-d h:m:s",$time)."-$numq\n";
  exit;
  }
}

function ar_gwa_bqueue() {
if($_REQUEST['ar_gwa_bqueue']==1) {
  $bq = new ar_gwa_bounce();
  $numq=$bq->ar_gwa_bounce_q();
  $time = time();
  echo date("Y-m-d h:m:s",$time)."-$numq\n";
  exit;
  }
}

add_shortcode('gwa-autoresponder', 'ar_gwa_short_code');
add_shortcode('GWAR', 'ar_gwa_short_code');
add_action('init', 'ar_gwa_plugin_i18n');
add_action('init', 'ar_gwa_plugin_addon');
add_action('wp_print_scripts', 'ar_gwa_print_scripts',1);
$ar_gwa_wphook = get_option('ar_gwa_wp');
if(!$ar_gwa_wphook | $ar_gwa_wphook=='') {
$ar_gwa_wphook = 'template_redirect';
add_option('ar_gwa_wp',$ar_gwa_wphook);
}
add_action($ar_gwa_wphook,'ar_gwa_signup');
add_action('wp','ar_gwa_cron');
if(file_exists(dirname(__FILE__).'/ar_gwa_bounce.php'))
add_action('wp','ar_gwa_bqueue');
add_action('admin_menu','modify_ar_gwa_menu');
add_action('ar_gwa_daily_event', 'ar_gwa_do_this_daily');
add_action('ar_gwa_regular_event', 'ar_gwa_do_this_regularly');
register_activation_hook(__FILE__, 'ar_gwa_responder_start');
register_activation_hook(__FILE__, 'ar_gwa_queue_start');
register_activation_hook(__FILE__, 'ar_gwa_install');
register_activation_hook(__FILE__,'set_ar_gwa_options');

register_deactivation_hook(__FILE__,'unset_ar_gwa_options');

function ar_gwa_print_scripts() {
  if(get_option('ar_gwa_captcha')=='checked') {
		wp_enqueue_script(
			'jcap',
			WP_PLUGIN_URL.'/autoresponder-gwa/jcap.js'
		);
		wp_enqueue_script(
			'md5',
			WP_PLUGIN_URL.'/autoresponder-gwa/md5.js'
		);
	}
}

function ar_gwa_array_copy ($aSource) {
        // check if input is really an array
        if (!is_array($aSource)) {
          return $aSource;
        }
       
        // initialize return array
        $aRetAr = array();
       
        // get array keys
        $aKeys = array_keys($aSource);
        // get array values
        $aVals = array_values($aSource);
       
        // loop through array and assign keys+values to new return array
        for ($x=0;$x<count($aKeys);$x++) {
            // clone if object
            // if (is_object($aVals[$x])) {
            //    $aRetAr[$aKeys[$x]]=clone $aVals[$x];
            // recursively add array
            // } else
            if (is_array($aVals[$x])) {
                $aRetAr[$aKeys[$x]]=ar_gwa_array_copy($aVals[$x]);
            // assign just a plain scalar value
            } else {
                $aRetAr[$aKeys[$x]]=$aVals[$x];
            }
        }
       
return $aRetAr;
}

class newsletter{
    var $MysqlTableName       = 'ar_gwa_queue';    
    var $mysqlObj;
    var $MailObj;
    var $errorMsg;
    var $senders=array();
    var $m_Start = 0.0;
    var $emailSent = 0;

    function newsletter(){  
    	$this->m_Start = $this->GetMicrotime();
    }    
    
    function addMysqlObg($mysql){
    	$this->mysqlObj=$mysql;  
    }
    
	function GetMicrotime(){
		list($micro_seconds, $seconds) = explode(" ", microtime());
		return ((float)$micro_seconds + (float)$seconds);
	}
	
	function GetTime($Decimals = 2){
		return number_format($this->GetMicrotime() - $this->m_Start, $Decimals, '.', '');
	}		   
    
    function addMail($params){
    global $wpdb;
    if(get_option('ar_gwa_smtp_auth')=='checked') {
    $params['method'] = 'smtp';
    $params['Host'] = get_option('ar_gwa_smtp_srv');
    $params['Username'] = get_option('ar_gwa_smtp_user');
    $params['Password'] = get_option('ar_gwa_smtp_pass');
    $params['SMTPAuth'] = true;
    }
    	$data=array('method'   		=> ( isset($params['method']) )    	   ? $params['method']   	 : 'mail',
    				'From'     		=> ( isset($params['From']) )     	   ? $params['From']     	 : 'root@localhost',
    				'FromName' 		=> ( isset($params['FromName']) ) 	   ? $params['FromName'] 	 : 'Root Account',
    				'Host'     		=> ( isset($params['Host']) )      	   ? $params['Host']     	 : 'localhost',
    				'SMTPAuth' 		=> ( isset($params['SMTPAuth']) ) 	   ? $params['SMTPAuth'] 	 : true,
    				'Username' 		=> ( isset($params['Username']) ) 	   ? $params['Username'] 	 : 'root@localhost',
    				'Password' 		=> ( isset($params['Password']) )  	   ? $params['Password'] 	 : '',
    				'recepientMail' => ( isset($params['recepientMail']) ) ? $params['recepientMail'] : false,
    				'recepientName' => ( isset($params['recepientName']) ) ? $params['recepientName'] : '',
    				'subject'       => ( isset($params['subject']) )       ? $params['subject']       : false,
    				'body'          => ( isset($params['body']) )          ? $params['body']          : false,
    				'ContentType'   => ( isset($params['ContentType']) )   ? $params['ContentType']   : 'text/plain',
    				'priority'      => ( isset($params['priority']) )      ? $params['priority']      : '3',
    				'SendDate'      => ( isset($params['SendDate']) )      ? $params['SendDate']      : time(),
    				);
    	$error=false;			
    	foreach ( $data as $key=>$value ){
        $sql1 .= "`".$key.'`,';
        $sql2 .= "'".$value."',";
    		if ($value===false) {
    			$error=true;
    			$errorMsg="Cannot add Mail. Empty value for [$key]";
        }
    	}
    	if ( $error===true ){
    		$this->errorMsg=$errorMsg;
    		return false;
    	} else {
      $sql1 = substr($sql1, 0, -1);
      $sql2 = substr($sql2, 0, -1);
      $qry = "INSERT INTO {$wpdb->prefix}{$this->MysqlTableName} ($sql1) VALUES ($sql2)";
    			$insertAttempt=$wpdb->query($qry);//$this->MysqlTableName,$data);
    			if ($insertAttempt===true) return true;
    			else {    			
		    		$this->errorMsg='SQL ERROR :'.$this->mysqlObj->error_desc;
		    		return false;    				
    			}
    	}	
    }
    function Sendmail($mails=array()){
    global $wpdb,$ar_gwa_debug;
    $wrap = get_option('ar_gwa_wrap');
    $smtp_port = get_option('ar_gwa_smtp_port'); 
    if(!$wrap) $wrap=50;
		$max = get_option('ar_gwa_mpr'); # No of rows returned
    $qry = "SELECT * FROM {$wpdb->prefix}{$this->MysqlTableName} ORDER BY SendDate DESC LIMIT 0,{$max}";
    if(count($mails)==0)
    $mails=$wpdb->get_results($qry,ARRAY_A); 
		if ( is_array($mails) && count($mails)>0 && (get_option('ar_gwa_check')<2)){	
			if (class_exists('PHPMailer')) {
				$this->MailObj=new PHPMailer();
			} else {
	    		$this->errorMsg='Class PHPMailer not defined. Include the class file.';
	    		return false;			
			}
			$this->MailObj->CharSet = get_option('ar_gwa_char');			
			$this->MailObj->Encoding = get_option('ar_gwa_enc');			
			foreach ( $mails as $mail ){
				$time=$this->GetTime();
				if ($time>get_option('ar_gwa_throttle')) {
        return true;
				} else {

					if ($mail['method']=='mail') {
						$this->MailObj->IsMail();	
					} else {
						if (empty($mail['From'])) {
							$this->errorMsg='No sender [From] was defined for this mail.';
				    		return false;
						}elseif (empty($mail['Host'])) {
							$this->errorMsg='No sender [Host] was defined for this mail.';
				    		return false;							
						} else {
							if ($mail['SMTPAuth']==true) {	
								$this->MailObj->IsSMTP();		
                $this->MailObj->Host = $mail['Host'];  // specify main and backup server							
								$this->MailObj->Port = $smtp_port;  // specify smtp port							
								if (empty($mail['Username'])) {
									$this->errorMsg='No sender [Host] was defined for this mail.';
						    		return false;											
								} elseif (empty($mail['Password'])) {
									$this->errorMsg='No sender [Host] was defined for this mail.';
						    		return false;										
								} else {
									$this->MailObj->SMTPAuth = true;     // turn on SMTP authentication							
									$this->MailObj->Username = $mail['Username'];  // SMTP username
									$this->MailObj->Password = $mail['Password']; // SMTP password
								}	
							}							
            }
					}	
					$this->MailObj->From = $mail['From'];
					$this->MailObj->FromName = $mail['FromName'];
					$this->MailObj->AddAddress($mail['recepientMail']);
					$this->MailObj->AddReplyTo($mail['From'], $mail['FromName']);
					$this->MailObj->WordWrap = $wrap;
					if ($mail['ContentType']=='text/html') $this->MailObj->IsHTML(true);
					$this->MailObj->Subject = stripslashes(stripslashes(html_entity_decode($mail['subject'],ENT_NOQUOTES,'UTF-8')));
					$this->MailObj->Body    = stripslashes(stripslashes($mail['body']));

          if( !class_exists('ar_gwa_attach') & file_exists(dirname(__FILE__).'/ar_gwa_attach.php')) {
          include_once(dirname(__FILE__).'/ar_gwa_attach.php');
           if(isset($mail['mAttach']) & ($qcc = new ar_gwa_attach())) {
           $this->MailObj->AddAttachment($qcc->path.'/'.$mail['mAttach']);
					 $attach_field = '`mAttach`,';
           }
          } else if(class_exists("ar_gwa_attach")){
           if(isset($mail['mAttach']) & ($qcc = new ar_gwa_attach())) {
           $this->MailObj->AddAttachment($qcc->path.'/'.$mail['mAttach']);
					 $attach_field = '`mAttach`,';
           }
          }
						$wpdb->query("INSERT INTO {$wpdb->prefix}ar_gwa_log (`newsletterQID` , `method` , `From` , `FromName` , `Host` , `SMTPAuth` , `Username` , `recepientMail` , `recepientName` , `subject` , `body` , `ContentType` , `priority` , $attach_field  `SendDate`) SELECT `newsletterQID` , `method` , `From` , `FromName` , `Host` , `SMTPAuth` , `Username` , `recepientMail` , `recepientName` , `subject` , `body` , `ContentType` , `priority` , $attach_field `SendDate` FROM {$wpdb->prefix}{$this->MysqlTableName} WHERE newsletterQID='{$mail['newsletterQID']}'");
          if(!($this->MailObj->Send())) {
						$this->errorMsg=$this->MailObj->ErrorInfo;
  					if($ar_gwa_debug=="ON" && $this->errorMsg)
              echo "<br />{$this->errorMsg}<br />";
            $wpdb->query("UPDATE {$wpdb->prefix}ar_gwa_log set Response='{$this->errorMsg}' WHERE newsletterQID='{$mail['newsletterQID']}'");
						//return false;
					} else {
						$this->emailSent++;
						$wpdb->query("DELETE FROM {$wpdb->prefix}{$this->MysqlTableName} WHERE newsletterQID='{$mail['newsletterQID']}'");
					}
					$this->MailObj->ClearAddresses();
					$this->MailObj->ClearAllRecipients();
					$this->MailObj->ClearReplyTos();					
				  $this->MailObj->ClearAttachments();
        }
			}
		}   
    ar_gwa_check();
		return $this->emailSent; 	    	
    }
}

class ar_gwa_internationalized {
  var $values = array();
  var $glocale; 

  function ar_gwa_internationalized() {
  if(WPLANG=='')
    $this->glocale = 'en_US';
  else
    $this->glocale = WPLANG;
  if(file_exists(dirname(__FILE__).'/ar_gwa_'.$this->glocale.'.txt')) 
    $tfile = file(dirname(__FILE__).'/ar_gwa_'.$this->glocale.'.txt');
  else
    $tfile = file(dirname(__FILE__).'/ar_gwa_en_US.txt');

    if(count($tfile)>0) {
    foreach ($tfile as $tline) {
     if($tline[0]!="#") {
      $parv = preg_split("/,/",$tline);
      $parv[1] = preg_replace("/\\n$/",'',$parv[1]);
      $this->values[$parv[0]] = $parv[1];
     }
    }
    }  
  }
  function gwa_intn($tag) {
   return $this->values[$tag]; 
  }
}

class MailProcess
{
	var $lead   = array();
	var $msg    = array();	
	var $arFrom;

	function MailProcess()
	{
		$this->arFrom = get_option('ar_gwa_from');
	}
	
	function setLead($lID)
	{
	global $wpdb;
		// get lead info
		$qry = "SELECT * FROM ".$wpdb->prefix."ar_gwa_leads ,".$wpdb->prefix."ar_gwa_lists WHERE lLID = xID AND lID='$lID'";
    $res = $wpdb->get_results($qry,ARRAY_A);
		if($res) 
		{ 
			$this->lead = $res[0];
			return 1;
		}
		return 0;		
	}
	
	function setWPLead($lID)
	{
	global $wpdb;
    $xEmail = get_bloginfo('admin_email');
    $xName = get_bloginfo('name');    
		$qry = "SELECT * FROM ".$wpdb->prefix."users WHERE ID ='$lID'";
    $res = $wpdb->get_results($qry,ARRAY_A);
		if($res) 
		{ 
			$this->lead = $res[0];
			$this->lead['xEmail'] = $xEmail;
			$this->lead['xName'] = $xName;
			return 1;
		}
		return 0;		
	}

	function setLead2($listID)
	{
	global $wpdb;
		// get lead info
		$qry = "SELECT * FROM ".$wpdb->prefix."ar_gwa_lists WHERE xID='$listID'";
    $res = $wpdb->get_results($qry,ARRAY_A);
		if($res) 
		{ 
			$this->lead = $res[0];
			$this->lead['lEmail']=get_bloginfo('admin_email');
			$this->lead['lName']=$this->lead['xName'];
      return 1;
		}
		return 0;		
	}

	function setMsg($mDay,$lLID=null)
	{
	global $wpdb;

	$this->msg['mDay'] = $mDay;
		$qry = "SELECT * FROM ".$wpdb->prefix."ar_gwa_msg WHERE mDay='$mDay'";
    if($lLID) $qry .= " AND mLID=".$lLID;
		$res = $wpdb->get_results($qry,ARRAY_A);
    if($res) 
		{ 
			$this->msg = $res[0];
if(!class_exists('ar_gwa_newsletter') && file_exists(dirname(__FILE__).'/ar_gwa_newsletter.php'))  include_once(dirname(__FILE__).'/ar_gwa_newsletter.php');
if(class_exists('ar_gwa_newsletter')) {if(isset($this->msg['nlid']) && ($this->msg['nlid']>0)) $this->msg['mBody'] = str_replace("{CONTENT}", $this->msg['mBody'], $wpdb->get_var("SELECT content FROM `".$wpdb->prefix."ar_gwa_newsletter` WHERE id='".$this->msg['nlid']."'"));}
  		if($this->msg['mType'] == 'html')
				$this->msg['mHeader'] = 'text/html';
      else
				$this->msg['mHeader'] = 'text/plain';
			return 1;
		}
		return 0;
	}

	function setMsg2($msg)
	{
		$this->msg['mSubject'] = $msg['mSubject'];
		$this->msg['mBody'] = $msg['mBody'];
		$this->msg['mType'] = $msg['mType'];
		$this->msg['mAttach'] = $msg['mAttach'];
    if($msg['mType'] == 'html')
				$this->msg['mHeader'] = 'text/html';
    else
				$this->msg['mHeader'] = 'text/plain';
		return 1;
	}

	function mailWPLead($mDay=null,$lID=null,$dbug=NULL,$direct=NULL)
	{
		global $wpdb;
		if(!count($this->lead) || !count($this->msg)) { return 0; }
		$this->formatMsg(1);
        	$data = array(
            'method'      => 'mail',
    				'From'     		=> $this->lead['xEmail'],
    				'FromName' 		=> $this->lead['xName'],
    				'recepientMail' => $this->lead['user_email'],
    				'recepientName' => $this->lead['display_name'],
    				'subject'       => $this->msg['mSubject'],
    				'body'          => stripslashes($this->msg['mBody']),
    				'ContentType'   => $this->msg['mHeader'],
    				'priority'      => '3',
    				'SendDate'      => time(),
    				'mAttach'       => $this->msg['mAttach'],
    				);
    $add = ar_gwa_add_email($data,$dbug);
	}

	function mailLead($mDay=null,$lID=null,$dbug=NULL,$direct=NULL)
	{
		global $wpdb;
		if(!count($this->lead) || !count($this->msg)) { return 0; }
		$this->formatMsg();
        	$data = array(
            'method'      => 'mail',
    				'From'     		=> $this->lead['xEmail'],
    				'FromName' 		=> $this->lead['xName'],
    				'recepientMail' => $this->lead['lEmail'],
    				'recepientName' => $this->lead['lName'],
    				'subject'       => $this->msg['mSubject'],
    				'body'          => stripslashes($this->msg['mBody']),
    				'ContentType'   => $this->msg['mHeader'],
    				'priority'      => '3',
    				'SendDate'      => time(),
    				'mAttach'       => $this->msg['mAttach'],
    				);
    $add = ar_gwa_add_email($data,$dbug);

    if(isset($this->msg['mDay']))
      $subq = "lMOut='".$this->msg['mDay']."', ";
		$qry = "UPDATE ".$wpdb->prefix."ar_gwa_leads SET $subq lDateOut=current_date WHERE lID='".$this->lead['lID']."'";
		$wpdb->query($qry);
	}
	
	function formatMsg($WP=NULL)
	{
		$unsubscribe = get_bloginfo('url').'/index.php?uID='.$this->lead['lID'] . '&Email='.htmlentities($this->lead['lEmail']);
		$archivelink = get_bloginfo('url').'/index.php?aID='.$this->lead['lID'] . '&Email='.htmlentities($this->lead['lEmail']);
		$affiliate = 'http://www.freeautoresponder.biz/?/'.get_option('ar_gwa_aff');
    $affiliate_text = "Wordpress Newsletter Manager\r\n".$affiliate;
		$ar_gwa_no_spam = get_option('ar_gwa_no_spam');
    if($ar_gwa_no_spam=='checked'){
		$ar_gwa_nospam_text = "\r\n\r\n".get_option('ar_gwa_nospam');    
    } else {
		$ar_gwa_nospam_text = "\r\n\r\n".get_option('ar_gwa_footer_'.$this->lead['lLID']);    
    }
		if($this->msg['mType'] == 'html') {
     if($ar_gwa_no_spam=='checked' && $ar_gwa_nospam_text != '') {
     $ar_gwa_nospam_text = preg_replace("/\r\n\r\n/",'<p>',$ar_gwa_nospam_text);
     $ar_gwa_nospam_text = preg_replace("/\r\n/",'<br>',$ar_gwa_nospam_text);
         }
     $affiliate_text = '<br /><br /><a href="'.$affiliate.'">Wordpress Newsletter Manager</a>';
     $unsubscribe = '<br /><br /><a href="'.$unsubscribe.'">'.get_option('ar_gwa_unsub').'</a>'; 
     $archivelink = '<br /><br /><a href="'.$archivelink.'">View your message archive.</a>'; 
    } else {
     $unsubscribe = "\r\n\r\n".get_option('ar_gwa_unsub')."\r\n$unsubscribe";     
     $archivelink = "\r\n\r\n"."View your message archive.\r\n$archivelink"; 
    }

    if($WP==1) {
    $unsubscribe = "\n\n".__('Sent as part of your blog membership at','argwa').' '.get_bloginfo('name').".\n\n";
		$this->msg['mBody'] = str_replace('<?Name?>', $this->lead['display_name'], $this->msg['mBody']);
		$this->msg['mSubject'] = str_replace('<?Name?>', $this->lead['display_name'], $this->msg['mSubject']);
		$this->msg['mBody'] = str_replace('<?Email?>', $this->lead['user_email'], $this->msg['mBody']);
		$this->msg['mSubject'] = str_replace('<?Email?>', $this->lead['user_email'], $this->msg['mSubject']);
    } else {
		$this->msg['mBody'] = str_replace('<?Name?>', $this->lead['lName'], $this->msg['mBody']);
		$this->msg['mSubject'] = str_replace('<?Name?>', $this->lead['lName'], $this->msg['mSubject']);
		$this->msg['mBody'] = str_replace('<?Email?>', $this->lead['lEmail'], $this->msg['mBody']);
		$this->msg['mSubject'] = str_replace('<?Email?>', $this->lead['lEmail'], $this->msg['mSubject']);
    }
		$this->msg['mBody'] = str_replace('<?Unsubscribe?>', $unsubscribe, $this->msg['mBody']);
		$this->msg['mBody'] = str_replace('<?Archive?>', $archivelink, $this->msg['mBody']);
		$this->msg['mBody'] = str_replace('<?Field1?>', $this->lead['lField1'], $this->msg['mBody']);
		$this->msg['mBody'] = str_replace('<?Field2?>', $this->lead['lField2'], $this->msg['mBody']);
		$this->msg['mBody'] = str_replace('<?Field3?>', $this->lead['lField3'], $this->msg['mBody']);
		$this->msg['mBody'] = str_replace('<?Field4?>', $this->lead['lField4'], $this->msg['mBody']);
		$this->msg['mBody'] = str_replace('<?Field5?>', $this->lead['lField5'], $this->msg['mBody']);		
//For html emails composed in tinymce
    if($WP==1) {
		$this->msg['mBody'] = str_replace('&lt;?Name?&gt;', $this->lead['display_name'], $this->msg['mBody']);
		$this->msg['mSubject'] = str_replace('&lt;?Name?&gt;', $this->lead['display_name'], $this->msg['mSubject']);
		$this->msg['mBody'] = str_replace('&lt;?Email?&gt;', $this->lead['user_email'], $this->msg['mBody']);
		$this->msg['mSubject'] = str_replace('&lt;?Email?&gt;', $this->lead['user_email'], $this->msg['mSubject']);
    } else {
		$this->msg['mBody'] = str_replace('&lt;?Name?&gt;', $this->lead['lName'], $this->msg['mBody']);
		$this->msg['mSubject'] = str_replace('&lt;?Name?&gt;', $this->lead['lName'], $this->msg['mSubject']);
		$this->msg['mBody'] = str_replace('&lt;?Email?&gt;', $this->lead['lEmail'], $this->msg['mBody']);
		$this->msg['mSubject'] = str_replace('&lt;?Email?&gt;', $this->lead['lEmail'], $this->msg['mSubject']);    
    }
		$this->msg['mBody'] = str_replace('&lt;?Unsubscribe?&gt;', $unsubscribe, $this->msg['mBody']);
		$this->msg['mBody'] = str_replace('&lt;?Archive?&gt;', $archivelink, $this->msg['mBody']);
		$this->msg['mBody'] = str_replace('&lt;?Field1?&gt;', $this->lead['lField1'], $this->msg['mBody']);
		$this->msg['mBody'] = str_replace('&lt;?Field2?&gt;', $this->lead['lField2'], $this->msg['mBody']);
		$this->msg['mBody'] = str_replace('&lt;?Field3?&gt;', $this->lead['lField3'], $this->msg['mBody']);
		$this->msg['mBody'] = str_replace('&lt;?Field4?&gt;', $this->lead['lField4'], $this->msg['mBody']);
		$this->msg['mBody'] = str_replace('&lt;?Field5?&gt;', $this->lead['lField5'], $this->msg['mBody']);

if(!class_exists('ar_gwa_user_edit') && file_exists(dirname(__FILE__).'/ar_gwa_user_edit.php')) include_once(dirname(__FILE__).'/ar_gwa_user_edit.php');
  if(class_exists('ar_gwa_user_edit') && $uca = new ar_gwa_user_edit($this->lead['lID'])){
    $this->msg['mBody'] = str_replace('<?Update?>',$uca->sendEditLink($this->msg['mType']), $this->msg['mBody']);
		$this->msg['mBody'] = str_replace('&lt;?Update?&gt;',$uca->sendEditLink($this->msg['mType']), $this->msg['mBody']);
  }
  
	if($this->msg['mType'] == 'html') { $lb = '<br /><br />'; } else { $lb ="\r\n\r\n"; }
  if(isset($ar_gwa_nospam_text) && $ar_gwa_nospam_text != '')
    $this->msg['mBody'] .= $ar_gwa_nospam_text.$lb;
	if(get_option('ar_gwa_cb')=='checked')
    $this->msg['mBody'] .= $lb.$affiliate_text.$lb;
	if(get_option('ar_gwa_addsub')==1)
    $this->msg['mBody'] .= $lb.$unsubscribe.$lb;
  
if( !class_exists('ar_gwa_track') & file_exists(dirname(__FILE__).'/ar_gwa_track.php')) {
    include_once(dirname(__FILE__).'/ar_gwa_track.php');
#  if(class_exists("ar_gwa_track")){
    $trk = new ar_gwa_track();
    $this->msg['mBody'] = $trk->sendTrack($this->msg['mBody'],$this->msg['mType']);
  } else if( class_exists('ar_gwa_track')) {
    $trk = new ar_gwa_track();
    $this->msg['mBody'] = $trk->sendTrack($this->msg['mBody'],$this->msg['mType']);
  }
 }
}

function ar_gwa_add_email($params,$dbug){
global $wpdb,$ar_gwa_debug;
if($dbug && $ar_gwa_debug=="ON") $wpdb->show_errors();
    if(get_option('ar_gwa_smtp_auth')=='checked') {
    $params['method'] = 'smtp';
    $params['Host'] = get_option('ar_gwa_smtp_srv');
    $params['Username'] = get_option('ar_gwa_smtp_user');
    $params['Password'] = get_option('ar_gwa_smtp_pass');
    }
    $data=array('method'   		=> ( isset($params['method']) )    	   ? $params['method']   	 : 'mail',
    				'From'     		=> ( isset($params['From']) )     	   ? $params['From']     	 : 'root@localhost',
    				'FromName' 		=> ( isset($params['FromName']) ) 	   ? $params['FromName'] 	 : 'Root Account',
    				'Host'     		=> ( isset($params['Host']) )      	   ? $params['Host']     	 : 'localhost',
    				'SMTPAuth' 		=> ( isset($params['SMTPAuth']) ) 	   ? $params['SMTPAuth'] 	 : true,
    				'Username' 		=> ( isset($params['Username']) ) 	   ? $params['Username'] 	 : 'root@localhost',
    				'Password' 		=> ( isset($params['Password']) )  	   ? $params['Password'] 	 : '',
    				'recepientMail' => ( isset($params['recepientMail']) ) ? $params['recepientMail'] : false,
    				'recepientName' => ( isset($params['recepientName']) ) ? $params['recepientName'] : '',
    				'subject'       => ( isset($params['subject']) )       ? $params['subject']       : false,
    				'body'          => ( isset($params['body']) )          ? $params['body']          : false,
    				'ContentType'   => ( isset($params['ContentType']) )   ? $params['ContentType']   : 'text/plain',
    				'priority'      => ( isset($params['priority']) )      ? $params['priority']      : '3',
    				'SendDate'      => ( isset($params['SendDate']) )      ? $params['SendDate']      : time()
    				);
    	if(isset($params['mAttach']) & $params['mAttach']!='')
      $data['mAttach'] = $params['mAttach'];  
    	$error=false;			
    	foreach ( $data as $key=>$value ){
        $sql1 .= "`".$key.'`,';
        $sql2 .= "'".$wpdb->escape($value)."',";
    		if ($value===false) {
    			$error=true;
    			$errorMsg="Cannot add Mail. Empty value for [$key]";
    		} 
    	}
    	
    	if ( $error===true ){
    	    		die( $errorMsg);
	$this->errorMsg=$errorMsg;
      if($dbug && $ar_gwa_debug=="ON" && $this->errorMsg)
    	echo "<br>Error for: ".$params['recepientMail']." : ".$this->errorMsg."<br>";
# echo $errorMsg;exit;
      	return false;
    	} else {
      $sql1 = substr($sql1, 0, -1);
      $sql2 = substr($sql2, 0, -1);
      $qry = "INSERT INTO {$wpdb->prefix}ar_gwa_queue ($sql1) VALUES ($sql2)";
    			$insertAttempt=$wpdb->query($qry);
    			if ($insertAttempt===true) return true;
    			else {    			
		    		return false;    				
    			}
    	}	
}

function ar_gwa_export_file() {
global $wpdb,$export_separator;
if($listid = $_REQUEST['ar_gwa_list_id'])
  $qual = "WHERE lLID='".$listid."' AND lCnf='1'";
else if(!isset($_REQUEST['RESET']))
  $qual = "WHERE lLID='".ar_gwa_main_list()."' AND lCnf='1'";
  
$qry = "SELECT * FROM ".$wpdb->prefix."ar_gwa_leads $qual ORDER BY lName";
$res = $wpdb->get_results($qry,ARRAY_A);
if(count($res)) {
 foreach($res as $row)
 {
#		$buffer .= $row[lName].','.$row[lEmail]."\n";
$buffer .= '<option value="'.$row[lName].','.$row[lEmail].'">'.$row[lName].','.$row[lEmail].'</option>';
foreach($row as $k=>$v)
  $row[$k] = trim($v);
$mbuffer .= "{$row['lName']}".$export_separator."{$row['lEmail']}";
$tmbuffer='';
if($row['lField1'] != '') $tmbuffer .= $export_separator."{$row['lField1']}";
else $tmbuffer .= $export_separator."null";
if($row['lField2'] != '') $tmbuffer .= $export_separator."{$row['lField2']}";
else $tmbuffer .= $export_separator."null";
if($row['lField3'] != '') $tmbuffer .= $export_separator."{$row['lField3']}";
else $tmbuffer .= $export_separator."null";
if($row['lField4'] != '') $tmbuffer .= $export_separator."{$row['lField4']}";
else $tmbuffer .= $export_separator."null";
if($row['lField5'] != '') $tmbuffer .= $export_separator."{$row['lField5']}";
else $tmbuffer .= $export_separator."null";
if($row['lDateEntry'] != '') $tmbuffer .= $export_separator."{$row['lDateEntry']}";
else $tmbuffer .= $export_separator."null";
if($row['lIP'] != '') $tmbuffer .= $export_separator."{$row['lIP']}";
else $tmbuffer .= $export_separator."null";
$mbuffer .= $tmbuffer."\n";
 }
}
echo $mbuffer;
}

function ar_gwa_export_dl() {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="ar_gwa_leads.xls"'); 
header('Content-Transfer-Encoding: binary');
ar_gwa_export_file();
exit;
}

function ar_gwa_plugin_addon() {
  if(file_exists(dirname(__FILE__).'/ar_gwa_help.php')) 
    include_once(dirname(__FILE__).'/ar_gwa_help.php');
  if(file_exists(dirname(__FILE__).'/ar_gwa_wizard.php')) 
    include_once(dirname(__FILE__).'/ar_gwa_wizard.php');
  if(file_exists(dirname(__FILE__).'/ar_gwa_bounce.php')) 
    include_once(dirname(__FILE__).'/ar_gwa_bounce.php');
  if(file_exists(dirname(__FILE__).'/ar_gwa_attach.php')) 
    include_once(dirname(__FILE__).'/ar_gwa_attach.php');
  if(file_exists(dirname(__FILE__).'/ar_gwa_template.php')) 
    include_once(dirname(__FILE__).'/ar_gwa_template.php');
  if(file_exists(dirname(__FILE__).'/ar_gwa_track.php')) 
    include_once(dirname(__FILE__).'/ar_gwa_track.php');
  if(file_exists(dirname(__FILE__).'/ar_gwa_calendar.php')) 
    include_once(dirname(__FILE__).'/ar_gwa_calendar.php');
  if(file_exists(dirname(__FILE__).'/ar_gwa_user_edit.php')) 
    include_once(dirname(__FILE__).'/ar_gwa_user_edit.php');
  if(file_exists(dirname(__FILE__).'/ar_gwa_newsletter.php')) 
    include_once(dirname(__FILE__).'/ar_gwa_newsletter.php');
}

function ar_gwa_plugin_i18n() {
if(isset($_REQUEST['ar_gwa_export_dl'])) 
    ar_gwa_export_dl();

			$currentLocale = get_locale();
			if(!empty($currentLocale)) {
				$moFile = dirname(__FILE__) . "/argwa-" . $currentLocale . ".mo";
				if(@file_exists($moFile) && is_readable($moFile)) load_plugin_textdomain('argwa',false,dirname( plugin_basename( __FILE__ ) ));
}}

function argwa_get_note($n) {
$cont['1'] = __("<b>Autoresponder Status Box</b> provides an instant overview of plugin operations. <b>Send Time</b> is when messages are generated and sent to subscribers. Click the button to reset the Send Time to any time within the next 24hrs.",'argwa');
$cont['3'] = __("<b>Fly-in Boxes</b> can be used to highlight your subscription forms. May require some CSS modifications for full theming compatability. Follow the link to setup these options before enabling.",'argwa');
$cont['4'] = __("<b>Enter and include</b> a custom footer and unsubscribe link for every message by ticking the checkboxes. Be sure to complete all the options below when using [shortcode] forms and responses.",'argwa');
$cont['5'] = __("<b>View and access</b> all your list details by clicking the List# links. Click the list name to go to the Messages page and click the number to go to the Leads page for each list shown.",'argwa');
$cont['6'] = __("<b>Enter your API Key</b> from the Download Page in your Members Area on the website at http://freeautoresponder.biz.",'argwa');
$cont['7'] = __("<b>Activate SMTP delivery</b> for your plugin. Check with your email provider and enter your smtp connection details. Be sure to select the correct protocol (none/tls/ssl) and check the Test box to verify.",'argwa');
$cont['8'] = __("<b>Intelligent Queue throttle setup</b> can be left at default values. See the Help Page of the plugin or the Wizard for instructions on setting these values to meet your hosting limits.",'argwa');
$cont['9'] = __("<b>Additional settings</b> used throughout the plugin. When using composing email in alternate languages you must select the proper character-set fto display accented and special characters.",'argwa');
$cont['10'] = __("<b>Click the [CREATE LIST] button</b> to create your next list. Click the Update Link on the far right (for each list) to access setup page of options. Use the checkboxes on the left and the [DELETE] button to remove list.",'argwa');
$cont['30'] = __("<b>All your Leads are listed here.</b> Enter address in the search box and click [GO] to find record(s) or select a single list (or Unconfirmed) and click [FILTER] to reload. Click 'View Info' to access additional lead info fields. Edit record fields on this page directly. Click CANCEL to release any edit box unchanged.",'argwa');
$cont['31'] = __("<b>Click subject line to edit a message contents.</b> To <b>send a mass mailing</b> use the [Send Message] button. To add a new message click the [Add Message] button. Use the select-box and [FILTER] button to view a single list.",'argwa');
$cont['32'] = __("<b>Messages in Queue are waiting to be sent.</b> Control how many messages are sent (and how often) using the Throttle Settings under Global Options on the",'argwa')." <a href='?page=autoresponder-gwa/ar_gwa.php'>GWA Options</a> ".__("menu page",'argwa').'.';
$cont['33'] = __("Newsletter name is displayed in the From: field of emails. Label appears in subscription form widget. From: email address should be an active local address at your blog domain (not gmail/hotmail/yahoo.) Use the exact <b>[short-code]</b> in your page and post content to display subscription form and responses when selected as forward page. See more below.",'argwa');
$cont['34'] = __("Select a page to display as the on-site user-info update page. Enter the field descriptions to display on the page. Tick the check-box to display these fields or leave it empty to hide them. Email and name fields always accessible.",'argwa');
$cont['35'] = __("Choose a blog page to show <b>after subscribing</b> or enter an external page url to forward. If using [shortcode] the response shown is set on the",'argwa')." <a href='?page=autoresponder-gwa/ar_gwa.php'>GWA Options</a> ".__("menu page",'argwa').'.';
$cont['36'] = __("Choose a blog page to show <b>after clicking confirm link</b> or enter an external page url to forward. If using [shortcode] the response shown is set on the",'argwa')." <a href='?page=autoresponder-gwa/ar_gwa.php'>GWA Options</a> ".__("menu page",'argwa').'.';
$cont['37'] = __("Choose a blog page to show <b>after un-subscribing</b> or enter an external page url to forward. If using [shortcode] the response shown is set on the",'argwa')." <a href='?page=autoresponder-gwa/ar_gwa.php'>GWA Options</a> ".__("menu page",'argwa').'.';
$cont['38'] = __("<b>Set additional list options here.</b> All options apply to this list only. See Help Page for guide to using CAPTCHA and modifications to subscription form required.",'argwa');
$cont['39'] = __("<b>Edit your subscription form</b> displayed with the widget/shortcode using the editor. Be sure to tick update radio-button below editor when submitting to confirm the changes. Switch to PLAIN-TEXT to paste/access raw html only or use the [HTML] button in the editor.",'argwa');
$cont['40'] = __("<b>Edit your Fly-in form here.</b> See PDF for Xinha Editor installation instructions.",'argwa');
$cont['41'] = __("<b>Edit your Slide-in form here.</b> See PDF for Xinha Editor installation instructions.",'argwa');
$cont['42'] = __("<b>Edit your Common List Footer here.</b> Will be displayed at bottom of all messages sent unless overridden by setting a footer on the",'argwa')." <a href='?page=autoresponder-gwa/ar_gwa.php'>GWA Options</a> ".__("menu page",'argwa').'.';
$cont['43'] = __("<b>Add messages to a Newsletter.</b> Select a list and set the Day Number (number of days after subscribing the message will be sent.) Select message format; controls email headers. DO NOT PASTE RAW HTML in PLAIN-TEXT window. Use HTML button in editor. Use PLAIN-TEXT to send unformatted text messages. Verify all dynamic field names are correct in message for substitutions to occur.",'argwa');
$cont['44'] = __("<b>Send Mass-Mailing to entire list.</b> Similar to Add Message page. Limit sending by subscription dates entered. Email entire Wordpress Members List by User Role or select Subscriber List. Verify all dynamic field names are correct in message for substitutions to occur.",'argwa');
$cont['45'] = __("<b>Templates for Newsletter Common Look and Feel.</b> Use the tag {CONTENT} inserted where you want your message text displayed. Select HTML or PLAIN-TEXT format. All dynamic fields available. See PDF in plugin package for more. Select for use on the Add and Send Message pages.",'argwa');
if($n<5) $ml=450; else $ml=338;
if($n<5) $m=150; else $m=450;
$tl=-20;
if($n>9) {$ml=-10;$tl=0;}
$note = '<div style="margin-left:'.$ml.'px;margin-bottom:'.$tl.'px;margin-top:-7px;width:24px;height:24px;float:right;"><a href="javascript:void(0);" id="note1_title" class="note" onclick="showNote(\'note'.$n.'\');"><img src="../wp-content/plugins/autoresponder-gwa/hlp.png" border=0></a></div><span id="note'.$n.'_body" class="notehidden"><br><div class="notebody" align="left" style="margin-left:'.$m.'px;margin-top:0px"><table class="notetitle" cellspacing="0" cellpadding="0"><tr><td><small>'.__("Help",'argwa').':</small></td><td align="right"><small>(<a href="javascript:void(0);" onclick="hideNote(\'note'.$n.'\');">'.__("hide",'argwa').'</a>)</small></td></tr></table>'.$cont[$n].'</div></span>&nbsp;';
return $note;
}
?>