/**
  * 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>';
 }
/**
 * Output a file input box.
 *
 * @access public
 * @param array $field
 * @return void
 */
function propertyhive_wp_photo_upload($field)
{
    global $thepostid, $post, $propertyhive;
    $thepostid = empty($thepostid) ? $post->ID : $thepostid;
    $field['id'] = isset($field['id']) ? $field['id'] : '';
    $field['button_label'] = isset($field['button_label']) ? $field['button_label'] : __('Select Photo', 'propertyhive');
    $field['class'] = isset($field['class']) ? $field['class'] : 'short';
    $field['wrapper_class'] = isset($field['wrapper_class']) ? $field['wrapper_class'] : '';
    $field['value'] = isset($field['value']) ? $field['value'] : get_post_meta($thepostid, $field['id'], true);
    $field['name'] = isset($field['name']) ? $field['name'] : $field['id'];
    $data_type = empty($field['data_type']) ? '' : $field['data_type'];
    // Custom attribute handling
    $custom_attributes = array();
    if (!empty($field['custom_attributes']) && is_array($field['custom_attributes'])) {
        foreach ($field['custom_attributes'] as $attribute => $value) {
            $custom_attributes[] = esc_attr($attribute) . '="' . esc_attr($value) . '"';
        }
    }
    propertyhive_wp_hidden_input($field);
    echo '
	<p class="form-field ' . esc_attr($field['id']) . '_field ' . esc_attr($field['wrapper_class']) . '"';
    if ($field['value'] == '') {
        echo ' style="display:none;"';
    }
    echo '>
	   <label for="' . esc_attr($field['id']) . '">' . __('Uploaded', 'propertyhive') . ' ' . wp_kses_post($field['label']) . '</label>
	   <span>';
    if ($field['value'] != '') {
        $image = wp_get_attachment_image_src($field['value'], 'thumbnail');
        if ($image !== FALSE) {
            echo '<img src="' . $image[0] . '" width="150" alt="">';
        } else {
            echo 'Image doesn\'t exist';
        }
    }
    echo '</span>
	</p>';
    echo '
	<p class="form-field ' . esc_attr($field['id']) . '_field ' . esc_attr($field['wrapper_class']) . '">
	   <label for="' . esc_attr($field['id']) . '">' . wp_kses_post($field['label']) . '</label>
	   <a href="" class="button button-primary ph_upload_photo_button' . $field['id'] . '">' . $field['button_label'] . '</a>';
    if (!empty($field['description'])) {
        if (isset($field['desc_tip']) && false !== $field['desc_tip']) {
            echo '<img class="help_tip" data-tip="' . esc_attr($field['description']) . '" src="' . esc_url(PH()->plugin_url()) . '/assets/images/help.png" height="16" width="16" />';
        } else {
            echo '<span class="description">' . wp_kses_post($field['description']) . '</span>';
        }
    }
    echo '</p>';
    echo '<script>

		var file_frame' . $field['id'] . ';

		jQuery(document).ready(function()
        {
        	jQuery(\'.ph_upload_photo_button' . $field['id'] . '\').live(\'click\', function( event ){
                 
	            event.preventDefault();
	         
	            // If the media frame already exists, reopen it.
	            if ( file_frame' . $field['id'] . ' ) {
	              file_frame' . $field['id'] . '.open();
	              return;
	            }
	         
	            // Create the media frame.
	            file_frame' . $field['id'] . ' = wp.media.frames.file_frame' . $field['id'] . ' = wp.media({
	              title: jQuery( this ).data( \'uploader_title\' ),
	              button: {
	                text: jQuery( this ).data( \'uploader_button_text\' ),
	              },
	              multiple: false  // Set to true to allow multiple files to be selected
	            });
	         
	            // When an image is selected, run a callback.
	            file_frame' . $field['id'] . '.on( \'select\', function() {
	                var selection = file_frame' . $field['id'] . '.state().get(\'selection\');

	                selection.map( function( attachment ) {
	             
	                    attachment = attachment.toJSON();
	             
	                    // Do something with attachment.id and/or attachment.url here
	                    console.log(attachment.url);
	                    
	                    // Add selected image to page
	                    //add_photo_attachment_to_grid(attachment);

	                    jQuery(\'.form-field.' . esc_attr($field['id']) . '_field\').show();
	                    jQuery(\'.form-field.' . esc_attr($field['id']) . '_field span\').html(\'<img src="\' + attachment.url + \'" width="150" alt="">\');
	                    jQuery(\'#' . esc_attr($field['id']) . '\').val(attachment.id);
	                });
	            });
	         
	            // Finally, open the modal
	            file_frame' . $field['id'] . '.open();
	        });
		});

	</script>';
}
    /**
     * 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);
    }