function cw_user_process_address($address)
{
    if ($address) {
        $address['titleid'] = cw_user_detect_title(addslashes($address['title']));
        $address['title'] = cw_user_get_title($address['titleid']);
        $address['statename'] = cw_get_state($address['state'], $address['country']);
        $address['countryname'] = cw_get_country($address['country'], null, true);
        if ($config['General']['use_counties'] == 'Y') {
            $address['countyname'] = cw_get_county($address['county']);
        }
        if (empty($address['custom_fields'])) {
            $address['custom_fields'] = cw_user_get_custom_fields($address['customer_id'], $address['address_id'], 'A');
        }
    }
    return $address;
}
function cw_doc_get($doc_id, $info_type = 0)
{
    global $tables;
    global $config, $addons;
    global $app_main_dir;
    global $smarty;
    cw_load('warehouse', 'profile_fields');
    $doc = cw_query_first("select * from {$tables['docs']} where doc_id='{$doc_id}'");
    $doc['info'] = cw_query_first("select * from {$tables['docs_info']} where doc_info_id='{$doc['doc_info_id']}'");
    $doc['info']['carrier'] = cw_call('cw_shipping_get_carrier', array($doc['info']['shipping_id']));
    $doc['info']['applied_taxes'] = unserialize($doc['info']['applied_taxes']);
    $doc['info']['extra'] = unserialize($doc['info']['extra']);
    $doc['info']['extras'] = cw_call('cw_doc_get_extras_data', array($doc_id));
    $doc['userinfo'] = cw_query_first("select * from {$tables['docs_user_info']} where doc_info_id='{$doc['doc_info_id']}'");
    $doc['userinfo']['main_address'] = cw_user_get_address(null, $doc['userinfo']['main_address_id']);
    $doc['userinfo']['current_address'] = cw_user_get_address(null, $doc['userinfo']['current_address_id']);
    $fields_area = cw_profile_fields_get_area($doc['userinfo']['customer_id'], $doc['userinfo']['membership_id']);
    list($profile_sections, $profile_fields, $additional_fields) = cw_profile_fields_get_sections('U', true, $fields_area);
    $doc['userinfo']['profile_sections'] = $profile_sections;
    $doc['userinfo']['profile_fields'] = $profile_fields;
    $doc['related_docs'] = cw_doc_get_related($doc_id);
    $doc['settings'] = cw_doc_get_settings($doc['doc_info_id']);
    if ($addons['egoods']) {
        $join .= " left join {$tables['download_keys']} ON {$tables['docs_items']}.item_id={$tables['download_keys']}.item_id AND {$tables['download_keys']}.product_id={$tables['docs_items']}.product_id";
        $fields .= ", {$tables['download_keys']}.download_key, {$tables['download_keys']}.expires";
    }
    $join .= " left join {$tables['products_system_info']} on {$tables['products_system_info']}.product_id={$tables['docs_items']}.product_id";
    $fields .= ", {$tables['products_system_info']}.supplier_customer_id";
    $products = cw_query("select {$tables['products']}.*, {$tables['products']}.productcode as sku, {$tables['docs_items']}.*, IF({$tables['products']}.product_id IS NULL, 'Y', '') as is_deleted, IF({$tables['docs_items']}.product = '', {$tables['products']}.product, {$tables['docs_items']}.product) as product {$fields} FROM {$tables['docs_items']} LEFT JOIN {$tables['products']} ON {$tables['docs_items']}.product_id = {$tables['products']}.product_id {$join} WHERE {$tables['docs_items']}.doc_id='{$doc_id}'");
    $products = cw_doc_translate_products($products, $doc['info']['language']);
    $is_returns = false;
    cw_load('warehouse');
    $gift_doc_ids = cw_doc_get_related_docs($doc_id);
    $gift_doc_ids = array_unique(array_merge($gift_doc_ids, array($doc_id)));
    $giftcerts = cw_query("SELECT * {$gc_add_date} FROM {$tables['giftcerts']} WHERE doc_id in ('" . implode(',', $gift_doc_ids) . "')");
    if (!empty($giftcerts) && $config['General']['use_counties'] == "Y") {
        foreach ($giftcerts as $k => $v) {
            if (!empty($v['recipient_county'])) {
                $giftcerts[$k]['recipient_countyname'] = cw_get_county($v['recipient_county']);
            }
        }
    }
    $doc['giftcerts'] = $giftcerts;
    if ($doc['info']['giftcert_ids']) {
        $doc['info']['applied_giftcerts'] = explode('*', $doc['info']['giftcert_ids']);
        if ($doc['info']['applied_giftcerts']) {
            $tmp = array();
            foreach ($doc['info']['applied_giftcerts'] as $k => $v) {
                if (empty($v)) {
                    continue;
                }
                list($arr['giftcert_id'], $arr['giftcert_cost']) = explode(':', $v);
                $tmp[] = $arr;
            }
            $doc['info']['applied_giftcerts'] = $tmp;
        }
    }
    $doc['is_returns'] = $is_returns;
    if (cw_query_first_cell("select count(*) from {$tables['docs_items']}, {$tables['download_keys']} WHERE {$tables['docs_items']}.doc_id = '{$doc_id}' and {$tables['download_keys']}.item_id = {$tables['docs_items']}.item_id ")) {
        $doc['is_egood'] = 'Y';
    } elseif (cw_query_first_cell("select count(*) from {$tables['docs_items']}, {$tables['products']} WHERE {$tables['docs_items']}.doc_id = '{$doc_id}' and {$tables['docs_items']}.product_id={$tables['products']}.product_id AND {$tables['products']}.distribution != ''")) {
        $doc['is_egood'] = 'E';
    }
    if (preg_match("/(free_ship|percent|absolute)(?:``)(.+)/S", $doc['coupon'], $found)) {
        $doc['coupon'] = $found[2];
        $doc['coupon_type'] = $found[1];
    }
    $order['info']['extra']['tax_info']['product_tax_name'] = '';
    $_products_taxes = array();
    if ($products) {
        foreach ($products as $k => $v) {
            if ($addons['sn']) {
                $v['serial_numbers'] = cw_query("select * from {$tables['docs_items_serials']} where item_id='{$v['item_id']}'");
            }
            $v['product_options_txt'] = $v['product_options'];
            if ($v['extra_data']) {
                $v['extra_data'] = unserialize($v['extra_data']);
                if (is_array(@$v['extra_data']['display'])) {
                    foreach ($v['extra_data']['display'] as $i => $j) {
                        $v["display_" . $i] = $j;
                    }
                }
                if (is_array($v['extra_data']['taxes'])) {
                    foreach ($v['extra_data']['taxes'] as $i => $j) {
                        if ($j['tax_value'] > 0) {
                            $_products_taxes[$i] = $j['tax_display_name'];
                        }
                    }
                }
            }
            $v['original_price'] = $v['ordered_price'] = $v['price'];
            $v['price_deducted_tax'] = "Y";
            if ($v['is_deleted'] != 'Y') {
                $v['original_price'] = cw_query_first_cell("SELECT {$tables['products_prices']}.price FROM {$tables['products_prices']} WHERE {$tables['products_prices']}.product_id = '{$v['product_id']}' AND {$tables['products_prices']}.membership_id IN (0, '{$userinfo['membership_id']}') AND {$tables['products_prices']}.quantity <= '{$v['amount']}' AND {$tables['products_prices']}.variant_id = 0");
                # kornev, TOFIX
                if ($addons['product_options'] && $v['extra_data']['product_options']) {
                    list($variant, $product_options) = cw_get_product_options_data($v['product_id'], $v['extra_data']['product_options'], $userinfo['membership_id']);
                    if ($product_options === false) {
                        unset($product_options);
                    } else {
                        if (empty($variant['price'])) {
                            $variant['price'] = $v['original_price'];
                        }
                        $v['original_price'] = $variant['price'];
                        unset($variant['price']);
                        if ($product_options) {
                            foreach ($product_options as $o) {
                                if ($o['modifier_type'] == '%') {
                                    $v['original_price'] += $v['original_price'] * $o['price_modifier'] / 100;
                                } else {
                                    $v['original_price'] += $o['price_modifier'];
                                }
                            }
                        }
                        $v['product_options'] = $product_options;
                        # Check current and saved product options set
                        if (!empty($v['product_options_txt'])) {
                            $flag_txt = true;
                            # Check saved product options
                            $count = 0;
                            foreach ($v['product_options'] as $opt) {
                                if (preg_match("/" . preg_quote($opt['class'], "/") . ": " . preg_quote($opt['option_name'], "/") . "/Sm", $v['product_options_txt'])) {
                                    $count++;
                                }
                            }
                            if ($count != count($v['product_options'])) {
                                $flag_txt = false;
                            }
                            # Check current product options set
                            if ($flag_txt) {
                                $count = 0;
                                $tmp = explode("\n", $v['product_options_txt']);
                                foreach ($tmp as $txt_row) {
                                    if (!preg_match("/^([^:]+): (.*)\$/S", trim($txt_row), $match)) {
                                        continue;
                                    }
                                    foreach ($v['product_options'] as $opt) {
                                        if ($match[1] == $opt['option_name'] && $match[2] == trim($opt['name'])) {
                                            $count++;
                                            break;
                                        }
                                    }
                                }
                                if ($count != count($tmp)) {
                                    $flag_txt = false;
                                }
                            }
                            # Force display saved product options set
                            # if saved and current product options sets wasn't equal
                            if (!$flag_txt) {
                                $v['force_product_options_txt'] = true;
                            }
                        }
                        if (!empty($variant)) {
                            $v = cw_array_merge($v, $variant);
                        }
                    }
                }
            }
            $products[$k] = $v;
        }
    }
    $doc['products'] = $products;
    if (count($_products_taxes) == 1) {
        $order['info']['extra']['tax_info']['product_tax_name'] = array_pop($_products_taxes);
    }
    if ($order['coupon_type'] == "free_ship") {
        $order['shipping_cost'] = $order['coupon_discount'];
        $order['discounted_subtotal'] += $order['coupon_discount'];
    }
    $order['discounted_subtotal'] = price_format($order['discounted_subtotal']);
    # kornev, 512 is free for now (something was removed)
    if ($info_type & 1024 && $addons['pos']) {
        cw_load('pos');
        $doc['pos'] = cw_pos_get_doc_info($doc['doc_info_id']);
    }
    if ($info_type & 2048) {
        $doc['warehouse'] = cw_warehouse_get_like_user($doc['info']['warehouse_customer_id'], $doc['info']['warehouse_customer_id']);
    }
    if ($info_type & 4096) {
        $doc['quotes'] = cw_doc_get_quotes($doc_id);
    }
    if ($info_type & 8192) {
        $doc['info']['details'] = text_decrypt($doc['info']['details']);
    }
    if ($info_type & 1) {
        $doc['attributes'] = cw_func_call('cw_attributes_get', array('item_id' => $doc_id, 'item_type' => 'O'));
    }
    return $doc;
}
     # Send via Email
     #
     $fill_error = $fill_error || empty($recipient_email);
     $giftcert = array("purchaser" => stripslashes($purchaser), "recipient" => stripslashes($recipient), "message" => stripslashes($message), "amount" => $amount, "send_via" => $send_via, "recipient_email" => $recipient_email);
 } else {
     #
     # Send via Postal Mail
     #
     $has_states = cw_query_first_cell("SELECT display_states FROM {$tables['map_countries']} WHERE code = '" . $recipient_country . "'") == 'Y';
     $fill_error = $fill_error || empty($recipient_firstname) || empty($recipient_lastname) || empty($recipient_address) || empty($recipient_city) || empty($recipient_zipcode) || empty($recipient_state) && $has_states || empty($recipient_country) || empty($recipient_county) && $has_states && $config['General']['use_counties'] == "Y";
     if (empty($gc_template) || $config['Gift_Certificates']['allow_customer_select_tpl'] != 'Y') {
         $gc_template = $config['Gift_Certificates']['default_giftcert_template'];
     } else {
         $gc_template = stripslashes($gc_template);
     }
     $giftcert = array("purchaser" => stripslashes($purchaser), "recipient" => stripslashes($recipient), "message" => stripslashes($message), "amount" => $amount, "send_via" => $send_via, "recipient_firstname" => stripslashes($recipient_firstname), "recipient_lastname" => stripslashes($recipient_lastname), "recipient_address" => stripslashes($recipient_address), "recipient_city" => stripslashes($recipient_city), "recipient_zipcode" => $recipient_zipcode, "recipient_county" => $recipient_county, "recipient_countyname" => cw_get_county($recipient_county), "recipient_state" => $recipient_state, "recipient_statename" => cw_get_state($recipient_state, $recipient_country), "recipient_country" => $recipient_country, "recipient_countryname" => cw_get_country($recipient_country), "recipient_phone" => $recipient_phone, "tpl_file" => $gc_template);
 }
 #
 # If gcindex is empty - add
 # overwise - update
 #
 if (!$fill_error && !$amount_error) {
     if (!empty($addons['Gift_Certificates']) && $action == "addgc2wl") {
         cw_include('addons/Wishlist/wishlist.php');
     }
     if ($mode == "preview") {
         $smarty->assign('giftcerts', array($giftcert));
         header("Content-Type: text/html");
         header("Content-Disposition: inline; filename=giftcertificates.html");
         $_tmp_smarty_debug = $smarty->debugging;
         $smarty->debugging = false;
    if (!$fillerror && is_array($additional_fields)) {
        foreach ($additional_fields as $k => $v) {
            $additional_fields[$k]['value'] = stripslashes($_POST['additional_values'][$v['field_id']]);
            if (empty($_POST['additional_values'][$v['field_id']]) && $v['required'] == 'Y' && $v['avail'] == 'Y') {
                $fillerror = true;
            }
        }
    }
    if (!$fillerror) {
        $fillerror = empty($subject) || empty($body);
    }
    if (!$fillerror && !$antibot_err) {
        $contact['b_statename'] = cw_get_state($contact['b_state'], $contact['b_country']);
        $contact['b_countryname'] = cw_get_country($contact['b_country']);
        if ($config['General']['use_counties'] == "Y") {
            $contact['b_countyname'] = cw_get_county($contact['b_county']);
        }
        $contact = cw_stripslashes($contact);
        $smarty->assign('contact', $contact);
        $smarty->assign('profile_fields', $profile_fields);
        $smarty->assign('is_areas', $is_areas);
        $smarty->assign('additional_fields', $additional_fields);
        cw_call('cw_send_mail', array($contact['email'], $config['Company']['support_department'], 'mail/contactus/subj.tpl', 'mail/contactus/body.tpl', $config['default_admin_language']));
        $top_message = array('content' => cw_get_langvar_by_name('txt_contact_us_sent'), 'type' => 'I');
        cw_header_location(cw_call('cw_core_get_html_page_url', array(array("var" => "help", "section" => "contactus", 'delimiter' => '&'))));
    } else {
        cw_unset($_POST, 'additional_values');
        $userinfo = $_POST;
        $userinfo['customer_id'] = $userinfo['uname'];
    }
}