<?php
/*=======================================================================
 *
 * email_send.php
 *
 * Autor: Marc Vollmann
 *
 =======================================================================*/

include_once ("../include/mcglobal.inc.php");
include_once ("../include/auth.inc.php");


// Check HTTP-Parameters
getSecHttpVars("1",array("f_act", "f_attachment", "f_email", "f_email_cc", "f_email_bcc", "f_email_sendToCcAndBcc", 
                         "f_mimetype", "f_charset", "f_subject", 
                         "f_fileName", "f_extension", "f_content", "f_contentFileName", "f_contentFileExtension", 
                         "f_salutationText", "f_hq_id", "f_group", "f_allCustomers", "f_branch", "statusMessage", "f_closeWin", 
                         "chunkSize"));

$deactivateMenuStatic = "1";
$pageTitel = getLngt("Email-Adressatenauswahl!");

getLanguage(__FILE__);

include_once ("../admin/menu.php");
include_once ("../include/html.inc.php");
include_once ("../include/inc_group.inc.php");
include_once ("../include/email/htmlMimeMail.php");

getCurrentScript(__FILE__);

// Check for authentication access and granted rights
$usrAccessArray["hq"] = "1";
authCheckForAccess($hq_id, $usr_id, $emp_id, "1", $customerId, $cscIdRoot, $cscIdActual);

// Execution-Time for script
set_time_limit(0);

$constGlobalDbInstNo = getParameterValue("0", "GLOBAL_UNIQUE_DB_INSTANCE_NO", "0", "0");

// Disable DSGVO filter by parameter
$dsgvoClause = " AND cmp.cmp_dsgvo = '1' ";
$dsgvoState = getParameterValue("0", "MAIL_NEWSLETTER_DSGVO_DISABLED", $hq_id);
if ($dsgvoState == "1") :
   $dsgvoClause = " ";
endif;

// Because of individual contents (e.g. customer hash for newsletter) there has to be only one mail for each mailaddress
if ($chunkSize == "" || !is_numeric($chunkSize)) :
   $chunkSize = getParameterValue("0", "MAIL_ADDRESS_CHUNKSIZE", "0");
   if ($chunkSize == "" || !is_numeric($chunkSize)) :
      $chunkSize = 3;
   endif;
endif;

if ($f_group == "") : $f_group = array(); endif;
$f_groupLen = count($f_group);

// Mandator filter
if ($f_hq_id == "") : $f_hq_id = array(); endif;
if (count($f_hq_id) == 0) : array_push($f_hq_id, $hq_id); endif;

// Current timestamp for ALL mails sent by this process
$currentTime = getDateTime("0");
$currentDate = getDateTime("3");

// Charset
if ($f_charset == "") : 
   $mailCharset = getParameterValue("0", "MAIL_CHARSET", "0");
   if ($mailCharset != "") :
      $f_charset = "; charset=" . $mailCharset;
   else :
      $f_charset = "; charset=ISO 8859-1";
   endif;
else :
   $f_charset = "; charset=" . $f_charset;
endif;

// Trim mail adresses
$f_email = trim($f_email);
$f_email_cc = trim($f_email_cc);
$f_email_bcc = trim($f_email_bcc);

// Flag for sending to Cc and Bcc mail addresses for every generated mail (e.g. newsletter to (all) customers)
if ($f_email_sendToCcAndBcc == "" || count($f_email_sendToCcAndBcc) == 0) :
   $f_email_sendToCcAndBcc = "0";
else: 
   $f_email_sendToCcAndBcc = "1";
endif;

// Init with special email addresses (important !!!)
$f_emailAddresses = array();
if ($f_email != "") : $f_emailAddresses[] = $f_email; endif;


// Check for selection of all customers
$whereClauseAllCs = "";
if ($f_allCustomers == "") : 
   $f_allCustomers = array();
endif;

// Check access to send mail to (all) customers, groups or member of branches
if (authCheckEmployeeRights($emp_id, "20")) :

   // "All customers" or "groups"
   $f_allCustomersLen = count($f_allCustomers);
   if ($f_allCustomersLen > 0) :

      for ($i = 0; $i < $f_allCustomersLen; $i++) :
          $whereClauseCs .= " cmp.cmp_type = '" . $f_allCustomers[$i] . "' ";
          if ($i < ($f_allCustomersLen - 1)) : $whereClauseCs .= " OR "; endif;
      endfor;
      $whereClauseCs = "(" . $whereClauseCs . ") AND ";

      // Filter branch
      $whereClauseBr = "";      
      $f_branch_len = 0;
      if (is_array($f_branch)) : $f_branch_len = count($f_branch); endif;
      if ($f_branch_len > 0) :
         // $whereClauseBr = " cmp.br_id = '" . $f_branch . "' AND ";
         $whereClauseBr = " cmp.br_id IN ('" . implode("','", $f_branch) . "') AND ";
      endif;      

      if ($f_hq_id != "" && count($f_hq_id) >= 1) : 
         $whereClauseCs .= " cs.hq_id IN " . getSQLMandatorArray($f_hq_id) . " AND ";
      else :
         $whereClauseCs .= " cs.hq_id = '" . $hq_id . "' AND ";
      endif;
      $sqlquery1 = "SELECT usr.usr_email AS email, cs.cs_id"
                      . " FROM customer AS cs, company AS cmp, employee AS emp, user AS usr"
                      . " WHERE " . $whereClauseCs . $whereClauseBr . " cs.cmp_id = cmp.cmp_id AND cs.cs_jbstatusmail2csc = '0' AND cmp.cmp_newsletter = '1' " . $dsgvoClause . " AND"
                      . "       cs.cs_admin = emp.emp_id AND emp.usr_id = usr.usr_id AND usr.usr_email != ''";

      $sqlquery2 = "SELECT cscad.cscad_email AS email, cs.cs_id"
                      . " FROM customer AS cs, company AS cmp, costcenter AS csc, costcenteraddress AS cscad"
                      . " WHERE " . $whereClauseCs . $whereClauseBr . " cs.cmp_id = cmp.cmp_id AND cs.cs_jbstatusmail2csc = '1' AND cmp.cmp_newsletter = '1' " . $dsgvoClause . " AND"
                      . "       csc.cs_id = cs.cs_id AND csc.csc_id = cscad.csc_id AND cscad.adt_id = '2' AND cscad.cscad_email != ''";

      $result = $db->query("(" . $sqlquery1 . ") UNION (" . $sqlquery2 . ")");
      if (DB::isError($result)) die ("$PHP_SELF: " . $result->getMessage());
      $count = 0;
      while ($row = $result->fetch_assoc()):
            $f_emailAddresses[$count] = $row["email"];
            $f_Ids[$count] = $row["cs_id"];
            $f_Type[$count] = "cs";
            $count++;
      endwhile;
      $result->free();

   else :

      // Check for selected groups
      if ($f_groupLen > 0) :
         $tmpEmailaddresses = getGroupMemberEmailaddresses($f_group, "cs", $f_hq_id, "cmp.cmp_newsletter = '1'" . $dsgvoClause);
         $tmpEmailaddresses1 = $tmpEmailaddresses[0];
         $tmpIds1 = $tmpEmailaddresses[1];
         $tmpType1 = $tmpEmailaddresses[2];
         
         $tmpEmailaddresses = getGroupMemberEmailaddresses($f_group, "cr", $f_hq_id, "cmp.cmp_newsletter = '1'" . $dsgvoClause);
         $tmpEmailaddresses2 = $tmpEmailaddresses[0];
         $tmpIds2 = $tmpEmailaddresses[1];
         $tmpType2 = $tmpEmailaddresses[2];
         
         $tmpEmailaddresses = getGroupMemberEmailaddresses($f_group, "emp", $f_hq_id, "cmp.cmp_newsletter = '1'" . $dsgvoClause);
         $tmpEmailaddresses3 = $tmpEmailaddresses[0];
         $tmpIds3 = $tmpEmailaddresses[1];
         $tmpType3 = $tmpEmailaddresses[2];
      
         // Merge all arrays
         $tmpEmailaddresses1Len = count($tmpEmailaddresses1);
         $tmpEmailaddresses2Len = count($tmpEmailaddresses2);
         for ($m = 0; $m < $tmpEmailaddresses2Len; $m++) :
             $tmpEmailaddresses1[($tmpEmailaddresses1Len + $m)] = $tmpEmailaddresses2[$m];
             $tmpIds1[($tmpEmailaddresses1Len + $m)] = $tmpIds2[$m];
             $tmpType1[($tmpEmailaddresses1Len + $m)] = $tmpType2[$m];
         endfor;
         $tmpEmailaddresses1Len = count($tmpEmailaddresses1);
         $tmpEmailaddresses3Len = count($tmpEmailaddresses3);
         for ($m = 0; $m < $tmpEmailaddresses3Len; $m++) :
             $tmpEmailaddresses1[($tmpEmailaddresses1Len + $m)] = $tmpEmailaddresses3[$m];
             $tmpIds1[($tmpEmailaddresses1Len + $m)] = $tmpIds3[$m];
             $tmpType1[($tmpEmailaddresses1Len + $m)] = $tmpType3[$m];
         endfor;

         $f_emailAddresses = $tmpEmailaddresses1; $tmpEmailaddresses1 = ""; $tmpEmailaddresses2 = ""; $tmpEmailaddresses3 = "";
         $f_Ids = $tmpIds1; $tmpIds1 = ""; $tmpIds2 = ""; $tmpIds3 = "";
         $f_Type = $tmpType1; $tmpType1 = ""; $tmpType2 = ""; $tmpType3 = "";

         // $f_emailAddresses = array_merge($f_emailAddresses, getGroupMemberEmailaddresses($f_group, "cs", $f_hq_id, "cmp.cmp_newsletter = '1'" . $dsgvoClause));
         // $f_emailAddresses = array_merge($f_emailAddresses, getGroupMemberEmailaddresses($f_group, "cr", $f_hq_id, "cmp.cmp_newsletter = '1'" . $dsgvoClause));
         // $f_emailAddresses = array_merge($f_emailAddresses, getGroupMemberEmailaddresses($f_group, "emp", $f_hq_id, "cmp.cmp_newsletter = '1'" . $dsgvoClause));
      endif;
   endif;
endif;

$f_emailAddressesLen = count($f_emailAddresses);


// ********************************************************
// * Prepare to send the mail and check all preconditions *
// ********************************************************

$mailSenderAddress = getParameterValue("0", "MAIL_NEWSLETTER_SENDER_ADDRESS", $hq_id);
if ($mailSenderAddress == "") :
   $mailSenderAddress = getParameterValue("0", "MAIL_SENDER_ADDRESS", $hq_id);
endif;
$statusMessage = getLngt("Es wurde keine Nachricht versendet!");

if ($f_attachment == "" && $f_content == "") :
   $statusMessage = getLngt("Entweder fehlt der Mailtext oder ein Anhang!");
elseif ($f_emailAddressesLen == 0) :
   $statusMessage = getLngt("Selektieren Sie bitte die Mailadressen oder tragen Sie bitte mindestens eine Mailadresse ein! Manuelle Adresseinträge werden durch Kommata getrennt!");
elseif ($f_subject == "") :
   $statusMessage = getLngt("Bitte tragen Sie in der Betreffzeile etwas ein!");
elseif ($f_mimetype == "") :
   $statusMessage = getLngt("Der Mimetype fehlt!");
elseif ($f_fileName == "" && $f_attachment != "") :
   $statusMessage = getLngt("Der Dateiname für den Anhang fehlt!");
elseif ($f_extension == "" && $f_attachment != "") :
   $statusMessage = getLngt("Der Dateityp für den Anhang fehlt (Extension)!");
elseif ($f_contentFileName == "" && $f_content == "_file_") :
   $statusMessage = getLngt("Der Dateiname zum Laden des Mailtextes fehlt!");
elseif ($f_contentFileExtension == "" && $f_content == "_file_") :
   $statusMessage = getLngt("Der Dateityp zum Laden des Mailtextes fehlt (Extension)!");
elseif ($mailSenderAddress == "") :
   $statusMessage = getLngt("Die Absenderadresse ist nicht definiert!");
else :
   if ($f_act == "mailsend") :

      $mailtext = "";
      if ($f_content != "") :

         if ($f_content == "_file_") :

            $tmpFile = "../temp/download/" . $f_contentFileName . "." . $f_contentFileExtension;
            if (file_exists($tmpFile)) :

               $mailtext = file_get_contents($tmpFile);
            endif;
         else :
            $mailtext = $f_content;
         endif;            

      else :
         $mailtext .= "<html><head><meta text/html>";
         $mailtext .= "<style type=\"text/css\">";
         $mailtext .= ".f8np1 { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: normal; padding: 1px}";
         $mailtext .= ".f8bp1 { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: bold; padding: 1px}";
         $mailtext .= ".f8np1_red { font-family: Verdana, Arial, Helvetica, sans-serif; font-size: 8pt; font-weight: normal; padding: 1px; color: #FF0000;}";
         $mailtext .= "</style>";
         $mailtext .= "</head><body><h4>";

         if ($f_salutationText == "") : 
            $f_salutationText  = "<div class=\"f8bp1\">" . getLngt("Sehr geehrte Damen und Herren,") . "</div><br>";
            $f_salutationText .= "<div class=\"f8bp1\">" . getLngt("hiermit übersenden wir Ihnen die folgenden Informationen.") . "</div><br>";
            $f_salutationText .= "<div class=\"f8bp1\">" . getLngt("Mit freundlichem Gruß,") . "</div>";
         endif;

         $mailtext .= $f_salutationText;

         /*
         $mailSalutationText = getParameterValue("0", "MAIL_SALUTATION_TEXT", $currentHqId);
         $mailtext .= "<div class=\"f8bp1\">" . getLngt($mailSalutationText) . "</div><br>";
         */
         
         // LOGO
         /*
         $logoName = getParameterValue("0", "IMG_LOGO_NAME", $currentHqId);
         $logoHeight = getParameterValue("0", "IMG_LOGO_HEIGHT", $currentHqId);
         $logoWidth = getParameterValue("0", "IMG_LOGO_WIDTH", $currentHqId);
         if ($logoName != "" && $logoHeight != "" && $logoWidth != "") :
            $mailtext .= "<br><div><img src=\"../images/external/" . $logoName . "\" border=\"0\" height=\"" . $logoHeight . "\" width=\"" . $logoWidth . "\"></div><br><br>";
         endif;
         */
         
         /*
         $mailFooterEnabled = getParameterValue("0", "MAIL_FOOTER_ENABLED", $currentHqId);
         if ($mailFooterEnabled == "1") :
            $mailFooterAddress = getParameterValue("0", "MAIL_FOOTER_ADDRESS", $currentHqId);
            if ($mailFooterAddress != "") :
               $mailtext .= $mailFooterAddress;
            endif;
            $mailFooterContact = getParameterValue("0", "MAIL_FOOTER_CONTACT", $currentHqId);
            if ($mailFooterContact != "") :
               $mailtext .= $mailFooterContact;
            endif;
            $mailFooterImpressum = getParameterValue("0", "MAIL_FOOTER_IMPRESSUM", $currentHqId);
            if ($mailFooterImpressum != "") :
               $mailtext .= $mailFooterImpressum;
            endif;
            $mailFooterThinkGreen = getParameterValue("0", "MAIL_FOOTER_THINK_GREEN", $currentHqId);
            if ($mailFooterThinkGreen != "") :
               $mailtext .= $mailFooterThinkGreen;
            endif;
         endif;
         */
         $mailtext .= "</body></html>";
      endif;

      // Remove old attachement
      if ($f_extension != "" && substr($f_extension,0,1) != ".") :
         foreach (glob("../temp/download/*." . $f_extension) as $fileNameToBeRemoved) {
             if ((time() - filemtime($fileNameToBeRemoved)) > 60) :
                if (file_exists($fileNameToBeRemoved)) :
                   unlink($fileNameToBeRemoved);
                endif;
             endif;
         }
      endif;

      $f_secretFileName = "";
      if ($f_fileName != "" && $f_extension != "") :
         $f_secretFileName = $f_fileName . "." . $f_extension;
         writeToFile("../temp/download/" . $f_secretFileName, $f_attachment);   // write attachement data into file
      endif;

      // Check for post parsing necessity
      $remMailtext = "";
      $postParsing = false;
      if (!(strpos($mailtext, "<postparser>") === FALSE)) :
         $postParsing = true;
         $remMailtext = $mailtext;
         $f_emailChunks = $f_emailAddresses;
      else :
         $f_emailAddresses = array_unique($f_emailAddresses);            // Unique addresses
         $f_emailChunks = array_chunk($f_emailAddresses, $chunkSize);    // Chunk addresses
      endif;

      // Loop if too much addresses
      $logMailAddressArray = array();
      $f_emailChunksLen = count($f_emailChunks);

      for ($i = 0; $i < $f_emailChunksLen; $i++) :

          if ($postParsing) :
             $mailtext = postParseMailtext($mailtext, $f_Type[$i], $f_Ids[$i], $constGlobalDbInstNo);
          endif;

          if ($mailtext != "ERR") :
             $mailObj = new htmlMimeMail();
	           
             $mailObj->setHtml($mailtext, null, "./");
             // $mailObj->setHtml($mailtext);
             // Set From address
             $mailObj->setFrom($mailSenderAddress);
             
             // Set Cc address
             /*
               $mailCcAddress = getParameterValue("0", "MAIL_CC_ADDRESS", $currentHqId);
               if ($mailCcAddress == "" || !checkEmailFormat($mailCcAddress)) :
                   $mailCcAddress = MAIL_CC_ADDRESS;
               endif;                        
               if ($mailCcAddress != "" && checkEmailFormat($mailCcAddress)) :
                  $mailObj->setCc($mailCcAddress);
               endif;
             */
             // Add Cc addresses
             if ($f_email_cc != "" && $f_email_sendToCcAndBcc == "1") :
                $mailObj->setCc($f_email_cc);
             endif;
             
             // Subject of the mail
             $mailObj->setSubject(getLngt($f_subject));

             if ($f_secretFileName != "") :
                if (file_exists("../temp/download/" . $f_secretFileName)) :
                   $attachment = $mailObj->getFile("../temp/download/" . $f_secretFileName);
                   $mailObj->addAttachment($attachment, $f_secretFileName, $f_mimetype . $f_charset);
                endif;
             endif;

             // Log (only for output)
             if (count($logMailAddressArray) > 0) : $logMailAddressArray = array_merge($logMailAddressArray, array("-------")); endif;
             
             // Set all addresses
             if ($postParsing) :
                // Log: $f_emailChunks[$i] IS NOT an array
                $logMailAddressArray = array_merge($logMailAddressArray, array("[" . $i . ".] " . $f_emailChunks[$i]));
             
                // Add Bcc addresses
                if ($f_email_bcc != "" && $f_email_sendToCcAndBcc == "1") :
                   $mailObj->setBcc($f_email_bcc);
                endif;
             
                $f_emailString = $f_emailChunks[$i];
                $mailReceiverAddress = $f_emailString;
             else :
                // Log: $f_emailChunks[$i] IS an array
                $logMailAddressArray = array_merge($logMailAddressArray, array("[" . $i . ".]"), $f_emailChunks[$i]);  // Log
             
                $f_emailString = implode(",", $f_emailChunks[$i]);
                
                // Add Bcc addresses
                if ($f_email_bcc != "" && $f_email_sendToCcAndBcc == "1") :
                   $f_emailString .= "," . $f_email_bcc;
                endif;
                
                $f_emailString = str_replace(",,", ',', $f_emailString);
                if (substr($f_emailString, 0, 1) == ",") : $f_emailString = substr($f_emailString, 1); endif;
                if (substr($f_emailString, -1) == ",") : $f_emailString = substr($f_emailString, 0, strlen($f_emailString) - 1); endif;
             
                // Only send to Bcc if chunks are ok. The receiver address is the same as the sender address!
                $mailObj->setBcc($f_emailString);
                $mailReceiverAddress = $mailSenderAddress;
             endif;

             // Check existence in log
             $mailResult = false;
             $sentToReceiverSameDay = "";
             if ($f_emailChunksLen > 3) :
                $sentToReceiverSameDay = getOneStmt("SELECT log_createtime FROM phoenix_log.log WHERE logo_id = '93' AND LEFT(log_createtime,10) = '" . $currentDate . "' AND logo_description = 'SENT=Y|EMAIL=" . $f_emailString . "' LIMIT 0,1", "log_createtime");
             endif;
             if ($sentToReceiverSameDay == "") :
                $mailResult = $mailObj->send(array($mailReceiverAddress), 'smtp');
             endif;

             if ($mailResult) :
                $statusMessage = getLngt("Die Nachricht(en) wurde versandt!");
             
                // Write logdata into log database
                writeToLogDB("93",$hq_id,"",$usr_id,"","",($f_Type[$i] == "cs" ? $f_Ids[$i] : ""),"SENT=Y|EMAIL=" . $f_emailString);
                
                // Generate report entry
                $tmpReportText = getLngt("Newsletterversand erfolgreich");
                insertStmt("phoenix_group.report_process", array("usr_id", $usr_id, "hq_id", $hq_id, "rp_reporttype", "15", "rp_text", $tmpReportText,
                                                                 "rp_createtime", $currentTime, "rp_objId", $f_Ids[$i], "rp_objtype", "cs"));
             else :
                $statusMessage = getLngt("Die Nachricht(en) konnte nicht gesendet werden!");
             
                // Write logdata into log database
                writeToLogDB("93",$hq_id,"",$usr_id,"","",($f_Type[$i] == "cs" ? $f_Ids[$i] : ""),"SENT=N|EMAIL=" . $f_emailString . ($sentToReceiverSameDay != "" ? "|TS=" . $sentToReceiverSameDay : ""));
             endif;

             // $mailObj->free();
             $mailObj = NULL;
          else :
             // Write logdata into log database
             writeToLogDB("93",$hq_id,"",$usr_id,"",($f_Type[$i] == "cs" ? $f_Ids[$i] : ""),$f_Ids[$i],"SENT=N|EMAIL=POSTPARSER_ERR");
          endif;
          
          if ($postParsing) :
             $mailtext = $remMailtext;
          endif;
      endfor;

      // Remove old file(s)
      if ($f_secretFileName != "") :
         foreach (glob("../temp/download/" . $f_secretFileName) as $fileNameToBeRemoved) {
           if (file_exists($fileNameToBeRemoved)) :
              unlink($fileNameToBeRemoved);
           endif;
         }
      endif;

   else :
      $statusMessage = getLngt("Die eingegebene Emailadresse ist syntaktisch nicht korrekt!");
   endif;
endif;

// ONLY for output
if ($f_groupLen > 0) : 
   $onLoadCall .= "groupList('on');";
else :
   $onLoadCall .= "groupList('off');";
endif;
?>

<html>

<head>
<title><?php echo $pageTitel ?></title>

<link rel="stylesheet" type="text/css" href="../css/phoenix.css">
<style type="text/css">
  <?php include_once ("../css/navigation.css.php"); ?>
</style>

<?php include_once ("../include/js_framework.inc.php"); ?>

<script src="../include/checkFormTags.js" type="text/javascript"></script>
<script src="../include/searchLists.js" type="text/javascript"></script>

<script type="text/javascript">
<!--
// NAVIGATION
<?php echo $jsMenuOut; ?>

// Shows/Hides the group list
function groupList(displayState) {
  if (displayState == 'on') {
  	 myshow('groupList');
  	 myhide('groupListReduced');
  };
  if (displayState == 'off') {
  	 myshow('groupListReduced');
  	 myhide('groupList');
  };
}

function parametersUriEncode() {
  document.forms[0].f_attachment.value = encodeURI('<?php echo my_str_check_http($f_attachment) ?>');
  document.forms[0].f_salutationText.value = encodeURI('<?php echo $f_salutationText ?>');
}

function finishEmailSendPage() {
	parametersUriEncode();
  document.forms[0].f_act.value = 'mailsend';
  document.forms[0].submit();
}

function closeWin() {
  var closeWin = '<?php echo $f_closeWin ?>';
  if (closeWin == '1') {
  	 window.close();
  }
}

function changePageSelection () {
	var numOfCmpTypes = 3;
	var cmpTypeIsSelected = false;
	var branchIsSelected = true;
	var elemBranch = document.forms[0].elements["f_branch[]"];
	var numOfBranches = elemBranch.length;
  for(var i=0;i<numOfBranches;++i) {
    if (elemBranch.options[i].selected == true) {
       if (elemBranch.options[i].value == '') {
          for (var j = 0; j <= numOfCmpTypes; j++) {
	            document.getElementsByName('f_allCustomers[]')[j].checked = false;
	            branchIsSelected = false;
	        }
       }
    }
  }
	// Check for any customer type has to be selected
	if (branchIsSelected) {
     for (var j = 0; j <= numOfCmpTypes; j++) {
	       if (document.getElementsByName('f_allCustomers[]')[j].checked == true) {
	       	  cmpTypeIsSelected = true;	           	  
	       }
	   }
	   if (!cmpTypeIsSelected) {
	   	 for(var i=0;i<numOfBranches;++i) {
	   	 	   elemBranch.options[i].selected = false;
	   	 }
	   	 elemBranch.options[0].selected = true;
	   	 alert('<?php echo getLngt("Die Auswahl einer Branche setzt die Auswahl mindestens eines Kundentyps voraus!") ?>');
	   }
	}
}
-->
</script>

</head>

<body class="menu_bgcol" onLoad="displayStatusMessage();closeWin();<?php echo $phpCurrentNavigationOnLoad ?><?php echo $onLoadCall ?>">

<?php echo $phpMenuOut ?>
<?php echo $phpReducedMenuOut ?>
<?php echo $phpPageTitelOut ?>

<div class="maincontent2" name="maincontent" id="maincontent">

<form action="../include/email_send.php" method="post">

  <input type="hidden" name="f_act" value="">
  <input type="hidden" name="f_content" value="<?php echo $f_content ?>">  
  <input type="hidden" name="f_fileName" value="<?php echo $f_fileName ?>">
  <input type="hidden" name="f_extension" value="<?php echo $f_extension ?>">
  <input type="hidden" name="f_contentFileName" value="<?php echo $f_contentFileName ?>">
  <input type="hidden" name="f_contentFileExtension" value="<?php echo $f_contentFileExtension ?>">
  <input type="hidden" name="f_mimetype" value="<?php echo $f_mimetype ?>">
  <input type="hidden" name="f_charset" value="<?php echo $f_charset ?>">
  
  <input type="hidden" name="f_attachment" value="">
  <input type="hidden" name="f_salutationText" value="">

  <?php echo $phpCurrentNavigationInputHidden ?>
  <input type="hidden" name="deactivateMenu" value="<?php echo ec($deactivateMenu) ?>">

  <?php echo htmlDivLineSpacer("10px"); ?>

  <!-- Headquarters checkboxes -->
  <?php if (authCheckEmployeeRights($emp_id, "10")) : ?>
    <?php echo getHeadquartersCheckboxes($f_hq_id, "130px"); ?>
    <?php echo htmlDivLineSpacer("20px", "", "left"); ?>
  <?php endif; ?>

  <div>
    <div <?php echo setStyleHtmlDiv("130px","left"); ?>><b><?php echo getLngt("Betreff") ?>:</b></div>
    <div>
      <input type="text" name="f_subject" value="<?php echo $f_subject ?>" size="125" maxlength="125">
    </div>
  </div>
  <?php echo htmlDivLineSpacer("10px"); ?>

  <div>
    <div <?php echo setStyleHtmlDiv("130px","left"); ?>><b><?php echo getLngt("Mailadresse(n)") ?>:</b></div>
    <div>&nbsp;</div>
  </div>
  <?php echo htmlDivLineSpacer("10px"); ?>
  <div>
    <div <?php echo setStyleHtmlDiv("130px","left"); ?>><?php echo getLngt("An (To)") ?>:</div>
    <div>
      <input type="text" name="f_email" value="<?php echo $f_email ?>" size="125" maxlength="250">
    </div>
  </div>
  <?php echo htmlDivLineSpacer("10px"); ?>
  <div>
    <div <?php echo setStyleHtmlDiv("130px","left"); ?>><?php echo getLngt("Kopie (Cc)") ?>:</div>
    <div>
      <input type="text" name="f_email_cc" value="<?php echo $f_email_cc ?>" size="125" maxlength="250">
    </div>
  </div>
  <?php echo htmlDivLineSpacer("10px"); ?>
  <div>
    <div <?php echo setStyleHtmlDiv("130px","left"); ?>><?php echo getLngt("Blindkopie (Bcc)") ?>:</div>
    <div>
      <input type="text" name="f_email_bcc" value="<?php echo $f_email_bcc ?>" size="125" maxlength="250">
    </div>
  </div>
  <?php echo htmlDivLineSpacer("10px"); ?>
  <div>
    <div <?php echo setStyleHtmlDiv("130px","left"); ?>>&nbsp;</div>
    <div>
    	<input type="checkbox" name="f_email_sendToCcAndBcc[]" value="1"> <?php echo getLngt("Bei jeder generierten Mail Cc und Bcc mit einbeziehen") ?>
    </div>
  </div>
  <?php echo htmlDivLineSpacer("30px"); ?>

  <?php if (authCheckEmployeeRights($emp_id, "20")) : ?>
    <!-- All customers -->
    <div>
       <div><input type="checkbox" name="f_allCustomers[]" value="0"> Alle Kunden</div>
       <div><input type="checkbox" name="f_allCustomers[]" value="1"> Alle Interessenten</div>
       <div><input type="checkbox" name="f_allCustomers[]" value="2"> Alle Potentialkunden</div>
       <div><input type="checkbox" name="f_allCustomers[]" value="3"> Alle Wunschkunden</div>
    </div>
    <?php echo htmlDivLineSpacer("15px"); ?>

    <!-- Branches -->
    <div>
      <div <?php echo $htmlDivFixedWidth; ?>><?php echo getLngt("Einschränkung nach Branchen:") ?></div>
      <div>
        <select name="f_branch[]" onChange="changePageSelection();" multiple="multiple">
          <option value="">---</option>
          <?php echo addOptionsFromTable("phoenix.branch","br_id","br_name","br_name","",$f_branch); ?>
        </select>
      </div>
    </div>
    <?php echo htmlDivLineSpacer("30px", "", "left"); ?>

    <!-- Groups -->
    <div>
      <div <?php echo $htmlDivFixedWidth; ?>>Gruppen:</div>
      <div>
        <div id="groupListReduced" name="groupListReduced">
          <?php echo defineButtonType08("+", "action_lock", "groupList('on');", "10", "left", "3") ?>
        </div>
        <div id="groupList" name="groupList">
          <?php echo defineButtonType08("-", "action_lock", "groupList('off');", "10", "left", "3") ?>
          <div>
            <table border="0">
              <tr>
                <td>
                  <?php echo addCheckboxesFromTable("f_group", "groups", "grp_id", "grp_name", "grp_id", "hq_id =" . $hq_id, $f_group, "</td></tr><tr><td>"); ?>
                </td>
              </tr>
            </table>
          </div>
        </div>
      </div>
    </div>
    <?php echo htmlDivLineSpacer("30px"); ?>

  <?php endif; ?>

  <?php echo defineButtonType08(getLngt("Senden"), "mail_send", "finishEmailSendPage();", "100", "left", "2"); ?>

  <?php echo htmlDivLineSpacer("50px", "", "left"); ?>
  <?php 
    if (count($logMailAddressArray) > 0) :
       echo "<b>" . getLngt("Der Versand erfolgt an folgende Email-Adressen:") . "</b><br><br>";
       echo implode("<br>", $logMailAddressArray);
    endif;
   ?>
</form>
</div>
</body>

</html>