<?php 
session_start();
$ID 				= NULL;
$ADDR_ID			= NULL;
$EMAIL				= NULL;
$FIRSTNAME			= NULL;
$LASTNAME			= NULL;
$MISC_1				= NULL;
$MISC_2				= NULL;
$MISC_3				= NULL;
$IS_DELETED 		= 0;
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;
$curFile = basename(__FILE__);
$table = "##contacts";
$ACTION				= 'add';
require_once ('includes/validate.contacts.php');

$appendToQuery = "";
## If the client is logged in then 
## give access to only those addressbooks for which
## access has been granted to this user.
$currentUserId 	= intval($_SESSION['SUPER_USER_ID']);

if ($_SESSION['IS_USER_CLIENT'])
{

	$query = "SELECT DISTINCT ADDR_ID FROM smlr_campaign_send_stats WHERE CAMPAIGN_ID IN (SELECT CAMPAIGN_ID FROM smlr_client_access WHERE USER_ID = '$currentUserId')";
	$resultSet = $funcObj->CustomQuery($query);
	
	$inArray = array();
	foreach ($resultSet as $row)
	{
		$inArray[] = $row->ADDR_ID;
	}
	
	if (!count($inArray))
	{
		$inArray[] = '0';
	}
	
	$inArrayStr = implode(",", $inArray);
	
	$appendToQuery = " WHERE ID IN ($inArrayStr) ";
	$appendToQuery2 = " AND ID IN ($inArrayStr) ";
	
	$appendToQuery3 = " ADDR_ID IN($inArrayStr) ";
}
else
{
	$appendToQuery3 = " ADDR_ID > 0 ";
}

$query = "SELECT ID, NAME FROM ##addressbook $appendToQuery ORDER BY NAME";
$addrBookDropdownResultSet = array();
$addrBookDropdownResultSet = $funcObj->CustomQuery($query);

if (empty($_GET['addrid']))
{
	$defaddrid =isset($_GET['defaddrid']) ? $_GET['defaddrid'] :'';
	$activeAddrBook = ($defaddrid > 0) ? "WHERE ADDR_ID = {$defaddrid}" : "WHERE $appendToQuery3";
}	
else
{
	
	$activeAddrBook = ($_GET['addrid'] > 0) ? "WHERE ADDR_ID = {$_GET['addrid']}" : "WHERE $appendToQuery3"; 
}
//ADD RECORD
if ((isset($_POST['formaction']) && $_POST['formaction'] == 'add') && (empty($error)))
{
	## ADD A CUSTOM RECORD IN THE SELECTED ADDRESS BOOK
	if ($_POST['formtype'] == 'custom')
	{
		# check for duplicate record entry
		$query = "SELECT COUNT(*) FROM $table WHERE EMAIL = '$EMAIL' AND ADDR_ID = $ADDR_ID";
		$queryCount = $funcObj->CustomQueryCount($query)[0]['COUNT(*)'];
		if ($queryCount == 0)
		{
			$query = "INSERT INTO $table SET ADDR_ID='$ADDR_ID', EMAIL='$EMAIL', FIRSTNAME='$FIRSTNAME', LASTNAME='$LASTNAME', MISC_1='$MISC_1', MISC_2='$MISC_2', MISC_3='$MISC_3', LAST_UPDATED=NOW(),IS_USED =0,IS_DELETED=0";
			
			$insertId = $funcObj->insertQuery($query);
			if ($insertId > 0)
			{
				$message = "Record has been added successfully";
			}
			## RESET THE FORM SO THAT 
			## NO VALUES SHOULD BE SHOWN
			## IF THE FORM IS IN THE ADD
			## MODE
			
		}
		else
		{
			$message = "Same contact already available in this address book. Please try with different contact.";
		}
	}
}

## DELETE MULTIPLE RECORDS
if (isset($_POST['formtype']) && $_POST['formtype'] == 'multipledelete')
{
	if ($_POST['delOrUndel'] == 'del')
	{
		if (count($_POST['chkContacts']))
		{
			$delIDs = implode("," ,$_POST['chkContacts']);
			$query = "UPDATE ##contacts SET IS_DELETED = 1 WHERE ID IN ($delIDs)";
			$funcObj->updateQuery($query);
			$message = "Contact(s) have been un-subscribed successfully.";	
		}
	}
	else
	{
		if (count($_POST['chkContacts']))
		{
			$delIDs = implode("," ,$_POST['chkContacts']);
			$query = "UPDATE ##contacts SET IS_DELETED = 0 WHERE ID IN ($delIDs)";
			$funcObj->updateQuery($query);
			$message = "Contact(s) have been subscribed (undo un-subscribed) successfully.";	
		}
	}
}

//EDIT RECORD
if ((isset($_POST['formaction']) && $_POST['formaction'] == 'edit') && (empty($error)))
{
	
	
	# check for duplicate record entry
	$query = "SELECT COUNT(*) FROM $table WHERE EMAIL = '$EMAIL' AND ADDR_ID = $ADDR_ID";
	$countRecords = $funcObj->CustomQueryCount($query)[0]['COUNT(*)'];
	
	if ($countRecords < 2)
	{
		
		$query = "UPDATE $table SET ADDR_ID='$ADDR_ID', EMAIL='$EMAIL', FIRSTNAME='$FIRSTNAME', LASTNAME='$LASTNAME', MISC_1='$MISC_1', MISC_2='$MISC_2', MISC_3='$MISC_3', IS_DELETED = '$IS_DELETED', LAST_UPDATED=NOW()"; 
		$query .= " WHERE ID = {$ID}";
		
		$updateId = $funcObj->updateQuery($query);
		if ($updateId == 1)
		{
			$message = "Record has been successfully updated.";
		}
		
		## RESET THE FORM SO THAT 
		## NO VALUES SHOULD BE SHOWN
		## IF THE FORM IS IN THE ADD
		## MODE
		
		
	}
	else
	{
		$message = "Same contact already available in this address book. Please try with different contact.";
	}
}

## if edit is EDIT
# then load values into the form
if (isset($_GET['action']) && $_GET['action'] == 'edit')
{
	$ID = $_GET['id'];
	$whereFields['ID'] = $ID;
	$resultSet = $funcObj->getRecordDetails($table,$whereFields);
	$ID					= trim($funcObj->AppendSlashes($resultSet[0]['ID']));
	$ADDR_ID			= trim($funcObj->AppendSlashes($resultSet[0]['ADDR_ID']));
	$EMAIL				= trim($funcObj->AppendSlashes($resultSet[0]['EMAIL']));
	$FIRSTNAME			= trim($funcObj->AppendSlashes($resultSet[0]['FIRSTNAME']));
	$LASTNAME			= trim($funcObj->AppendSlashes($resultSet[0]['LASTNAME']));
	$MISC_1 			= trim($funcObj->AppendSlashes($resultSet[0]['MISC_1']));
	$MISC_2 			= trim($funcObj->AppendSlashes($resultSet[0]['MISC_2']));
	$MISC_3 			= trim($funcObj->AppendSlashes($resultSet[0]['MISC_3']));
	$IS_DELETED			= trim($funcObj->AppendSlashes($resultSet[0]['IS_DELETED']));
	
	$ACTION				= 'edit';
}

if (isset($_GET['action']) && $_GET['action'] == 'addcontact')
{
	$ADDR_ID = $_GET['defaddrid'];	
}
$searchbox=isset($_REQUEST['searchbox']) ? $_REQUEST['searchbox'] : '';
$status=isset($_REQUEST['status']) ? $_REQUEST['status'] : '';
$ID=isset($_REQUEST['id']) ? $_REQUEST['id'] : '';
$searchTxt = trim($funcObj->AppendSlashes($searchbox));
$searchArray = 'ID,EMAIL,FIRSTNAME,LASTNAME,MISC_1,MISC_2,MISC_3,LAST_UPDATED';
$getsearchbox=isset($_GET['searchbox']) ? $_GET['searchbox'] : '';
$doUpdation = false;

switch ($status)
{
	case 'activate': 
		$setField	= 'IS_ACTIVE';
		$setValue	= '1';
		$doUpdation = true;
		break;
	case 'deactivate': 
		$setField	= 'IS_ACTIVE';
		$setValue	= '0';
		$doUpdation = true;
		break;
}	

if($doUpdation)
{
	$whereField = "ID";
	$whereValue = $ID;
    $funcObj->UpdateRecord($table,$setField,$setValue,$whereField,$whereValue);
}	

if(isset($_GET['action']) && $_GET['action']=='del')
{
	$setField = "IS_DELETED";
	$setValue = '1';
	$id = intval($_GET['id']);
	
	/*
	If this email address has been used in any campaign then unsubscribe
	this email address; if never used then safely remove it physically.
	*/
	if ($_GET['used'] == '1')
	{
		$funcObj->UpdateRecord($table,$setField,$setValue,'ID',$id);
		$message = "Contact has been un-subscribed successfully.";
	}
	else
	{
		$funcObj->DeleteRecord($table,'ID',$id);
		$message = "Contact has been deleted successfully.";
	}	
}


$resultSet = $funcObj->CountAllRecords("$table $activeAddrBook ",$searchTxt,$searchArray);

$records	= $funcObj->fetchParameterValue('SHOW_RECORDS_PER_PAGE')[0]['FIELDVALUE'];
if($records > 0)
{
	$limit = intval($records);
}
else
{
	$limit = $configAdminPaging;
}

if(isset($_REQUEST['start']))
	$start = $_REQUEST['start'];
else
	$start = 0;
	


$proCount = $resultSet;
$addrid=isset($_GET['addrid']) ? $_GET['addrid'] : '';
$link = $curFile.'?addrid='.$addrid.'&amp;searchbox='.$searchbox;

require_once('classes/paging.class.php');
//$pagingObj= new Paging;
$pageObj = new Paging( $proCount, $start , $limit);

/* ACTIVATE THE TAB */
$activeTab = 'Contacts';
?>
<!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 Contacts</title>
<link rel="stylesheet" type="text/css" href="includes/css/thickbox.css" />
<link href="includes/css/ajaxfileupload.css" type="text/css" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="includes/css/segnantmailer.css" />
<link rel="stylesheet" href="includes/css/themes/blue/style.css" type="text/css"  media="print, projection, screen" />
<link rel="stylesheet" type="text/css" href="includes/css/paging.css"  />
<link rel="stylesheet" type="text/css" href="includes/css/ui.core.css"  />
<link rel="stylesheet" type="text/css" href="includes/css/ui.theme.css"  />
<link rel="stylesheet" type="text/css" href="includes/css/ui.accordion.css"  />
<script type="text/javascript" src="includes/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="includes/js/jquery.tablesorter.js"></script>
<script type="text/javascript" src="includes/js/thickbox-compressed.js"></script>
<script type="text/javascript" src="includes/js/ajaxfileupload.js"></script>
<script type="text/javascript" src="includes/js/ui.core.js"></script>
<script type="text/javascript" src="includes/js/ui.accordion.js"></script>
<script type="text/javascript" src="includes/js/common.jquery.js"></script>
<script type="text/javascript" src="includes/js/contacts.jquery.js"></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"><?php 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 colspan="2" class="heading" height="50">Manage Contacts</td>
        </tr>
      <tr>
        <td colspan="2" bgcolor="#eaeaea" style="padding:10px;">
        <table cellspacing="0" cellpadding="0" class="tabtable" >
<tr>
<?php
$file = basename($_SERVER['PHP_SELF']);

## ADD EXCEPTIONS

$tabArray = array("<td nowrap=\"nowrap\" style=\"cursor:pointer;\" onclick=\"javascript:window.location.href='addressbook.php'\"> Address Books </td>",
		"<td nowrap=\"nowrap\" style=\"cursor:pointer;\" onclick=\"javascript:window.location.href='contacts.php'\"> Contacts </td>");
foreach ($tabArray as $key => $val)
{
	$strpos = strpos($val, $file);

	if ($strpos > 0)
	{
		$newString = str_replace('style="cursor:pointer;"','style="cursor:pointer;" class="active" ',$val);
		echo $newString;
	}
	else
	{
		echo $val;
	}	
}
?>
</tr>
</table>
        <table width="100%" border="0" cellspacing="0" cellpadding="4">
                <tr>
                  <td height="405" bgcolor="#FFFFFF" valign="top"><table width="100%" border="0" cellspacing="1" cellpadding="1">
                      <tr>
                        <td class="pageHeading">Manage Contacts</td>
                      </tr>
                      <tr>
                        <td height="55" valign="top" align="right"><form name="formsearch" method="get" style="margin: 0;" action="">
                            <table border="0" cellspacing="2" cellpadding="2" align="right">
                              <tr>
                                <td><strong>Choose address book</strong></td>
                                <td><select name="addrid" class="textbox" onchange="reloadContacts(this.value)">
                                <option value="0">All Address books</option>
                                <?php
								if (empty($_GET['addrid']))
									$_GET['addrid'] = $_GET['defaddrid'];
									
                                foreach ($addrBookDropdownResultSet as $row)
								{
									$defaultOption = ($_GET['addrid'] == $row['ID']) ? 'selected="selected"' : '';
									echo "<option value='{$row["ID"]}' $defaultOption>{$row['NAME']}</option>\n";
								}
								?>
                        		</select></td>
                                <td width="50">&nbsp;</td>
                                <td nowrap="nowrap"><strong>Search</strong></td>
                                <td><input type="text" name="searchbox" placeholder="search" class="textbox" value="<?=$funcObj->RemoveSlashes($searchbox)?>" style="margin-bottom: 2px;" size="20" /></td>
                                <td><input type="submit" name="submit" value="Search" class="button size2" /></td>
                              </tr>
                            </table>
                          </form></td>
                      </tr>
                      <?php if (!empty($message))
					  echo "
                      <tr>
                        <td class='message'>$message</td>
                      </tr>
					  ";
					  ?>
                      <tr>
                        <td><form name="frmListing" id="frmListing" method="post" style="margin:0; padding: 0" action=""><table cellspacing="1" class="tablesorter">
                        <thead>
                            <tr>
                              <th width="30" align="center"><input type="checkbox" name="chkAll" id="chkAll" onclick="checkAll()" value="1" /></th>
                              <th align="left">Email</th>
                              <th width="15%" align="left">First name</th>
                              <th width="15%" align="left">Last name</th>
                              <th width="100" align="center">Modified</th>
                              <th width="100" align="center">Action</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php
							$addrid =isset($_GET['addrid']) ? $_GET['addrid']:'';
							$qry = "SELECT count(*) FROM smlr_contacts WHERE ADDR_ID = '$addrid'";
							$searchctr='';
							if(!empty($searchTxt))
							{
								$searchctr = " AND (";
								$searchArray1=explode(",",$searchArray);
								
								$searchctr.= "ID = '$searchTxt' OR EMAIL like '%$searchTxt%' 
								OR FIRSTNAME like '%$searchTxt%' 
								OR LASTNAME like '%$searchTxt%' 
								OR MISC_1 like '%$searchTxt%' 
								OR MISC_2 like '%$searchTxt%' 
								OR MISC_3 like '%$searchTxt%' 
								OR LAST_UPDATED LIKE '%$searchTxt%'"; 
								$searchctr .= ") ";
							}
						
							$query = "SELECT ID, EMAIL, FIRSTNAME, LASTNAME, IS_USED, IS_DELETED, LAST_UPDATED FROM
							smlr_contacts $activeAddrBook $searchctr ORDER BY EMAIL ASC
							LIMIT {$pageObj->start}, {$pageObj->limit}";
					$resultSet = $funcObj->CustomQuery($query);
					$i=1;
					if(count($resultSet)!=0)
					{
						
					foreach ($resultSet as $row)
					{
						$delClass = '';
						if ($row['IS_DELETED'] == 1)
							$delClass = 'delete';
						
						echo "<tr>";
						echo "
						<td align='center'><input type='checkbox' name='chkContacts[]' value='{$row["ID"]}' /></td>
						<td align='left' class='$delClass'>";
						echo $row['EMAIL']; 
						echo "</td>
						<td align='left' class='$delClass'>{$row['FIRSTNAME']}&nbsp;</td>
						<td align='left' class='$delClass'>{$row['LASTNAME']}&nbsp;</td>
						<td align='center' class='$delClass'>". date("M j, Y", strtotime($row['LAST_UPDATED'])) . "</td>
						<td align='center' nowrap='nowrap'>
						<a href='".$curFile."?action=edit&amp;addrid={addrid}&amp;id={$row['ID']}&amp;searchbox={$getsearchbox}'><img src='images/edit.gif' alt='Edit' title='Edit' border='0' /></a>&nbsp;&nbsp;&nbsp;";
						echo "<a href='javascript:confirmAction(\"Are you sure you want to delete this record?\",\"{$curFile}?addrid={$addrid}&amp;searchbox={$getsearchbox}&amp;action=del&amp;id={$row['ID']}&amp;used={$row['IS_USED']}\")'><img src='images/delete.gif' alt='Delete' title='Delete' border='0' /></a>";
						echo "&nbsp;</td></tr>
						";
						}
					}
					else
					{
						echo "<tr><td colspan='6' align='center' height='30' valign='middle' class='row0'>No Record Found... </td></tr>";
					}
					?>
                          </tbody>
                          <tfoot style="background-color: #ffffff; border-color: #ffffff;">
                         <?php
						if (count($resultSet))
						{
							echo "<tr style='background-color: #ffffff; border-color: #ffffff;'>
							<td colspan='6' align='left' style='padding-left:10px; height: 30px;' valign='top'><img src='images/selarrow.gif' alt='' border='0' /> <a href='javascript:;' onclick='return seldelete()'>Un-subscribe selected records</a> | <a href='javascript:;' onclick='return selundelete()'>Subscribe selected records</a></td> 
							</tr>";
						}
						 ?> 
                          </tfoot>
                          </table>
                          <input type="hidden" name="delOrUndel" value="del" />
                          <input type="hidden" name="formtype" value="multipledelete" />
                          </form></td>
                      </tr>
                      <tr>
                        <td class="pagingTD"><table cellspacing='0' cellpadding='0'  width='100%'>
                            <tr>
                              <td height='35' style="text-align:left" class="form_base_header"><span class="pagenav">
                                <?=$pageObj->ShowPageInfo()?>
                                </span></td>
                              <td style="text-align:right" class="form_base_header"><span class="pagenav">
                                <?=$pageObj->Show($link)?>
                                </span></td>
                            </tr>
                          </table></td>
                      </tr>
                      <tr>
                      <td>&nbsp; <small><strong>Note:</strong> Contact(s) can only be deleted if that contact has never been used in any campaign. Otherwise, the selected contact will be marked as un-subscribed.</small></td>
                      </tr>
                    </table></td>
                  <td valign="top" align="left" width="240">                  
                  <div id="accordion">
                    <h3><a href="#">Manual Add</a></h3>
                    <div style="padding: 3px;">
                        <form name="formcontacts" method="post" action="contacts.php?addrid=<?=$_GET['addrid']?>&amp;searchbox=<?=$getsearchbox?>" style="margin: 0; padding: 0">
                  <table width="100%" border="0" cellspacing="1" cellpadding="1">
				  <?php if(!empty($errorMsg)){?>
                      <tr>
                        <td height="25" valign="top" <?= (! empty ($errorMsg)) ? 'class="error"' : '' ?>><?php
				   errorMessage($errorMsg);
				   ?></td>
                      </tr>
				  <?php } ?>
                      <tr>
                        <td class="inputlabel">Choose Address Book *</td>
                      </tr>
                      <tr>
                        <td height="65"><select name="addrid" class="textbox">
                                <?php
								/**
                                 * If the form is not in edit mode then the dropdown
                                 * should show the default selected option same as the 
                                 * currently selected addressbook. 
                                 * @var $ADDR_ID public
                                 * 
                                 */
                                
								if (empty($ADDR_ID))
									$ADDR_ID = intval($_GET['addrid']);
									
                                foreach ($addrBookDropdownResultSet as $row)
								{
									$defaultOption = ($ADDR_ID == $row["ID"]) ? 'selected="selected"' : '';
									echo "<option value='{$row["ID"]}' $defaultOption>";
									echo left($row["NAME"],23);
									echo "</option>\n";
								}
								?>
                        		</select>
                        <br />
                        <small>Choose the address book you want to add contact into.</small>
                        
                        </td>
                      </tr>
                      <tr>
                        <td class="inputlabel">Email *</td>
                      </tr>
                      <tr>
                        <td><input type="text" name="txtemail" class="textbox" value="<?=$funcObj->RemoveSlashes($EMAIL)?>" maxlength="50" size="25" /></td>
                      </tr>
                      <tr>
                        <td class="inputlabel">First name</td>
                      </tr>
                      <tr>
                        <td><input type="text" name="txtfname" class="textbox" value="<?=$funcObj->RemoveSlashes($FIRSTNAME)?>" maxlength="35" size="25" /></td>
                      </tr>
                      <tr>
                        <td class="inputlabel">Last name</td>
                      </tr>
                      <tr>
                        <td><input type="text" name="txtlname" class="textbox" value="<?=$funcObj->RemoveSlashes($LASTNAME)?>" size="25" maxlength="25" /></td>
                      </tr>
                      <tr>
                        <td><input type="checkbox" name="chkShowCustom" id="chkShowCustom" onclick="showHideCustomFields(this)" value="1" /> Show custom fields <small><a href="#TB_inline?height=150&amp;width=450&amp;inlineId=customFieldContents" class="thickbox orange">What's this?</a></small></td>
                      </tr>
						<tr class="hideit">
                        <td class="inputlabel">Custom Field 1</td>
                      </tr>
                      <tr class="hideit">
                        <td><input type="text" name="txtcustom1" class="textbox" value="<?=$funcObj->RemoveSlashes($MISC_1)?>" size="25" maxlength="50" /></td>
                      </tr>
						<tr class="hideit">
                        <td class="inputlabel">Custom Field 2</td>
                      </tr>
                      <tr class="hideit">
                        <td><input type="text" name="txtcustom2" class="textbox" value="<?=$funcObj->RemoveSlashes($MISC_2)?>" size="25" maxlength="50" /></td>
                      </tr>
						<tr class="hideit">
                        <td class="inputlabel">Custom Field 3</td>
                      </tr>
                      <tr class="hideit">
                        <td><input type="text" name="txtcustom3" class="textbox" value="<?=$funcObj->RemoveSlashes($MISC_3)?>" size="25" maxlength="50" /></td>
                      </tr>
                      <tr class="hideit">
                        <td><input type="checkbox" name="chkunsubscribe" value="1" <?php echo ($funcObj->RemoveSlashes($IS_DELETED) == '1') ? 'checked="checked"' : '' ?> /> Un-subscribe</td>
                      </tr>
                      <tr>
                        <td height="35"><input type="submit" name="submit" value="Save" class="button size1" /></td>
                      </tr>
                      <tr>
                        <td height="45"><small>Fields marked with * are mandatory.</small></td>
                      </tr>
                    </table>
                    <input type="hidden" name="ID" value="<?php echo isset($_GET['id']) ? $_GET['id'] :'' ?>" />
                    <input type="hidden" name="formtype" value="custom" />
                    <input type="hidden" name="formaction" value="<?php echo $ACTION?>" />
                    
                    </form>
                    </div>
                    <h3><a href="#">Bulk Import</a></h3>
                   <div style="padding: 3px;">
                        <form name="form" action="" method="post" enctype="multipart/form-data" style="margin: 0; padding: 0">
                  <table width="100%" border="0" cellspacing="1" cellpadding="1">
				  <?php if(!empty($errorMsg)){?>
                      <tr>
                        <td height="25" valign="top" <?= (! empty ($errorMsg)) ? 'class="error"' : '' ?>><?php
				   errorMessage($errorMsg);
				   ?></td>
                      </tr>
				  <?php } ?>
                        <td height="45">See <a href="#TB_inline?height=250&amp;width=450&amp;inlineId=hiddenContent" class="thickbox orange">import file instructions</a></td>
                      </tr>

                      <tr>
                        <td class="inputlabel">Choose Address Book *</td>
                      </tr>
                      <tr>
                        <td height="65"><select name="addridImport" id="addridImport" class="textbox">
                                <?php
                                /**
                                 * If the form is not in edit mode then the dropdown
                                 * should show the default selected option same as the 
                                 * currently selected addressbook. 
                                 * @var $ADDR_ID public
                                 * 
                                 */
                                
								if (empty($ADDR_ID))
									$ADDR_ID = intval($_GET['addrid']);
                                
									foreach ($addrBookDropdownResultSet as $row)
									{
										$defaultOption = ($ADDR_ID == $row["ID"]) ? 'selected="selected"' : '';
										echo "<option value='{$row["ID"]}' $defaultOption>";
										echo left($row['NAME'],23);
										echo "</option>\n";
									}
								?>
                        		</select>
                        <br />
                        <small>Choose the address book you want to import contacts into.</small>                        </td>
                      </tr>
                      <tr>
                        <td class="inputlabel">Import *</td>
                      </tr>
                      <tr>
                        <td><br />
                        <small>Use CSV file</small>
                          <input id="fileToUpload" type="file" name="fileToUpload" class="textbox" size="15" /></td>
                      </tr>
                      <tr>
                        <td height="35"><input type="button" id="buttonUpload" name="buttonUpload" value="Import" class="button size1" onclick="return ajaxFileUpload();" /> <img id="loading" src="images/ajax-loader2.gif" style="display:none;" alt=""> <span id="ajaxpreloader" class="bold size14"></span></td>
                      </tr>
                      <tr>
                        <td height="45"><small>Fields marked with * are mandatory.</small></td>
                      </tr>
                    </table>
                    <input type="hidden" name="formtype" value="import" />
                    </form>
                    </div>
                    <h3><a href="#">Export</a></h3>
                    <form name="frmExport" action="doexport.php" method="post" onsubmit="return checkExport()" style="margin: 0; padding: 0">
                    <div style="padding: 3px;">
                        Choose the address book(s) you wish you export:
                        <div style="height: 300px; overflow:scroll">
                        <table width="100%" style="margin-top: 8px;">
                        <?php 
						foreach ($addrBookDropdownResultSet as $row)
						{
							$row_id = $row['ID'];
							$row_name = $row['NAME'];
							
                        	echo "<tr><td width='20' align='left'><input type='checkbox' name='chkExport[]' value='{$row_id}' /></td><td title=\"$row_name\">";
							echo left($row_name,23);
							echo "</td></tr>";
                        }
						?>
                        </table>
                        </div>
                    </div>
                    <input type="hidden" name="formtype" value="export" />
                    <input name="btnExport" type="submit" value="Export" class="button" />
                    </form>
                </div>                  
                    </td>
                </tr>
              </table></td>
      </tr>
    </table></td>
  </tr>
<?php require_once 'includes/inc.footer.php' ?>
</table>
<div id="hiddenContent" style="display:none">
<p class="size16 bold orange">Import File Format:</p>
<p>The system only accepts a valid CSV (comma separated file). If you have an Excel file please save this file as CSV file before importing the file into the system.</p>
<p>Email address is the only mandatory column required in the CSV file. Please make sure that the CSV file has a header row (First row with column headings). Following column headings are valid (No other column heading will be accepted):</p>
<p>EMAIL<br />
  FIRSTNAME<br />
  LASTNAME<br />
  MISC_1<br />
  MISC_2<br />
  MISC_3</p>
<p>These columns can be used later for mapping in the newsletter. If you like to personalize the newsletter/email these mappings will greatly help you.</p>
<p>For more details please <a href="uploads/import.csv" class="orange">download a sample CSV import file</a>.</p>
</div>
<div id="customFieldContents" style="display:none">
<p class="size16 bold orange">What are custom fields?</p>
<p>
You can use these custom fields to store any kind of information like Phone Number, Fax Number, Address, City, State, Zip etc. You can use this information in the emails to personalize them. This information can be used with the help of <em><strong>Personalize Markers</strong></em>. For more information please visit the campaigns section.</p>
<p class="size16 bold orange">What is un-subscribe checkbox for?</p>
<p>
If the un-subscribe checkbox is checked then that contact will be treated as un-subscribed. Meaning, that contact will not receive newsletters when sent in future using that address book. You can even subscribe back the user by un-checking this checkbox.<br/><br/>
Contacts marked as un-subscribed will not be exported using the export option.
</p>
</div>
</body>
</html>