/**
  * Output the metabox
  */
 public static function output($post)
 {
     global $post, $wpdb, $thepostid;
     wp_nonce_field('propertyhive_save_data', 'propertyhive_meta_nonce');
     echo '<div class="propertyhive_meta_box">';
     echo '<div class="options_group">';
     propertyhive_wp_text_input(array('id' => '_address_name_number', 'label' => __('Building Name / Number', 'propertyhive'), 'desc_tip' => false, 'placeholder' => __('e.g. Thistle Cottage, or Flat 10', 'propertyhive'), 'type' => 'text'));
     propertyhive_wp_text_input(array('id' => '_address_street', 'label' => __('Street', 'propertyhive'), 'desc_tip' => false, 'placeholder' => __('e.g. High Street', 'propertyhive'), 'type' => 'text'));
     propertyhive_wp_text_input(array('id' => '_address_two', 'label' => __('Address Line 2', 'propertyhive'), 'desc_tip' => false, 'type' => 'text'));
     propertyhive_wp_text_input(array('id' => '_address_three', 'label' => __('Town / City', 'propertyhive'), 'desc_tip' => false, 'type' => 'text'));
     propertyhive_wp_text_input(array('id' => '_address_four', 'label' => __('County / State', 'propertyhive'), 'desc_tip' => false, 'type' => 'text'));
     propertyhive_wp_text_input(array('id' => '_address_postcode', 'label' => __('Postcode / Zip Code', 'propertyhive'), 'desc_tip' => false, 'type' => 'text'));
     // Country dropdown
     $countries = get_option('propertyhive_countries', array('GB'));
     $contact_country = get_post_meta($thepostid, '_address_country', TRUE);
     if ($contact_country == '') {
         $contact_country = get_option('propertyhive_default_country', 'GB');
     }
     if (empty($countries) || count($countries) < 2) {
         propertyhive_wp_hidden_input(array('id' => '_address_country', 'value' => $contact_country));
     } else {
         $ph_countries = new PH_Countries();
         $country_options = array();
         foreach ($countries as $country_code) {
             $country = $ph_countries->get_country($country_code);
             if ($country !== false) {
                 $country_options[$country_code] = $country['name'];
             }
         }
         propertyhive_wp_select(array('id' => '_address_country', 'label' => __('Country', 'propertyhive'), 'desc_tip' => false, 'options' => $country_options, 'value' => $contact_country));
     }
     do_action('propertyhive_contact_correspondence_address_fields');
     echo '</div>';
     echo '</div>';
 }
 /**
  * Save meta box data
  */
 public static function save($post_id, $post)
 {
     global $wpdb;
     // Only save meta info if department is 'commercial'
     $department = get_post_meta($post_id, '_department', TRUE);
     if ($department == 'commercial') {
         update_post_meta($post_id, '_for_sale', '');
         update_post_meta($post_id, '_to_rent', '');
         if (isset($_POST['_available_as']) && !empty($_POST['_available_as'])) {
             if (in_array('sale', $_POST['_available_as'])) {
                 update_post_meta($post_id, '_for_sale', 'yes');
                 update_post_meta($post_id, '_commercial_price_currency', $_POST['_commercial_price_currency']);
                 $price = preg_replace("/[^0-9.]/", '', $_POST['_price_from']);
                 if ($price == '') {
                     $price = preg_replace("/[^0-9.]/", '', $_POST['_price_to']);
                 }
                 update_post_meta($post_id, '_price_from', $price);
                 $price = preg_replace("/[^0-9.]/", '', $_POST['_price_to']);
                 if ($price == '') {
                     $price = preg_replace("/[^0-9.]/", '', $_POST['_price_from']);
                 }
                 update_post_meta($post_id, '_price_to', $price);
                 update_post_meta($post_id, '_price_units', $_POST['_price_units']);
                 update_post_meta($post_id, '_price_poa', isset($_POST['_commercial_price_poa']) ? $_POST['_commercial_price_poa'] : '');
                 if (!empty($_POST['commercial_price_qualifier_id'])) {
                     wp_set_post_terms($post_id, $_POST['commercial_price_qualifier_id'], 'price_qualifier');
                 } else {
                     // Setting to blank
                     wp_delete_object_term_relationships($post_id, 'price_qualifier');
                 }
                 if (!empty($_POST['commercial_sale_by_id'])) {
                     wp_set_post_terms($post_id, $_POST['commercial_sale_by_id'], 'sale_by');
                 } else {
                     // Setting to blank
                     wp_delete_object_term_relationships($post_id, 'sale_by');
                 }
                 if (!empty($_POST['commercial_tenure_id'])) {
                     wp_set_post_terms($post_id, $_POST['commercial_tenure_id'], 'commercial_tenure');
                 } else {
                     // Setting to blank
                     wp_delete_object_term_relationships($post_id, 'commercial_tenure');
                 }
             }
             if (in_array('rent', $_POST['_available_as'])) {
                 update_post_meta($post_id, '_to_rent', 'yes');
                 update_post_meta($post_id, '_commercial_rent_currency', $_POST['_commercial_rent_currency']);
                 $rent = preg_replace("/[^0-9.]/", '', $_POST['_rent_from']);
                 if ($rent == '') {
                     $rent = preg_replace("/[^0-9.]/", '', $_POST['_rent_to']);
                 }
                 update_post_meta($post_id, '_rent_from', $rent);
                 $rent = preg_replace("/[^0-9.]/", '', $_POST['_rent_to']);
                 if ($rent == '') {
                     $rent = preg_replace("/[^0-9.]/", '', $_POST['_rent_from']);
                 }
                 update_post_meta($post_id, '_rent_to', $rent);
                 update_post_meta($post_id, '_rent_units', $_POST['_rent_units']);
                 update_post_meta($post_id, '_rent_poa', isset($_POST['_commercial_rent_poa']) ? $_POST['_commercial_rent_poa'] : '');
             }
         }
         // Store price in common currency (GBP) used for ordering
         $ph_countries = new PH_Countries();
         $ph_countries->update_property_price_actual($post_id);
         $property_types = array();
         if (isset($_POST['property_type_ids']) && !empty($_POST['property_type_ids'])) {
             foreach ($_POST['property_type_ids'] as $property_type_id) {
                 $property_types[] = $property_type_id;
             }
         }
         if (!empty($property_types)) {
             wp_set_post_terms($post_id, $property_types, 'commercial_property_type');
         } else {
             wp_delete_object_term_relationships($post_id, 'commercial_property_type');
         }
         $size = preg_replace("/[^0-9.]/", '', $_POST['_floor_area_from']);
         if ($size == '') {
             $size = preg_replace("/[^0-9.]/", '', $_POST['_floor_area_to']);
         }
         update_post_meta($post_id, '_floor_area_from', $size);
         update_post_meta($post_id, '_floor_area_from_sqft', convert_size_to_sqft($size, $_POST['_floor_area_units']));
         $size = preg_replace("/[^0-9.]/", '', $_POST['_floor_area_to']);
         if ($size == '') {
             $size = preg_replace("/[^0-9.]/", '', $_POST['_floor_area_from']);
         }
         update_post_meta($post_id, '_floor_area_to', $size);
         update_post_meta($post_id, '_floor_area_to_sqft', convert_size_to_sqft($size, $_POST['_floor_area_units']));
         update_post_meta($post_id, '_floor_area_units', $_POST['_floor_area_units']);
         $size = preg_replace("/[^0-9.]/", '', $_POST['_site_area_from']);
         if ($size == '') {
             $size = preg_replace("/[^0-9.]/", '', $_POST['_site_area_to']);
         }
         update_post_meta($post_id, '_site_area_from', $size);
         update_post_meta($post_id, '_site_area_from_sqft', convert_size_to_sqft($size, $_POST['_site_area_units']));
         $size = preg_replace("/[^0-9.]/", '', $_POST['_site_area_to']);
         if ($size == '') {
             $size = preg_replace("/[^0-9.]/", '', $_POST['_site_area_from']);
         }
         update_post_meta($post_id, '_site_area_to', $size);
         update_post_meta($post_id, '_site_area_to_sqft', convert_size_to_sqft($size, $_POST['_site_area_units']));
         update_post_meta($post_id, '_site_area_units', $_POST['_site_area_units']);
     }
 }
/**
 * Output individual field
 *
 * @return void
 */
function ph_form_field($key, $field)
{
    global $post;
    $output = '';
    switch ($field['type']) {
        case "text":
        case "email":
            $field['class'] = isset($field['class']) ? $field['class'] : '';
            $field['before'] = isset($field['before']) ? $field['before'] : '<div class="control control-' . $key . '">';
            $field['after'] = isset($field['after']) ? $field['after'] : '</div>';
            $field['show_label'] = isset($field['show_label']) ? $field['show_label'] : true;
            $field['label'] = isset($field['label']) ? $field['label'] : '';
            $field['placeholder'] = isset($field['placeholder']) ? $field['placeholder'] : '';
            $field['required'] = isset($field['required']) ? $field['label'] : false;
            $field['value'] = isset($field['value']) ? $field['value'] : '';
            if (isset($_GET[$key]) && !empty($_GET[$key])) {
                $field['value'] = $_GET[$key];
            } else {
                if (isset($post->ID)) {
                    $value = get_post_meta($post->ID, '_' . $key, true);
                    if ($value != '') {
                        $field['value'] = $value;
                    }
                }
            }
            $output .= $field['before'];
            if ($field['show_label']) {
                $output .= '<label for="' . esc_attr($key) . '">' . $field['label'];
                if ($field['required']) {
                    $output .= '<span class="required"> *</span>';
                }
                $output .= '</label>';
            }
            $output .= '<input 
                    type="' . esc_attr($field['type']) . '" 
                    name="' . esc_attr($key) . '" 
                    id="' . esc_attr($key) . '" 
                    value="' . esc_attr($field['value']) . '"
                    placeholder="' . esc_attr($field['placeholder']) . '"
                    class="' . esc_attr($field['class']) . '"
                    ' . ($field['required'] ? 'required' : '') . '
            >';
            $output .= $field['after'];
            break;
        case "textarea":
            $field['class'] = isset($field['class']) ? $field['class'] : '';
            $field['before'] = isset($field['before']) ? $field['before'] : '<div class="control control-' . $key . '">';
            $field['after'] = isset($field['after']) ? $field['after'] : '</div>';
            $field['show_label'] = isset($field['show_label']) ? $field['show_label'] : true;
            $field['label'] = isset($field['label']) ? $field['label'] : '';
            $field['placeholder'] = isset($field['placeholder']) ? $field['placeholder'] : '';
            $field['required'] = isset($field['required']) ? $field['label'] : false;
            $field['value'] = isset($field['value']) ? $field['value'] : '';
            if (isset($_GET[$key]) && !empty($_GET[$key])) {
                $field['value'] = $_GET[$key];
            }
            $output .= $field['before'];
            if ($field['show_label']) {
                $output .= '<label for="' . esc_attr($key) . '">' . $field['label'];
                if ($field['required']) {
                    $output .= '<span class="required"> *</span>';
                }
                $output .= '</label>';
            }
            $output .= '<textarea 
                    name="' . esc_attr($key) . '" 
                    id="' . esc_attr($key) . '" 
                    placeholder="' . esc_attr($field['placeholder']) . '"
                    class="' . esc_attr($field['class']) . '"
                    ' . ($field['required'] ? 'required' : '') . '
            >' . esc_attr($field['value']) . '</textarea>';
            $output .= $field['after'];
            break;
        case "radio":
            $field['class'] = isset($field['class']) ? $field['class'] : '';
            $field['before'] = isset($field['before']) ? $field['before'] : '<div class="control control-' . $key . '">';
            $field['after'] = isset($field['after']) ? $field['after'] : '</div>';
            $field['show_label'] = isset($field['show_label']) ? $field['show_label'] : false;
            $field['label'] = isset($field['label']) ? $field['label'] : '';
            $field['value'] = isset($field['value']) ? $field['value'] : '';
            if (isset($_GET[$key]) && !empty($_GET[$key])) {
                $field['value'] = $_GET[$key];
            }
            $output .= $field['before'];
            if ($field['show_label']) {
                $output .= '<label for="' . esc_attr($key) . '">' . $field['label'] . '</label>';
            }
            foreach ($field['options'] as $option_key => $value) {
                $output .= '<label><input 
                    type="' . esc_attr($field['type']) . '" 
                    name="' . esc_attr($key) . '" 
                    value="' . esc_attr($option_key) . '"
                    class="' . esc_attr($field['class']) . '" 
                    ' . checked(esc_attr($field['value']), esc_attr($option_key), false) . '
                > ' . esc_html($value) . '</label>';
            }
            $output .= $field['after'];
            break;
        case "select":
            $field['class'] = isset($field['class']) ? $field['class'] : '';
            $field['before'] = isset($field['before']) ? $field['before'] : '<div class="control control-' . $key . '">';
            $field['after'] = isset($field['after']) ? $field['after'] : '</div>';
            $field['show_label'] = isset($field['show_label']) ? $field['show_label'] : true;
            $field['label'] = isset($field['label']) ? $field['label'] : '';
            $field['options'] = isset($field['options']) && is_array($field['options']) ? $field['options'] : array();
            $field['value'] = isset($field['value']) ? $field['value'] : '';
            if (isset($_GET[$key]) && !empty($_GET[$key])) {
                $field['value'] = $_GET[$key];
            }
            $output .= $field['before'];
            if ($field['show_label']) {
                $output .= '<label for="' . esc_attr($key) . '">' . $field['label'] . '</label>';
            }
            $output .= '<select 
                name="' . esc_attr($key) . '" 
                id="' . esc_attr($key) . '" 
                class="' . esc_attr($field['class']) . '"
             >';
            foreach ($field['options'] as $option_key => $value) {
                $output .= '<option 
                    value="' . esc_attr($option_key) . '" 
                    ' . selected(esc_attr($field['value']), esc_attr($option_key), false) . '
                >' . esc_html($value) . '</option>';
            }
            $output .= '</select>';
            $output .= $field['after'];
            break;
        case "office":
            $key = 'officeID';
            $field['class'] = isset($field['class']) ? $field['class'] : '';
            $field['before'] = isset($field['before']) ? $field['before'] : '<div class="control control-' . $key . '">';
            $field['after'] = isset($field['after']) ? $field['after'] : '</div>';
            $field['show_label'] = isset($field['show_label']) ? $field['show_label'] : true;
            $field['label'] = isset($field['label']) ? $field['label'] : '';
            $field['value'] = isset($field['value']) ? $field['value'] : '';
            if (isset($_GET[$key]) && !empty($_GET[$key])) {
                $field['value'] = $_GET[$key];
            }
            $output .= $field['before'];
            if ($field['show_label']) {
                $output .= '<label for="' . esc_attr($key) . '">' . $field['label'] . '</label>';
            }
            $output .= '<select 
                name="' . esc_attr($key) . '" 
                id="' . esc_attr($key) . '" 
                class="' . esc_attr($field['class']) . '"
             >';
            $output .= '<option 
                        value="" 
                        ' . selected(esc_attr($field['value']), esc_attr(''), false) . '
                    >' . esc_html(__('No preference', 'propertyhive')) . '</option>';
            $args = array('post_type' => 'office', 'nopaging' => true, 'orderby' => 'title', 'order' => 'ASC');
            $office_query = new WP_Query($args);
            if ($office_query->have_posts()) {
                while ($office_query->have_posts()) {
                    $office_query->the_post();
                    $output .= '<option 
                        value="' . esc_attr($post->ID) . '" 
                        ' . selected(esc_attr($field['value']), esc_attr($post->ID), false) . '
                    >' . esc_html(get_the_title()) . '</option>';
                }
            }
            wp_reset_postdata();
            $output .= '</select>';
            $output .= $field['after'];
            break;
        case "country":
            $key = 'country';
            $field['class'] = isset($field['class']) ? $field['class'] : '';
            $field['before'] = isset($field['before']) ? $field['before'] : '<div class="control control-' . $key . '">';
            $field['after'] = isset($field['after']) ? $field['after'] : '</div>';
            $field['show_label'] = isset($field['show_label']) ? $field['show_label'] : true;
            $field['label'] = isset($field['label']) ? $field['label'] : '';
            $field['value'] = isset($field['value']) ? $field['value'] : '';
            if (isset($_GET[$key]) && !empty($_GET[$key])) {
                $field['value'] = $_GET[$key];
            }
            $output .= $field['before'];
            if ($field['show_label']) {
                $output .= '<label for="' . esc_attr($key) . '">' . $field['label'] . '</label>';
            }
            $output .= '<select 
                name="' . esc_attr($key) . '" 
                id="' . esc_attr($key) . '" 
                class="' . esc_attr($field['class']) . '"
             >';
            $output .= '<option 
                        value="" 
                        ' . selected(esc_attr($field['value']), esc_attr(''), false) . '
                    >' . esc_html(__('No preference', 'propertyhive')) . '</option>';
            $countries = get_option('propertyhive_countries', array());
            if (is_array($countries) && !empty($countries)) {
                $ph_countries = new PH_Countries();
                foreach ($countries as $country) {
                    $ph_country = $ph_countries->get_country($country);
                    if ($ph_country !== FALSE) {
                        $output .= '<option 
                        value="' . esc_attr($country) . '" 
                        ' . selected(esc_attr($field['value']), esc_attr($country), false) . '
                        >' . esc_html($ph_country['name']) . '</option>';
                    }
                }
            }
            $output .= '</select>';
            $output .= $field['after'];
            break;
        case "hidden":
            $field['value'] = isset($field['value']) ? $field['value'] : '';
            if (isset($_GET[$key]) && !empty($_GET[$key])) {
                $field['value'] = $_GET[$key];
            }
            $output .= '<input type="hidden" name="' . esc_attr($key) . '" value="' . $field['value'] . '">';
            break;
        default:
            if (taxonomy_exists($field['type'])) {
                $field['class'] = isset($field['class']) ? $field['class'] : '';
                $field['before'] = isset($field['before']) ? $field['before'] : '<div class="control control-' . $key . '">';
                $field['after'] = isset($field['after']) ? $field['after'] : '</div>';
                $field['show_label'] = isset($field['show_label']) ? $field['show_label'] : true;
                $field['label'] = isset($field['label']) ? $field['label'] : '';
                $field['blank_option'] = isset($field['blank_option']) ? $field['blank_option'] : __('No preference', 'propertyhive');
                $field['value'] = isset($field['value']) ? $field['value'] : '';
                if (isset($_GET[$key]) && !empty($_GET[$key])) {
                    $field['value'] = $_GET[$key];
                }
                $output .= $field['before'];
                if ($field['show_label']) {
                    $output .= '<label for="' . esc_attr($key) . '">' . $field['label'] . '</label>';
                }
                $output .= '<select 
                    name="' . esc_attr($key) . '" 
                    id="' . esc_attr($key) . '" 
                    class="' . esc_attr($field['class']) . '"
                 >';
                $options = array('' => $field['blank_option']);
                $args = array('hide_empty' => false, 'parent' => 0);
                $terms = get_terms($field['type'], $args);
                $selected_value = '';
                if (!empty($terms) && !is_wp_error($terms)) {
                    foreach ($terms as $term) {
                        $options[$term->term_id] = $term->name;
                        $args = array('hide_empty' => false, 'parent' => $term->term_id);
                        $subterms = get_terms($field['type'], $args);
                        if (!empty($subterms) && !is_wp_error($subterms)) {
                            foreach ($subterms as $term) {
                                $options[$term->term_id] = '- ' . $term->name;
                                $args = array('hide_empty' => false, 'parent' => $term->term_id);
                                $subsubterms = get_terms($field['type'], $args);
                                if (!empty($subsubterms) && !is_wp_error($subsubterms)) {
                                    foreach ($subsubterms as $term) {
                                        $options[$term->term_id] = '- ' . $term->name;
                                    }
                                }
                            }
                        }
                    }
                }
                foreach ($options as $option_key => $value) {
                    $output .= '<option 
                        value="' . esc_attr($option_key) . '" 
                        ' . selected(esc_attr($field['value']), esc_attr($option_key), false) . '
                    >' . esc_html($value) . '</option>';
                }
                $output .= '</select>';
                $output .= $field['after'];
            }
    }
    echo $output;
}
    /**
     * Output the metabox
     */
    public static function output($post, $args = array())
    {
        global $wpdb, $thepostid;
        $original_post = $post;
        $original_thepostid = $thepostid;
        // Used in the scenario where this meta box isn't used on the property edit page
        if (isset($args['args']['property_post'])) {
            $post = $args['args']['property_post'];
            $thepostid = $post->ID;
            setup_postdata($post);
        }
        if (isset($_GET['owner_contact_id']) && !empty($_GET['owner_contact_id'])) {
            if (get_post_type($_GET['owner_contact_id']) == 'contact') {
                $owner_contact_id = $_GET['owner_contact_id'];
            }
        } else {
            $owner_contact_id = get_post_meta($post->ID, '_owner_contact_id', TRUE);
        }
        echo '<div class="propertyhive_meta_box">';
        echo '<div class="options_group">';
        echo '<input type="hidden" name="_owner_contact_id" id="_owner_contact_id" value="' . $owner_contact_id . '">';
        // No owner currently selected
        echo '<div id="search_propertyhive_contacts"' . ($owner_contact_id != '' ? ' style="display:none"' : '') . '>';
        echo '<p class="form-field search_propertyhive_contacts_keyword_field">
                    <label for="search_propertyhive_contacts_keyword">' . __('Search Existing Contacts', 'propertyhive') . '</label>
                    <input type="text" class="short" name="search_propertyhive_contacts_keyword" id="search_propertyhive_contacts_keyword" value="" placeholder="' . __('Start typing to search...', 'propertyhive') . '">
                </p>';
        echo '<p class="form-field search_propertyhive_contacts_results">
                    <label for="search_propertyhive_contacts_results"></label>
                    <span id="search_propertyhive_contacts_results"></span>
                </p>';
        echo '<p class="form-field"><label>&nbsp;</label>';
        echo __('Or', 'propertyhive') . '<br><br>';
        echo '<a href="#" class="button add-new-property-owner-contact">' . __('Add New Contact', 'propertyhive') . '</a>';
        echo '</p>';
        echo '</div>';
        echo '<script>
            
                      function load_existing_owner_contact(contact_id)
                      {
                          // Do AJAX request
                          var data = {
                              action:         \'propertyhive_load_existing_owner_contact\',
                              contact_id:     contact_id,
                              security:       \'' . wp_create_nonce("load-existing-owner-contact") . '\',
                          };
                
                          jQuery.post( \'' . admin_url('admin-ajax.php') . '\', data, function(response) {
                              
                              jQuery(\'#existing-owner-details\').html( response );
                              
                          });
                          
                          jQuery(\'#_owner_contact_id\').val(contact_id);
                      }
            
                      jQuery(document).ready(function()
                      {
                          ';
        if ($owner_contact_id != '') {
            echo 'load_existing_owner_contact(' . $owner_contact_id . ');';
        }
        echo '
                          jQuery(\'a.add-new-property-owner-contact\').click(function()
                          {
                              jQuery(\'#search_propertyhive_contacts\').fadeOut(\'fast\', function()
                              {
                                  jQuery(\'#add_new_property_owner_contact\').fadeIn();
                              });
                              
                              return false;
                          });
                          
                          jQuery(\'a.search-property-owner-contacts\').click(function()
                          {
                              jQuery(\'#add_new_property_owner_contact\').fadeOut(\'fast\', function()
                              {
                                  jQuery(\'#search_propertyhive_contacts\').fadeIn();
                                  jQuery(\'#search_propertyhive_contacts_keyword\').focus();
                              });
                              
                              return false;
                          });
                          
                          jQuery(\'body\').on(\'click\', \'a[id^=\\\'search-contact-result-\\\']\', function()
                          {
                              var contact_id = jQuery(this).attr(\'id\');
                              contact_id = contact_id.replace(\'search-contact-result-\', \'\');
                              
                              load_existing_owner_contact(contact_id);
                              
                              jQuery(\'#search_propertyhive_contacts\').fadeOut(\'fast\', function()
                              {
                                    jQuery(\'#existing-owner-details\').fadeIn();
                              });
                              return false;
                          });
                          
                          jQuery(\'body\').on(\'click\', \'a#remove-owner-contact\', function()
                          {
                              jQuery(\'#existing-owner-details\').fadeOut(\'fast\', function()
                              {
                                    jQuery(\'#search_propertyhive_contacts\').fadeIn();
                              });
                              
                              jQuery(\'#_owner_contact_id\').val(\'\');
                              
                              return false;
                          });
                          
                          // Existing contact search
                          jQuery(\'#search_propertyhive_contacts_keyword\').keyup(function()
                          {
                              var keyword = jQuery(\'#search_propertyhive_contacts_keyword\').val();
                              
                              if (keyword.length == 0)
                              {
                                  // Clear existing results
                                  jQuery(\'#search_propertyhive_contacts_results\').stop(true, true).fadeOut(\'fast\');
                              }
                              else
                              {
                                  jQuery(\'#search_propertyhive_contacts_results\').stop(true, true).fadeIn(\'fast\');
                                  
                                  if (keyword.length > 2)
                                  {
                                        // Do AJAX request
                                        var data = {
                                            action:         \'propertyhive_search_contacts\',
                                            keyword:        keyword,
                                            security:       \'' . wp_create_nonce("search-contacts") . '\',
                                        };
                                
                                        jQuery.post( \'' . admin_url('admin-ajax.php') . '\', data, function(response) {
                                            
                                            if (response.length > 0)
                                            {
                                                var new_html = \'\';
                                                for (var i in response)
                                                {
                                                    new_html += \'<a href="#" id="search-contact-result-\' + response[i].ID + \'">\' + response[i].post_title + \'</a><br>\';
                                                }
                                                jQuery(\'#search_propertyhive_contacts_results\').html(new_html);
                                            }
                                            else
                                            {
                                                jQuery(\'#search_propertyhive_contacts_results\').html(\'' . __('No contacts found', 'propertyhive') . '\');
                                            }
                                            
                                            
                                            //$(\'ul.record_notes\').prepend( response );
                                            //$(\'#propertyhive-property-notes\').unblock();
                                            //$(\'#add_property_note\').val(\'\');
                                        });
                                  }
                                  else
                                  {
                                      jQuery(\'#search_propertyhive_contacts_results\').html(\'' . __('Keep on typing...', 'propertyhive') . '\');
                                  }
                              }
                          });
                      });
                  </script>';
        echo '<div id="add_new_property_owner_contact" style="display:none;">';
        echo '<a href="#" class="button right search-property-owner-contacts">&lt; ' . __('Search Existing Contacts', 'propertyhive') . '</a>';
        echo '<h4>' . __('Name', 'propertyhive') . '</h4>';
        propertyhive_wp_text_input(array('id' => '_owner_name', 'label' => __('Full Name', 'propertyhive'), 'desc_tip' => false, 'placeholder' => __('e.g. Mr & Mrs Jones, Ms Jane Smith', 'propertyhive'), 'type' => 'text'));
        echo '<h4>' . __('Correspondence Address', 'propertyhive') . ' (<a href="" class="use-property-address">Use Property Address</a>)</h4>';
        propertyhive_wp_text_input(array('id' => '_owner_address_name_number', 'label' => __('Building Name / Number', 'propertyhive'), 'desc_tip' => false, 'placeholder' => __('e.g. Thistle Cottage, or Flat 10', 'propertyhive'), 'type' => 'text'));
        propertyhive_wp_text_input(array('id' => '_owner_address_street', 'label' => __('Street', 'propertyhive'), 'desc_tip' => false, 'placeholder' => __('e.g. High Street', 'propertyhive'), 'type' => 'text'));
        propertyhive_wp_text_input(array('id' => '_owner_address_two', 'label' => __('Address Line 2', 'propertyhive'), 'desc_tip' => false, 'type' => 'text'));
        propertyhive_wp_text_input(array('id' => '_owner_address_three', 'label' => __('Town / City', 'propertyhive'), 'desc_tip' => false, 'type' => 'text'));
        propertyhive_wp_text_input(array('id' => '_owner_address_four', 'label' => __('County / State', 'propertyhive'), 'desc_tip' => false, 'type' => 'text'));
        propertyhive_wp_text_input(array('id' => '_owner_address_postcode', 'label' => __('Postcode / Zip Code', 'propertyhive'), 'desc_tip' => false, 'type' => 'text'));
        $countries = get_option('propertyhive_countries', array('GB'));
        // Get all countries
        $owner_country = get_option('propertyhive_default_country', 'GB');
        // get default
        if (empty($countries) || count($countries) < 2) {
            propertyhive_wp_hidden_input(array('id' => '_owner_address_country', 'value' => $owner_country));
        } else {
            $ph_countries = new PH_Countries();
            // Can't use $this->countries because we're inside a static method
            $country_options = array();
            foreach ($countries as $country_code) {
                $country = $ph_countries->get_country($country_code);
                if ($country !== false) {
                    $country_options[$country_code] = $country['name'];
                }
            }
            propertyhive_wp_select(array('id' => '_owner_address_country', 'label' => __('Country', 'propertyhive'), 'desc_tip' => false, 'options' => $country_options, 'value' => $owner_country));
        }
        echo '<h4>' . __('Contact Details', 'propertyhive') . '</h4>';
        propertyhive_wp_text_input(array('id' => '_owner_telephone_number', 'label' => __('Telephone Number', 'propertyhive'), 'desc_tip' => false, 'type' => 'text'));
        propertyhive_wp_text_input(array('id' => '_owner_email_address', 'label' => __('Email Address', 'propertyhive'), 'desc_tip' => true, 'description' => __('If the contact has multiple email addresses simply separate them using a comma', 'propertyhive'), 'type' => 'text'));
        echo '</div>';
        do_action('propertyhive_property_owner_fields');
        echo '<div id="existing-owner-details"' . ($owner_contact_id == '' ? ' style="display:none"' : '') . '>';
        echo '</div>';
        echo '</div>';
        echo '</div>';
        echo '<script>

          jQuery(document).ready(function()
          {
              jQuery(\'a.use-property-address\').click(function()
              {
                  jQuery(\'#_owner_address_name_number\').val( jQuery(\'#_address_name_number\').val() );
                  jQuery(\'#_owner_address_street\').val( jQuery(\'#_address_street\').val() );
                  jQuery(\'#_owner_address_two\').val( jQuery(\'#_address_two\').val() );
                  jQuery(\'#_owner_address_three\').val( jQuery(\'#_address_three\').val() );
                  jQuery(\'#_owner_address_four\').val( jQuery(\'#_address_four\').val() );
                  jQuery(\'#_owner_address_postcode\').val( jQuery(\'#_address_postcode\').val() );
                  jQuery(\'#_owner_address_country\').val( jQuery(\'#_address_country\').val() );

                  return false;
              });
          });

        </script>';
        $post = $original_post;
        $thepostid = $original_thepostid;
        setup_postdata($post);
    }
    /**
     * Output the metabox
     */
    public static function output($post, $args = array())
    {
        global $wpdb, $thepostid;
        $thepostid = $post->ID;
        $original_post = $post;
        $original_thepostid = $thepostid;
        // Used in the scenario where this meta box isn't used on the property edit page
        if (isset($args['args']['property_post'])) {
            $post = $args['args']['property_post'];
            $thepostid = $post->ID;
            setup_postdata($post);
        }
        wp_nonce_field('propertyhive_save_data', 'propertyhive_meta_nonce');
        echo '<div class="propertyhive_meta_box">';
        echo '<div class="options_group">';
        $post_parent_id = isset($post->post_parent) ? $post->post_parent : 0;
        $parent_post = false;
        if (isset($_GET['post_parent']) && $_GET['post_parent'] != '') {
            $post_parent_id = $_GET['post_parent'];
            $parent_post = $post_parent_id;
        }
        propertyhive_wp_hidden_input(array('id' => 'post_parent', 'value' => $post_parent_id));
        $args = array('id' => '_reference_number', 'label' => __('Reference Number', 'propertyhive'), 'desc_tip' => false, 'type' => 'text');
        if ($parent_post !== FALSE) {
            $args['value'] = get_post_meta($parent_post, '_reference_number', TRUE);
        }
        propertyhive_wp_text_input($args);
        $args = array('id' => '_address_name_number', 'label' => __('Building Name / Number', 'propertyhive'), 'desc_tip' => false, 'placeholder' => __('e.g. Thistle Cottage, or Flat 10', 'propertyhive'), 'type' => 'text');
        if ($parent_post !== FALSE) {
            $args['value'] = get_post_meta($parent_post, '_address_name_number', TRUE);
        }
        propertyhive_wp_text_input($args);
        $args = array('id' => '_address_street', 'label' => __('Street', 'propertyhive'), 'desc_tip' => false, 'placeholder' => __('e.g. High Street', 'propertyhive'), 'type' => 'text');
        if ($parent_post !== FALSE) {
            $args['value'] = get_post_meta($parent_post, '_address_street', TRUE);
        }
        propertyhive_wp_text_input($args);
        $args = array('id' => '_address_two', 'label' => __('Address Line 2', 'propertyhive'), 'desc_tip' => false, 'type' => 'text');
        if ($parent_post !== FALSE) {
            $args['value'] = get_post_meta($parent_post, '_address_two', TRUE);
        }
        propertyhive_wp_text_input($args);
        $args = array('id' => '_address_three', 'label' => __('Town / City', 'propertyhive'), 'desc_tip' => false, 'type' => 'text');
        if ($parent_post !== FALSE) {
            $args['value'] = get_post_meta($parent_post, '_address_three', TRUE);
        }
        propertyhive_wp_text_input($args);
        $args = array('id' => '_address_four', 'label' => __('County / State', 'propertyhive'), 'desc_tip' => false, 'type' => 'text');
        if ($parent_post !== FALSE) {
            $args['value'] = get_post_meta($parent_post, '_address_four', TRUE);
        }
        propertyhive_wp_text_input($args);
        $args = array('id' => '_address_postcode', 'label' => __('Postcode / Zip Code', 'propertyhive'), 'desc_tip' => false, 'type' => 'text');
        if ($parent_post !== FALSE) {
            $args['value'] = get_post_meta($parent_post, '_address_postcode', TRUE);
        }
        propertyhive_wp_text_input($args);
        // Country dropdown
        $countries = get_option('propertyhive_countries', array('GB'));
        $property_country = get_post_meta($thepostid, '_address_country', TRUE);
        $default_country = get_option('propertyhive_default_country', 'GB');
        $country_js = array();
        if ($property_country == '') {
            $property_country = $default_country;
        }
        // Make sure country is in list of countries we operate in
        if (!in_array($property_country, $countries)) {
            $property_country = $default_country;
        }
        if (empty($countries) || count($countries) < 2) {
            if (count($countries) == 1) {
                $ph_countries = new PH_Countries();
                $country = $ph_countries->get_country($countries[0]);
                $country_js[$countries[0]] = $country;
            }
            $args = array('id' => '_address_country', 'value' => $property_country);
            if ($parent_post !== FALSE) {
                $args['value'] = get_post_meta($parent_post, '_address_country', TRUE);
            }
            propertyhive_wp_hidden_input($args);
        } else {
            $ph_countries = new PH_Countries();
            // Can't use $this->countries because we're inside a static method
            $country_options = array();
            foreach ($countries as $country_code) {
                $country = $ph_countries->get_country($country_code);
                if ($country !== false) {
                    $country_options[$country_code] = $country['name'];
                    $country_js[$country_code] = $country;
                }
            }
            $args = array('id' => '_address_country', 'label' => __('Country', 'propertyhive'), 'desc_tip' => false, 'options' => $country_options, 'value' => $property_country);
            if ($parent_post !== FALSE) {
                $args['value'] = get_post_meta($parent_post, '_address_country', TRUE);
            }
            propertyhive_wp_select($args);
        }
        // Location
        $options = array('' => '');
        $args = array('hide_empty' => false, 'parent' => 0);
        $terms = get_terms('location', $args);
        $selected_value = '';
        if (!empty($terms) && !is_wp_error($terms)) {
            foreach ($terms as $term) {
                $options[$term->term_id] = $term->name;
                $args = array('hide_empty' => false, 'parent' => $term->term_id);
                $subterms = get_terms('location', $args);
                if (!empty($subterms) && !is_wp_error($subterms)) {
                    foreach ($subterms as $term) {
                        $options[$term->term_id] = '- ' . $term->name;
                        $args = array('hide_empty' => false, 'parent' => $term->term_id);
                        $subsubterms = get_terms('location', $args);
                        if (!empty($subsubterms) && !is_wp_error($subsubterms)) {
                            foreach ($subsubterms as $term) {
                                $options[$term->term_id] = '- ' . $term->name;
                            }
                        }
                    }
                }
            }
            $term_list = wp_get_post_terms($post->ID, 'location', array("fields" => "ids"));
            if (!is_wp_error($term_list) && is_array($term_list) && !empty($term_list)) {
                $selected_value = $term_list[0];
            }
        }
        ?>
<p class="form-field"><label for="location_id"><?php 
        _e('Location', 'propertyhive');
        ?>
</label>
        <select id="location_id" name="location_id[]" multiple="multiple" data-placeholder="<?php 
        _e('Select location(s)', 'propertyhive');
        ?>
" class="multiselect attribute_values">
            <?php 
        $options = array('' => '');
        $args = array('hide_empty' => false, 'parent' => 0);
        $terms = get_terms('location', $args);
        $selected_values = array();
        $term_list = wp_get_post_terms($post->ID, 'location', array("fields" => "ids"));
        if (!is_wp_error($term_list) && is_array($term_list) && !empty($term_list)) {
            foreach ($term_list as $term_id) {
                $selected_values[] = $term_id;
            }
        }
        if (!empty($terms) && !is_wp_error($terms)) {
            foreach ($terms as $term) {
                $options[$term->term_id] = $term->name;
                echo '<option value="' . esc_attr($term->term_id) . '"';
                if (in_array($term->term_id, $selected_values)) {
                    echo ' selected';
                }
                echo '>' . esc_html($term->name) . '</option>';
                $args = array('hide_empty' => false, 'parent' => $term->term_id);
                $subterms = get_terms('location', $args);
                if (!empty($subterms) && !is_wp_error($subterms)) {
                    foreach ($subterms as $term) {
                        echo '<option value="' . esc_attr($term->term_id) . '"';
                        if (in_array($term->term_id, $selected_values)) {
                            echo ' selected';
                        }
                        echo '>- ' . esc_html($term->name) . '</option>';
                        $args = array('hide_empty' => false, 'parent' => $term->term_id);
                        $subsubterms = get_terms('location', $args);
                        if (!empty($subsubterms) && !is_wp_error($subsubterms)) {
                            foreach ($subsubterms as $term) {
                                echo '<option value="' . esc_attr($term->term_id) . '"';
                                if (in_array($term->term_id, $selected_values)) {
                                    echo ' selected';
                                }
                                echo '>- - ' . esc_html($term->name) . '</option>';
                            }
                        }
                    }
                }
            }
        }
        ?>
        </select>
<?php 
        do_action('propertyhive_property_address_fields');
        echo '</div>';
        echo '</div>';
        echo '
        <script>
            
            var countries = ' . json_encode($country_js) . ';

            // Change currency symbol shown on sales and lettings details meta boxes
            function countryChange(country_code)
            {
                if (typeof countries[country_code] != \'undefined\')
                {
                    jQuery(\'.currency-symbol\').html(countries[country_code].currency_symbol);
                }
                else
                {
                    jQuery(\'.currency-symbol\').html(countries[jQuery(\'#_address_country\').val()].currency_symbol);
                }
            }

            jQuery(document).ready(function()
            {
                countryChange(jQuery(\'#_address_country\').val());

                jQuery(\'select[id=\\\'_address_country\\\']\').change(function()
                {
                    countryChange(jQuery(this).val());
                });

                if (jQuery(\'#title\').length > 0)
                {
                    jQuery(\'#title\').change(function()
                    {
                        // Check title contains something
                        if (jQuery(\'#title\').val() != \'\')
                        {
                            // Check all address fields are empty so we don\'t override anything should the user have customised it already
                            
                            if (jQuery(\'#_address_name_number\').val() == \'\' && jQuery(\'#_address_street\').val() == \'\' && jQuery(\'#_address_two\').val() == \'\' && jQuery(\'#_address_three\').val() == \'\' && jQuery(\'#_address_four\').val() == \'\' && jQuery(\'#_address_postcode\').val() == \'\')
                            {
                                // Yep. All address fields are empty
                                
                                // See if any of the locations can be set
                                jQuery("#location_id > option").each(function() 
                                {
                                    if (this.text != \'\')
                                    {
                                        var text_to_search_for = this.text.replace(\'- \', \'\');
                                        if (jQuery(\'#title\').val().indexOf(text_to_search_for) != -1)
                                        {
                                            this.selected = true;
                                        }
                                    }
                                });
                                
                                // Split address and fill related address field
                                
                                var address_fields = [
                                    \'_address_name_number\',
                                    \'_address_street\',
                                    \'_address_two\',
                                    \'_address_three\',
                                    \'_address_four\',
                                    \'_address_postcode\'
                                ];
                                
                                // Split title by comma
                                var explode_title = jQuery(\'#title\').val().split(\',\');
                                for (var i in explode_title)
                                {
                                    var title_element = jQuery.trim(explode_title[i]); // Trim it to remove any white space either side
                                    
                                    if (title_element != \'\' && address_fields.length > 0)
                                    {
                                        if ( i == 0 )
                                        {
                                            var split_title_element = title_element.split(\' \');
                                            if (jQuery.isNumeric( title_element ) || jQuery.isNumeric( split_title_element[0] )) // check if this is a house number
                                            {
                                                jQuery(\'#\' + address_fields[0]).val(split_title_element[0]);
                                                
                                                title_element = title_element.replace(split_title_element[0], \'\', title_element);
                                                title_element = jQuery.trim(title_element);
                                                
                                                jQuery(\'#\' + address_fields[1]).val(title_element);
                                                address_fields.splice(0,2);
                                            }
                                            else
                                            {
                                                jQuery(\'#\' + address_fields[1]).val(title_element);
                                                address_fields.splice(0,2);
                                            }
                                        }
                                        else
                                        {
                                            var split_title_elements = title_element.split(\' \');
                                            
                                            var numeric_matches = title_element.match(/\\d+/g);
                                            if (i == explode_title.length-1 &&  numeric_matches != null)
                                            {
                                                // We\'re on the last bit and it contains a number
                                                for (var j in split_title_elements)
                                                {
                                                    var split_title_element = jQuery.trim(split_title_elements[j]);
                                                    
                                                    var numeric_matches = split_title_element.match(/\\d+/g);
                                                    
                                                    if (split_title_element.length >=2 && split_title_element.length <= 4 && numeric_matches != null)
                                                    {
                                                        // This bit of the address element definitely contains postcode bit
                                                        var postcode = split_title_element;
                                                        if (j == (split_title_elements.length - 2))
                                                        {
                                                            var temp_title_element = jQuery.trim(split_title_elements[split_title_elements.length-1]); // Trim it to remove any white space either side
                                                            
                                                            if ((temp_title_element.length >=2 || temp_title_element.length <= 4))
                                                            {
                                                                // We have one element left after this
                                                                postcode += \' \' + temp_title_element;
                                                            }
                                                        }
                                                        jQuery(\'#address_postcode\').val(postcode);
                                                        
                                                        break;
                                                    }
                                                    else
                                                    {
                                                        // General address element
                                                        jQuery(\'#\' + address_fields[0]).val(title_element);
                                                        address_fields.splice(0,1);
                                                    }
                                                }
                                                
                                            }
                                            else
                                            {
                                                // General address element
                                                jQuery(\'#\' + address_fields[0]).val(title_element);
                                                address_fields.splice(0,1);
                                            }
                                        }
                                    }
                                }

                                jQuery(\'#_address_postcode\').trigger(\'change\');
                            }
                        }
                    });
                }
            });
        
        </script>
        ';
        $post = $original_post;
        $thepostid = $original_thepostid;
        setup_postdata($post);
    }
 /**
  * Get the formatted deposit
  *
  * @access public
  * @return string
  */
 public function get_formatted_deposit()
 {
     $ph_countries = new PH_Countries();
     $currency = $ph_countries->get_currency($this->_currency);
     $prefix = $currency['currency_prefix'] ? $currency['currency_symbol'] : '';
     $suffix = !$currency['currency_prefix'] ? $currency['currency_symbol'] : '';
     return $prefix . number_format($this->_deposit, 0) . $suffix;
 }
 /**
  * Save meta box data
  */
 public static function save($post_id, $post)
 {
     global $wpdb;
     // Only save meta info if department is 'residential-lettings'
     $department = get_post_meta($post_id, '_department', TRUE);
     if ($department == 'residential-lettings') {
         update_post_meta($post_id, '_currency', $_POST['_rent_currency']);
         $rent = preg_replace("/[^0-9.]/", '', $_POST['_rent']);
         update_post_meta($post_id, '_rent', $rent);
         update_post_meta($post_id, '_rent_frequency', $_POST['_rent_frequency']);
         // Store price in common currency (GBP) and frequency (PCM) used for ordering
         $ph_countries = new PH_Countries();
         $ph_countries->update_property_price_actual($post_id);
         update_post_meta($post_id, '_poa', isset($_POST['_rent_poa']) ? $_POST['_rent_poa'] : '');
         update_post_meta($post_id, '_deposit', preg_replace("/[^0-9.]/", '', $_POST['_deposit']));
         update_post_meta($post_id, '_available_date', $_POST['_available_date']);
         if (!empty($_POST['furnished_id'])) {
             wp_set_post_terms($post_id, $_POST['furnished_id'], 'furnished');
         } else {
             // Setting to blank
             wp_delete_object_term_relationships($post_id, 'furnished');
         }
         do_action('propertyhive_save_property_residential_lettings_details', $post_id);
     }
 }
 /**
  * Save meta box data
  */
 public static function save($post_id, $post)
 {
     global $wpdb;
     // Only save meta info if department is 'residential-sales'
     $department = get_post_meta($post_id, '_department', TRUE);
     if ($department == 'residential-sales') {
         update_post_meta($post_id, '_currency', $_POST['_price_currency']);
         $price = preg_replace("/[^0-9]/", '', $_POST['_price']);
         update_post_meta($post_id, '_price', $price);
         // Store price in common currency (GBP) used for ordering
         $ph_countries = new PH_Countries();
         $ph_countries->update_property_price_actual($post_id);
         update_post_meta($post_id, '_poa', isset($_POST['_sale_poa']) ? $_POST['_sale_poa'] : '');
         if (!empty($_POST['price_qualifier_id'])) {
             wp_set_post_terms($post_id, $_POST['price_qualifier_id'], 'price_qualifier');
         } else {
             // Setting to blank
             wp_delete_object_term_relationships($post_id, 'price_qualifier');
         }
         if (!empty($_POST['sale_by_id'])) {
             wp_set_post_terms($post_id, $_POST['sale_by_id'], 'sale_by');
         } else {
             // Setting to blank
             wp_delete_object_term_relationships($post_id, 'sale_by');
         }
         if (!empty($_POST['tenure_id'])) {
             wp_set_post_terms($post_id, $_POST['tenure_id'], 'tenure');
         } else {
             // Setting to blank
             wp_delete_object_term_relationships($post_id, 'tenure');
         }
         do_action('propertyhive_save_property_residential_sales_details', $post_id);
     }
 }