<?php

session_start();

require 'authenticate.user.php';



require 'configuration.php';

require_once 'includes/common.functions.php';

require_once ('classes/database.php');

require_once ('classes/functions.php');

$sqlObj = new mysqlClass;

$funcObj = new funcClass;

$table = "##addressbook";

$curFile = basename(__FILE__);

$ACTION				= 'add';



if ($_SESSION['IS_USER_CLIENT'])

{

	die ("Sorry, you are not authorized to access this page");

}



$id = intval($_GET['id']);

if (empty($id))

	die("Required parameter is missing");



$query = "SELECT CAMPAIGN_NAME, FROM_NAME, FROM_EMAIL, REPLYTO_NAME, REPLYTO_EMAIL,SUBJECT  FROM ##campaigns WHERE ID = '{$id}'";

$result = $funcObj->CustomQuery($query);

$campaignName = $result[0]->CAMPAIGN_NAME;



$campaignID = $_SESSION['CAMPAIGNID'];

if (empty($campaignID))

	die ("Required data missing. Please try again from step 1");



###FETCH ACTIVE ADDRESSBOOK(S)########################

$query = "SELECT DISTINCT(A.NAME) AS NAME, A.ID AS ADDRID 

FROM ##addressbook AS A,

##campaign_send_stats AS B

WHERE B.ADDR_ID = A.ID

AND B.SESSION_ID = '".session_id()."'

AND B.CAMPAIGN_ID = '{$id}'";

$AddrResultSet = array();

$AddrResultSet = $funcObj->CustomQueryArray($query);

/* ACTIVATE THE TAB */

$activeTab = 'Campaigns';

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<title>Segnant Mailer - Manage Campaigns</title>

<link rel="stylesheet" type="text/css" href="includes/css/thickbox.css" />

<link rel="stylesheet" type="text/css" href="includes/css/segnantmailer.css" />

<link rel="stylesheet" type="text/css" href="includes/css/paging.css"  />

<script>

function silentErrorHandler() {return true;}



window.onerror=silentErrorHandler;

</script>

<script type="text/javascript" src="includes/js/prototype/prototype.js"></script>

<script type="text/javascript" src="includes/js/jquery-1.3.2.min.js"></script>

<script type="text/javascript" src="includes/js/common.jquery.js"></script>

<script type="text/javascript" src="includes/js/send4.jquery.js"></script>

<script type="text/javascript" src="includes/js/bramus/jsProgressBarHandler.js"></script>

<script type="text/javascript" src="includes/js/thickbox.js"></script>

<script>

var $j = jQuery.noConflict();

// Javascript Global counter start value.

var glbStartFrom 	= 1;



// JavaScript global percentage to show in the progress bar.

var glbPercentage 	= 0;



// To handle Pause and Resume Functionality.

// It will become 1 when somebody presses the Pause Button.

var glbPause 		= 0;



// Global variable for threads (how many simultaneous

// connections to establish for sending emails;

var threads;



// Global variable for campaign ID

// It will be used for sending AJAX request to send newsletters.

var glbID;



function mailingListWindow(id)

{

	newWin = window.open("mailinglist.php?id="+id,null,"height=650,width=600,status=yes,toolbar=0,scrollbars=1,menubar=no,location=no,resizable=no" );

}

</script>

<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />

</head>

<body>

<table width="100%" border="0" cellspacing="0" cellpadding="0">

  <tr>

    <td height="79" class="headerbg"><? require_once 'includes/inc.header.php' ?>    

    </td>

  </tr>



  <tr>

    <td class="canvas" height="300" valign="top"><table width="100%" border="0" cellspacing="10" cellpadding="4">

      <tr>

        <td width="100%" height="50" valign="top" class="heading">Send Campaign</td>

        </tr>

      <tr>

        <td><table width="100%" border="0" cellspacing="1" cellpadding="1"><tr><td><form name="frmListing" id="frmListing" method="post" style="margin:0; padding: 0" onsubmit="return ajaxSend()">

          <table width="100%" border="0" cellspacing="1" cellpadding="1">

            <?php if (!empty($message))

					  echo "

                      <tr>

                        <td class='message'>$message</td>

                      </tr>

					  ";

					  ?>

            <tr>

              <td><?

			  $resultSet = $funcObj->FetchRecords("$table",$searchTxt,$searchArray,'NAME ASC', $pageObj->start, $pageObj->limit);

			  ?>

                  <table width="100%" border="0" cellspacing="0" cellpadding="0" class="inactiveTable">

                    <tr class="inactiveTab">

                      <td width="30" align="center"><img src="images/10.png" alt="" hspace="8" border="0" /></td>

                      <td width="90%"><span><strong>Campaign:</strong> select data sources for "

                            <?=$campaignName?>

                        "</span></td>

                      <td width="10%" nowrap="nowrap" align="right" style="padding-right:10px"><a href="send.php?&id=<?=$id?>&action=edit">Edit Settings</a></td>

                    </tr>

                  </table>

                <table width="100%" border="0" cellspacing="0" cellpadding="0" class="inactiveTable" style="margin-top: 3px;">

                    <tr class="inactiveTab">

                      <td width="30" align="center"><img src="images/20.png" alt="" hspace="8" border="0" /></td>

                      <td width="90%"><span><strong>Campaign:</strong> summary for "

                            <?=$campaignName?>

                        "</span></td>

                      <td width="10%" nowrap="nowrap" align="right" style="padding-right:10px"><a href="send2.php?&id=<?=$id?>&action=edit">Edit Settings</a></td>

                    </tr>

                  </table>

                <table width="100%" border="0" cellspacing="0" cellpadding="0" class="inactiveTable" style="margin-top: 3px;">

                    <tr class="inactiveTab">

                      <td width="30" align="center"><img src="images/30.png" alt="" border="0" hspace="8" /></td>

                      <td width="90%"><span><strong>Campaign:</strong> live preview for "

                            <?=$campaignName?>

                        "</span></td>

                      <td width="10%" nowrap="nowrap" align="right" style="padding-right:10px"><a href="send3.php?&id=<?=$id?>&action=edit">Edit Settings</a></td>

                    </tr>

                  </table>

                <table width="100%" border="0" cellspacing="0" cellpadding="0" class="activeTable" style="margin-top: 3px;">

                    <tr class="activeTab">

                      <td align="left"><img src="images/41.png" alt="" hspace="8" border="0" align="absmiddle" /> <span><strong>Campaign:</strong> send</span></td>

                    </tr>

                    <tr>

                      <td colspan="2" height="40" style="padding: 8px;">You are on the final step of sending newsletters. On the right side of this screen you will get real-time statistics of email sending. <br />

                          <br />

                          Click on the start button to begin sending newsletters.</td>

                    </tr>

                    <tr>

                      <td colspan="2" align="center"><table width="100%" border="0" cellspacing="8" cellpadding="8">

                          <tr>

                            <td valign="top" align="center">

                            <table border="0" cellspacing="0" cellpadding="3" width="350">

                            <tr>

                            <td>

                            <table border="0" cellspacing="0" cellpadding="3" width="350" class="box">

                              <tr>

                                <td class="orange size14 bold" align="center" height="28" colspan="2">Send Campaign</td>

                              </tr>

                              <tr>

                                <td colspan="2" height="10" id="systemerror"></td>

                              </tr>

                              <tr>

                                <td width="30%" height="30" align="left">Progress&nbsp;&nbsp;</td>

                                <td align="left"><span id="element6">[ Loading Progress Bar ]</span></td>

                              </tr>

                              <tr>

                                <td align="left">&nbsp;</td>

                                <td height="40" align="left" nowrap="nowrap"><input type="submit" id="startSending" value="Start" class="button" /><input type="button" id="pauseResume" value="Pause" class="button" style="display:none" onclick='pauseOrResume()' /><img src="images/preloader1.gif" hspace="5" alt="" border="0" id="running" style="display: none" />

                               </td>

                              </tr>

                              <tr>

                                <td align="left">&nbsp;</td>

                                <td align="left"><a href="javascript:;" id="advancedSettingsLink">Advanced Settings</a><br />

                                <div id="advancedSettings" style="display:none">

                                <table width="100%" border="0" cellspacing="0" cellpadding="0" class="advancedTable innerbox" style="margin-top: 8px;">

                                  <tr>

                                    <td width="40%"> 

                                    Threads: 

                                    </td>

                                    <td>

                                    <input type="text" name="txtThreads" id="txtThreads" size="5" maxlength="2" class="textbox" dir="rtl" value="5" /> <small><a href="#TB_inline?height=50&width=350&inlineId=threadsdiv" class="thickbox">What's this?</a></small>

                                    </td>

                                  </tr>

                                  <tr>

                                    <td width="40%"> 

                                    Delay after Threads (sec): 

                                    </td>

                                    <td>

                                    <input type="text" name="txtDelay" id="txtDelay" size="4" maxlength="4" class="textbox" dir="rtl" value="60" /> <small><a href="#TB_inline?height=50&width=350&inlineId=delaydiv" class="thickbox">What's this?</a></small>

                                    </td>

                                  </tr>

                                  <tr>

                                    <td>Start From: 

                                    

                                    </td>

                                    <td>

                                    <input type="text" name="txtStartFrom" id="txtStartFrom" size="5" maxlength="5" class="textbox" dir="rtl" value="1" /> <small><a href="#TB_inline?height=50&width=350&inlineId=startfromdiv" class="thickbox">What's this?</a></small>

                                    <br /><a href="javascript:mailingListWindow('<?=$id?>')">See entire mailing list</a>

                                    </td>

                                  </tr>

                                  

                                </table>

                                </div>

                                </td>

                              </tr>

                            </table>

                            <table width="100%" border="0" cellspacing="0" cellpadding="4" style="margin-top: 4px; display: none;" class="box" id="debugtable">

                                  <tr>

                                    <td align="center" class="orange size14 bold" height="28">Debug Window</td>

                                  </tr>

                                  <tr>

                                    <td align="left" valign="top" height="90" ><div style="height: 90px; overflow:auto" id="debugmessage">&nbsp;</div></td>

                                    </tr>

                              </table>

                            </td>

                            </tr>

                            </table>

                            </td>

                            <td width="350" valign="top" ><table width="100%" border="0" cellspacing="0" cellpadding="4" style="margin-bottom:4px;" class="box">

                                <tr>

                                  <td align="center" class="orange size14 bold" height="28" colspan="2">General Information</td>

                                </tr>

                                <tr>

                                  <td width="35%" valign="top" align="left">Campaign: </td>

                                  <td valign="top" align="left"><?=$campaignName?></td>

                                </tr>

                                <tr>

                                  <td align="left" valign="top">Address Book(s):</td>

                                  <td align="left" valign="top"><?

								  $campIds = array();

								  $count = 1;

								  

								  if (count($AddrResultSet) > 1)

								  {

									  foreach($AddrResultSet as $row)

									  {

										

										$query = "SELECT COUNT(*) FROM ##contacts WHERE ADDR_ID = '{$row[ADDRID]}' AND IS_DELETED = 0";

										$countContacts = @$funcObj->CustomQueryCount($query);

										

										echo $count . '. ' . $row['NAME'] . " ({$countContacts})";

										$campIds[] = $row['ADDRID'];

										echo "<br />";

										$count++;

									  }

								  }

								  else

								  {

										foreach($AddrResultSet as $row)

									  	{

											$query = "SELECT COUNT(*) FROM ##contacts WHERE ADDR_ID = '{$row[ADDRID]}' AND IS_DELETED = 0";

											$countContacts = @$funcObj->CustomQueryCount($query);



											echo $row['NAME'] . " ({$countContacts})";

											$campIds[] = $row['ADDRID'];

											$count++;

									  	}

								  }

								  ?>                                  </td>

                                </tr>

                                <tr>

                                  <td align="left" valign="top">Mailer:</td>

                                  <td align="left" valign="top"><?

								$query = "SELECT *	FROM ##smtp WHERE `DEFAULT` = '1'";

								$resultSetSMTP = array();

								$resultSetSMTP = $funcObj->CustomQuery($query);

								if (count($resultSetSMTP))

								{

									if ($resultSetSMTP[0]->MAILER_TYPE == 'smtp')

									{

										echo $resultSetSMTP[0]->TITLE;

									}

									else

									{

										echo $resultSetSMTP[0]->MAILER_TYPE;

									}

								}

								else

								{

									// Bind alert message with Start button

									echo "<strong style='color: red'>No default SMTP Mailer.</strong>";

									$prohibitProceed = " onclick='return noDefaultSMTP()' ";

								}

								?>                                </td>

                                </tr>

                              </table>

                                <table width="100%" border="0" cellspacing="0" cellpadding="4" class="box">

                                  <tr>

                                    <td align="center" class="orange size14 bold" height="28" colspan="2">Newsletter Statistics</td>

                                  </tr>

                                  <tr>

                                    <td width="35%" align="left" valign="top">Unique Emails #: </td>

                                    <td align="left" valign="top">

									<?

									$campIdsStr = implode(",", $campIds);

									$query = "SELECT COUNT(DISTINCT(EMAIL)) AS TOTAL FROM ##contacts WHERE ADDR_ID IN ($campIdsStr) AND IS_DELETED = 0";

									$resultCampIds = $funcObj->CustomQuery($query);

									echo $resultCampIds[0]->TOTAL;

									?>                                   </td>

                                  </tr>

                                  <tr>

                                    <td align="left" valign="top">Successfully Sent:</td>

                                    <td align="left" valign="top" id="successfullySent">0</td>

                                  </tr>

                                  <tr>

                                    <td align="left" valign="top">Failed:</td>

                                    <td align="left" valign="top" nowrap="nowrap" ><span id="emailsFailed">0</span> &nbsp; <a href="javascript:;" onclick="seeFailedEmails()">See failed emails</a></td>

                                  </tr>

                                  <tr>

                                    <td align="left" valign="top">&nbsp;</td>

                                    <td align="left" valign="top"><div id="failedEamilsDiv" style="display:none; height: 150px; overflow:auto; vertical-align:top" class="innerbox">

                                    <div class="size14 bold" style="vertical-align:top">Failed E-mails <span class="size12 bold">(Hard Bounce)</span></div>

                                    </div></td>

                                  </tr>

                              </table></td>

                          </tr>

                      </table></td>

                    </tr>

                  </table>

                <input type="hidden" name="campaignId" id="campaignId" value="<?php echo $id?>" />

                  </td>

            </tr>

          </table>

        </form>

        <script type="text/javascript">

				document.observe('dom:loaded', function() {



					// second manual example : multicolor (and take all other default paramters)

					manualPB2 = new JS_BRAMUS.jsProgressBar(

								$('element6'),

								0,

								{



									barImage	: Array(

										'images/bramus/percentImage_back4.png',

										'images/bramus/percentImage_back3.png',

										'images/bramus/percentImage_back2.png',

										'images/bramus/percentImage_back1.png'

									),



									onTick : function(pbObj) {



										switch(pbObj.getPercentage()) {

											case 100:

												

												// When all emails are sent

												// change the button label to Done

												// and disable it.

												jQuery('#pauseResume').val('Done');

												jQuery('#pauseResume').attr("disabled", "disabled");

												glbPause = 1;

												jQuery('#running').hide();

												

												//alert('Progressbar full at 100% ... maybe do a redirect or sth like that here?');

											break;



										}



										return true;

									}

								}

							);

				}, false);

			</script>

        </td>

              </tr>

        </table>

        </td>

      </tr>

    </table></td>

  </tr>

<? require_once 'includes/inc.footer.php' ?>

</table>

<div id="threadsdiv" style="display: none">

<strong class="size14 bold">Threads:</strong>



<p>In this new mailer version you can open multiple connections to send newsletters. The more the connections (threads) the faster it will send emails. But it may also result into failing or connection timeout errors. Therefore, the idle thread rate basically depends upon your computer performance and internet speed. If it starts failing try to reduce the thread rate. The default thread rate is 10. You can change them to 1, 2, 5, 10, 15, 20 etc.</p>

</div>

<div id="delaydiv" style="display: none">

<strong class="size14 bold">Delay after Threads:</strong>



<p>If you like this application to send one set of threads and then hold for certain time so that the SMTP server does not treat emails as SPAM.  <br /><br />

<b>This is how it works:</b><br /><br />

<strong>Example 1:</strong><br/>

Send 5 emails and then hold for 1 minute:<br />

Threads: 5<br />

Delay after Threads: 60<br /><br />

<strong>Example 2:</strong><br/>

Send 100 emails and then hold for 5 minutes:<br />

Threads: 100<br />

Delay after Threads: 300<br /><br />

<em>Enter the delay amount in seconds. Enter 0 (zero) for no delay.</em>

</p>

</div>

<div id="startfromdiv" style="display: none">

<strong class="size14 bold">Start From:</strong>

<p>By default the application will start sending emails from the very first record. But there may be a need to start the application from mid way (from a given record#). This feature will help.



For instance, your application failed at 120th record due to any reason. Then in the second attempt you need not to start it all from begining. You can start sending newsletters right from 120record by entering 120 value in the <em>Start From</em> input box.

</p>

<p><a href="#" class="orange">Click here</a> to see the entire mailing list addresses which will help you to find the <em>Start From</em> counter.</p>

</div>

</body>

</html>