function cw_order_messages_process_new_emails($condition = "")
{
    global $tables, $config;
    global $take_messages_debug;
    cw_load('doc', 'user');
    $new_emails = cw_query("select * from {$tables['mail_rpool']} {$condition}");
    if (empty($new_emails)) {
        return;
    }
    $processed_mail_ids = array();
    foreach ($new_emails as $email) {
        if (strpos($email['body'], '--------- please reply above this line ----------') !== false) {
            $bodyparts = explode("--------- please reply above this line ----------", $email['body']);
            if (!empty($bodyparts[0])) {
                $email['body'] = $bodyparts[0];
            }
        }
        //remove RE, FWD etc from subject
        $clean_subject = cw_order_messages_remove_re($email['subject']);
        //cw_log_add("order_messages_process_new_emails",array('clean_subject'=>$clean_subject));
        if ($take_messages_debug == 'Y') {
            print_r(array('clean_subject' => $clean_subject));
            print "<br>";
        }
        $related_threads = cw_query($s = "select {$tables['order_messages_messages']}.*, {$tables['order_messages_threads']}.doc_id from {$tables['order_messages_messages']} left join {$tables['order_messages_threads']} on {$tables['order_messages_threads']}.thread_id={$tables['order_messages_messages']}.thread_id where {$tables['order_messages_messages']}.subject = '{$clean_subject}'");
        //cw_log_add("order_messages_process_new_emails", array('related_threads'=>$related_threads, 'sql'=>$s));
        if ($take_messages_debug == 'Y') {
            print_r(array('related_threads' => $related_threads, 'sql' => $s));
            print "<br>";
        }
        if (!empty($related_threads)) {
            foreach ($related_threads as $doc_thread) {
                $doc_data = cw_call('cw_doc_get', array($doc_thread['doc_id'], 8192));
                if ($email['mail_from'] == $doc_data['userinfo']['email']) {
                    $new_message_id = cw_array2insert('order_messages_messages', array('thread_id' => $doc_thread['thread_id'], 'sender_id' => $doc_data['userinfo']['customer_id'], 'recepient_id' => $doc_thread['author_id'], 'author_id' => $doc_data['userinfo']['customer_id'], 'date' => time(), 'subject' => addslashes($email['subject']), 'body' => addslashes($email['body']), 'read_status' => 0));
                    //notify recipient over email when reply is processed
                    cw_order_messages_notify_other_respondent($new_message_id, $doc_thread['author_id'], $doc_thread['doc_id']);
                    $processed_mail_ids[] = $email['mail_id'];
                    break;
                } elseif (cw_query_first_cell("select count(*) from {$tables['customers']} where usertype='A' and email='{$email['mail_from']}'")) {
                    $admin_id = cw_query_first_cell("select customer_id from {$tables['customers']} where usertype='A' and email='{$email['mail_from']}'");
                    $recepient_ids = array();
                    if ($doc_thread['sender_id'] != $admin_id) {
                        $recepient_ids[] = $doc_thread['sender_id'];
                    }
                    if ($doc_thread['recepient_id'] != $admin_id) {
                        $recepient_ids[] = $doc_thread['recepient_id'];
                    }
                    $new_message_id = cw_array2insert('order_messages_messages', array('thread_id' => $doc_thread['thread_id'], 'sender_id' => $admin_id, 'recepient_id' => $recepient_ids[0], 'author_id' => $admin_id, 'date' => time(), 'subject' => addslashes($email['subject']), 'body' => addslashes($email['body']), 'read_status' => 0));
                    //notify recipient over email when reply is processed
                    foreach ($recepient_ids as $recepient_id) {
                        cw_order_messages_notify_other_respondent($new_message_id, $recepient_id, $doc_thread['doc_id']);
                    }
                    $processed_mail_ids[] = $email['mail_id'];
                    break;
                } else {
                    $supplier_info = array();
                    foreach ($doc_data['products'] as $doc_product) {
                        if ($doc_product['supplier_customer_id']) {
                            $supplier_info = cw_user_get_info($doc_product['supplier_customer_id'], 1);
                            if ($supplier_info['email'] == $email['mail_from']) {
                                break;
                            }
                            $supplier_info = array();
                        }
                    }
                    if (!empty($supplier_info)) {
                        $new_message_id = cw_array2insert('order_messages_messages', array('thread_id' => $doc_thread['thread_id'], 'sender_id' => $supplier_info['customer_id'], 'recepient_id' => $doc_thread['author_id'], 'author_id' => $supplier_info['customer_id'], 'date' => time(), 'subject' => addslashes($email['subject']), 'body' => addslashes($email['body']), 'read_status' => 0));
                        //notify recipient over email when reply is processed
                        cw_order_messages_notify_other_respondent($new_message_id, $doc_thread['author_id'], $doc_thread['doc_id']);
                        $processed_mail_ids[] = $email['mail_id'];
                        break;
                    }
                }
            }
        } else {
            //detect thread by {thread_id} or create new thread by #SW [doc_id]
            //cw_log_add("order_messages_process_new_emails", "detect thread by {thread_id}");
            if ($take_messages_debug == 'Y') {
                print_r(array("detect thread by {thread_id}"));
                print "<br>";
            }
            $email_thread_id = intval(cw_order_messages_take_out_from_tags($email['subject'], "{", "}", false));
            $related_thread = cw_query_first("select {$tables['order_messages_threads']}.* from {$tables['order_messages_threads']} where {$tables['order_messages_threads']}.thread_id='{$email_thread_id}'");
            if (empty($related_thread)) {
                $email_thread_id = 0;
            }
            //cw_log_add("order_messages_process_new_emails",array("email_thread_id"=>$email_thread_id));
            if ($take_messages_debug == 'Y') {
                print_r(array("email_thread_id" => $email_thread_id));
                print "<br>";
            }
            if (empty($email_thread_id) && strpos($email['subject'], "#") !== false) {
                $_parts = explode("#", cw_order_messages_remove_doc_prefix($email['subject']));
                $extracted_doc_id = intval(trim($_parts[1]));
                //cw_log_add("order_messages_process_new_emails", array("extracted_doc_id"=>$extracted_doc_id));
                if ($take_messages_debug == 'Y') {
                    print_r(array("extracted_doc_id" => $extracted_doc_id));
                    print "<br>";
                }
                if ($extracted_doc_id) {
                    $doc_data = cw_call('cw_doc_get', array($extracted_doc_id, 8192));
                    if (!empty($doc_data)) {
                        $email_thread_id = cw_array2insert('order_messages_threads', array('doc_id' => $extracted_doc_id, 'type' => 'A'));
                    }
                }
                //cw_log_add("order_messages_process_new_emails", array("created new thread"=>$email_thread_id));
                if ($take_messages_debug == 'Y') {
                    print_r(array("created new thread" => $email_thread_id));
                    print "<br>";
                }
                if (!empty($email_thread_id)) {
                    $related_thread = $email_thread_id;
                }
            }
            if (empty($related_thread)) {
                continue;
            }
            $email_sender_id = cw_query_first_cell("select customer_id from {$tables['customers']} where email='{$email['mail_from']}'");
            //cw_log_add("order_messages_process_new_emails", array("$email[mail_from] email_sender_id $email_sender_id"));
            if ($take_messages_debug == 'Y') {
                print_r(array("{$email['mail_from']} email_sender_id {$email_sender_id}"));
                print "<br>";
            }
            if (empty($email_sender_id)) {
                continue;
            }
            //is sender email related to detected thread
            $is_email_allowed = cw_query_first_cell("select count(*) from {$tables['order_messages_messages']} where {$tables['order_messages_messages']}.thread_id='{$email_thread_id}' and ({$tables['order_messages_messages']}.sender_id='{$email_sender_id}' or {$tables['order_messages_messages']}.recepient_id='{$email_sender_id}' or {$tables['order_messages_messages']}.author_id='{$email_sender_id}')");
            if (!$is_email_allowed) {
                $is_email_allowed = cw_query_first_cell("select count(*) from {$tables['docs_user_info']} dui, {$tables['docs']} d, {$tables['order_messages_threads']} omt where omt.thread_id='{$email_thread_id}' and omt.doc_id=d.doc_id and d.doc_info_id=dui.doc_info_id and dui.email='{$email['mail_from']}'");
            }
            //cw_log_add("order_messages_process_new_emails", "<br>is_email_allowed $is_email_allowed<br>");
            if ($take_messages_debug == 'Y') {
                print_r(array("<br>is_email_allowed {$is_email_allowed}<br>"));
                print "<br>";
            }
            if ($is_email_allowed) {
                //get other respondends in thread
                $other_respondent_id = cw_query_first_cell("select sender_id from {$tables['order_messages_messages']} where thread_id='{$email_thread_id}' and sender_id != '{$email_sender_id}'");
                //cw_log_add("order_messages_process_new_emails","<br>other_respondent_id $other_respondent_id<br>");
                if ($take_messages_debug == 'Y') {
                    print_r(array("<br>other_respondent_id {$other_respondent_id}<br>"));
                    print "<br>";
                }
                if (empty($other_respondent_id)) {
                    $other_respondent_id = cw_query_first_cell("select recepient_id from {$tables['order_messages_messages']} where thread_id='{$email_thread_id}' and recepient_id != '{$email_sender_id}'");
                }
                if (empty($other_respondent_id) || cw_query_first_cell("select count(*) from {$tables['customers']} where usertype='A' and customer_id='{$other_respondent_id}'")) {
                    //use default id to sent email
                    if (!empty($config['order_messages']['default_recepient_admin_email'])) {
                        $default_recepient_admin_email = $config['order_messages']['default_recepient_admin_email'];
                    }
                    $other_respondent_id = cw_query_first_cell("select customer_id from {$tables['customers']} where usertype='A' and email='{$default_recepient_admin_email}'");
                    //cw_log_add("order_messages_process_new_emails","<br>selected default recepient ($default_recepient_admin_email): customer_id = $other_respondent_id<br>");
                    if ($take_messages_debug == 'Y') {
                        print_r(array("<br>selected default recepient ({$default_recepient_admin_email}): customer_id = {$other_respondent_id}<br>"));
                        print "<br>";
                    }
                }
                if (!empty($other_respondent_id)) {
                    global $smarty, $current_language;
                    $rnd_key = time();
                    $smarty->assign('message', array('subject' => $rnd_key, 'thread_id' => $email_thread_id));
                    $smarty->assign('doc_id', $related_thread['doc_id']);
                    $language = $language ? $language : $current_language;
                    $order_subject_template = 'addons/order_messages/mail/customer_subj.tpl';
                    $test_subject = chop(cw_display($order_subject_template, $smarty, false, $language));
                    //cw_log_add("order_messages_process_new_emails","<br>test subject: $test_subject<br>");
                    if ($take_messages_debug == 'Y') {
                        print_r(array("<br>test subject: {$test_subject}<br>"));
                        print "<br>";
                    }
                    $subject_parts = explode($rnd_key, $test_subject);
                    $extracted_replied_subject = str_replace($subject_parts, "", $email['subject']);
                    //cw_log_add("order_messages_process_new_emails","<br>extracted_replied_subject $extracted_replied_subject<br>");
                    if ($take_messages_debug == 'Y') {
                        print_r(array("<br>extracted_replied_subject {$extracted_replied_subject}<br>"));
                        print "<br>";
                    }
                    $new_message_id = cw_array2insert('order_messages_messages', array('thread_id' => $email_thread_id, 'sender_id' => $email_sender_id, 'recepient_id' => $other_respondent_id, 'author_id' => $email_sender_id, 'date' => time(), 'subject' => addslashes($extracted_replied_subject), 'body' => addslashes($email['body']), 'read_status' => 0));
                    cw_order_messages_notify_other_respondent($new_message_id, $other_respondent_id, $related_thread['doc_id']);
                    $processed_mail_ids[] = $email['mail_id'];
                }
            }
        }
    }
    //if ($take_messages_debug != "Y")
    if (!empty($processed_mail_ids)) {
        db_query("delete from {$tables['mail_rpool']} where mail_id in ('" . implode("','", $processed_mail_ids) . "')");
    }
    return $processed_mail_ids;
}
        if ($thread_id && $doc_id) {
            //get other respondends in thread
            $new_message_recepient_id = cw_query_first_cell("select sender_id from {$tables['order_messages_messages']} where thread_id='{$thread_id}' and sender_id != '{$customer_id}'");
            if (empty($new_message_recepient_id)) {
                $new_message_recepient_id = cw_query_first_cell("select recepient_id from {$tables['order_messages_messages']} where thread_id='{$thread_id}' and recepient_id != '{$customer_id}'");
            }
            if ($new_message['on_behalf']) {
                $sender_id = $new_message_recepient_id;
                $recepient_id = $customer_id;
            } else {
                $recepient_id = $new_message_recepient_id;
                $sender_id = $customer_id;
            }
            $new_message_id = cw_array2insert('order_messages_messages', array('thread_id' => $thread_id, 'sender_id' => $sender_id, 'recepient_id' => $recepient_id, 'author_id' => $customer_id, 'date' => time(), 'subject' => addslashes($new_message['subject']), 'body' => addslashes($new_message['body']), 'read_status' => 1));
            if ($recepient_id != $customer_id && $new_message_id) {
                cw_order_messages_notify_other_respondent($new_message_id, $recepient_id, $doc_id);
            }
        }
    }
    cw_header_location("index.php?target={$target}&mode={$mode}&doc_id={$doc_id}&thread_id={$thread_id}");
}
$thread_messages = cw_query("select * from {$tables['order_messages_messages']} where thread_id = '{$thread_id}' order by date desc");
cw_array2update('order_messages_messages', array('read_status' => 1), "thread_id = '{$thread_id}'");
//global $config;
$messages_users = array();
$start_message = array();
foreach ($thread_messages as $msg_k => $msg) {
    if (!$msg['sender_id']) {
        if (!empty($config['order_messages']['default_recepient_admin_email'])) {
            $default_recepient_admin_email = $config['order_messages']['default_recepient_admin_email'];
        }