/**
* Send a submit notification to the email address specified in the notifications tab in the survey settings
*/
function sendSubmitNotifications($surveyid)
{
    // @todo: Remove globals
    global $thissurvey, $maildebug, $tokensexist;
    if (trim($thissurvey['adminemail']) == '') {
        return;
    }
    $homeurl = Yii::app()->createAbsoluteUrl('/admin');
    $clang = Yii::app()->lang;
    $sitename = Yii::app()->getConfig("sitename");
    $debug = Yii::app()->getConfig('debug');
    $bIsHTML = $thissurvey['htmlemail'] == 'Y';
    $aReplacementVars = array();
    if ($thissurvey['allowsave'] == "Y" && isset($_SESSION['survey_' . $surveyid]['scid'])) {
        $aReplacementVars['RELOADURL'] = "" . Yii::app()->getController()->createUrl("/survey/index/sid/{$surveyid}/loadall/reload/scid/" . $_SESSION['survey_' . $surveyid]['scid'] . "/loadname/" . urlencode($_SESSION['survey_' . $surveyid]['holdname']) . "/loadpass/" . urlencode($_SESSION['survey_' . $surveyid]['holdpass']) . "/lang/" . urlencode($clang->langcode));
        if ($bIsHTML) {
            $aReplacementVars['RELOADURL'] = "<a href='{$aReplacementVars['RELOADURL']}'>{$aReplacementVars['RELOADURL']}</a>";
        }
    } else {
        $aReplacementVars['RELOADURL'] = '';
    }
    if (!isset($_SESSION['survey_' . $surveyid]['srid'])) {
        $srid = null;
    } else {
        $srid = $_SESSION['survey_' . $surveyid]['srid'];
    }
    $aReplacementVars['ADMINNAME'] = $thissurvey['adminname'];
    $aReplacementVars['ADMINEMAIL'] = $thissurvey['adminemail'];
    $aReplacementVars['VIEWRESPONSEURL'] = Yii::app()->createAbsoluteUrl("/admin/responses/sa/view/surveyid/{$surveyid}/id/{$srid}");
    $aReplacementVars['EDITRESPONSEURL'] = Yii::app()->createAbsoluteUrl("/admin/dataentry/sa/editdata/subaction/edit/surveyid/{$surveyid}/id/{$srid}");
    $aReplacementVars['STATISTICSURL'] = Yii::app()->createAbsoluteUrl("/admin/statistics/sa/index/surveyid/{$surveyid}");
    if ($bIsHTML) {
        $aReplacementVars['VIEWRESPONSEURL'] = "<a href='{$aReplacementVars['VIEWRESPONSEURL']}'>{$aReplacementVars['VIEWRESPONSEURL']}</a>";
        $aReplacementVars['EDITRESPONSEURL'] = "<a href='{$aReplacementVars['EDITRESPONSEURL']}'>{$aReplacementVars['EDITRESPONSEURL']}</a>";
        $aReplacementVars['STATISTICSURL'] = "<a href='{$aReplacementVars['STATISTICSURL']}'>{$aReplacementVars['STATISTICSURL']}</a>";
    }
    $aReplacementVars['ANSWERTABLE'] = '';
    $aEmailResponseTo = array();
    $aEmailNotificationTo = array();
    $sResponseData = "";
    if (!empty($thissurvey['emailnotificationto'])) {
        $aRecipient = explode(";", ReplaceFields($thissurvey['emailnotificationto'], array('ADMINEMAIL' => $thissurvey['adminemail']), true));
        foreach ($aRecipient as $sRecipient) {
            $sRecipient = trim($sRecipient);
            if (validateEmailAddress($sRecipient)) {
                $aEmailNotificationTo[] = $sRecipient;
            }
        }
    }
    if (!empty($thissurvey['emailresponseto'])) {
        // there was no token used so lets remove the token field from insertarray
        if (!isset($_SESSION['survey_' . $surveyid]['token']) && $_SESSION['survey_' . $surveyid]['insertarray'][0] == 'token') {
            unset($_SESSION['survey_' . $surveyid]['insertarray'][0]);
        }
        //Make an array of email addresses to send to
        $aRecipient = explode(";", ReplaceFields($thissurvey['emailresponseto'], array('ADMINEMAIL' => $thissurvey['adminemail']), true));
        foreach ($aRecipient as $sRecipient) {
            $sRecipient = trim($sRecipient);
            if (validateEmailAddress($sRecipient)) {
                $aEmailResponseTo[] = $sRecipient;
            }
        }
        $aFullResponseTable = getFullResponseTable($surveyid, $_SESSION['survey_' . $surveyid]['srid'], $_SESSION['survey_' . $surveyid]['s_lang']);
        $ResultTableHTML = "<table class='printouttable' >\n";
        $ResultTableText = "\n\n";
        $oldgid = 0;
        $oldqid = 0;
        foreach ($aFullResponseTable as $sFieldname => $fname) {
            if (substr($sFieldname, 0, 4) == 'gid_') {
                $ResultTableHTML .= "\t<tr class='printanswersgroup'><td colspan='2'>" . strip_tags($fname[0]) . "</td></tr>\n";
                $ResultTableText .= "\n{$fname[0]}\n\n";
            } elseif (substr($sFieldname, 0, 4) == 'qid_') {
                $ResultTableHTML .= "\t<tr class='printanswersquestionhead'><td  colspan='2'>" . strip_tags($fname[0]) . "</td></tr>\n";
                $ResultTableText .= "\n{$fname[0]}\n";
            } else {
                $ResultTableHTML .= "\t<tr class='printanswersquestion'><td>" . strip_tags("{$fname[0]} {$fname[1]}") . "</td><td class='printanswersanswertext'>" . CHtml::encode($fname[2]) . "</td></tr>\n";
                $ResultTableText .= "     {$fname[0]} {$fname[1]}: {$fname[2]}\n";
            }
        }
        $ResultTableHTML .= "</table>\n";
        $ResultTableText .= "\n\n";
        if ($bIsHTML) {
            $aReplacementVars['ANSWERTABLE'] = $ResultTableHTML;
        } else {
            $aReplacementVars['ANSWERTABLE'] = $ResultTableText;
        }
    }
    $sFrom = $thissurvey['adminname'] . ' <' . $thissurvey['adminemail'] . '>';
    $aAttachments = unserialize($thissurvey['attachments']);
    $aRelevantAttachments = array();
    /*
     * Iterate through attachments and check them for relevance.
     */
    if (isset($aAttachments['admin_notification'])) {
        foreach ($aAttachments['admin_notification'] as $aAttachment) {
            $relevance = $aAttachment['relevance'];
            // If the attachment is relevant it will be added to the mail.
            if (LimeExpressionManager::ProcessRelevance($relevance) && file_exists($aAttachment['url'])) {
                $aRelevantAttachments[] = $aAttachment['url'];
            }
        }
    }
    $redata = compact(array_keys(get_defined_vars()));
    if (count($aEmailNotificationTo) > 0) {
        $sMessage = templatereplace($thissurvey['email_admin_notification'], $aReplacementVars, $redata, 'frontend_helper[1398]', $thissurvey['anonymized'] == "Y", NULL, array(), true);
        $sSubject = templatereplace($thissurvey['email_admin_notification_subj'], $aReplacementVars, $redata, 'frontend_helper[1399]', $thissurvey['anonymized'] == "Y", NULL, array(), true);
        foreach ($aEmailNotificationTo as $sRecipient) {
            if (!SendEmailMessage($sMessage, $sSubject, $sRecipient, $sFrom, $sitename, true, getBounceEmail($surveyid), $aRelevantAttachments)) {
                if ($debug > 0) {
                    echo '<br />Email could not be sent. Reason: ' . $maildebug . '<br/>';
                }
            }
        }
    }
    $aRelevantAttachments = array();
    /*
     * Iterate through attachments and check them for relevance.
     */
    if (isset($aAttachments['detailed_admin_notification'])) {
        foreach ($aAttachments['detailed_admin_notification'] as $aAttachment) {
            $relevance = $aAttachment['relevance'];
            // If the attachment is relevant it will be added to the mail.
            if (LimeExpressionManager::ProcessRelevance($relevance) && file_exists($aAttachment['url'])) {
                $aRelevantAttachments[] = $aAttachment['url'];
            }
        }
    }
    if (count($aEmailResponseTo) > 0) {
        $sMessage = templatereplace($thissurvey['email_admin_responses'], $aReplacementVars, $redata, 'frontend_helper[1414]', $thissurvey['anonymized'] == "Y", NULL, array(), true);
        $sSubject = templatereplace($thissurvey['email_admin_responses_subj'], $aReplacementVars, $redata, 'frontend_helper[1415]', $thissurvey['anonymized'] == "Y", NULL, array(), true);
        foreach ($aEmailResponseTo as $sRecipient) {
            if (!SendEmailMessage($sMessage, $sSubject, $sRecipient, $sFrom, $sitename, true, getBounceEmail($surveyid), $aRelevantAttachments)) {
                if ($debug > 0) {
                    echo '<br />Email could not be sent. Reason: ' . $maildebug . '<br/>';
                }
            }
        }
    }
}