/**
  * 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 the metabox
  */
 public static function output($post)
 {
     global $post, $wpdb, $thepostid;
     echo '<div class="propertyhive_meta_box">';
     echo '<div class="options_group">';
     propertyhive_wp_text_input(array('id' => '_telephone_number', 'label' => __('Telephone Number', 'propertyhive'), 'desc_tip' => false, 'type' => 'text'));
     propertyhive_wp_text_input(array('id' => '_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'));
     propertyhive_wp_checkboxes(array('id' => '_forbidden_contact_methods', 'label' => __('Do Not Contact Via', 'propertyhive'), 'options' => array('telephone' => 'Telephone', 'email' => 'Email')));
     propertyhive_wp_textarea_input(array('id' => '_contact_notes', 'label' => __('Contact Notes', 'propertyhive'), 'desc_tip' => false, 'placeholder' => __('e.g. Works nights so do not call between 11am and 2pm', 'propertyhive')));
     do_action('propertyhive_contact_contact_details_fields');
     echo '</div>';
     echo '</div>';
 }
    /**
     * 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)
 {
     echo '<div class="propertyhive_meta_box">';
     echo '<div class="options_group">';
     echo '<div id="property_descriptions">';
     $num_property_descriptions = get_post_meta($post->ID, '_descriptions', TRUE);
     if ($num_property_descriptions == '') {
         $num_property_descriptions = 0;
     }
     for ($i = 0; $i < $num_property_descriptions; ++$i) {
         $description_name = get_post_meta($post->ID, '_description_name_' . $i, TRUE);
         echo '<div class="room">';
         echo '<h3>
                         <button type="button" class="remove_description button">' . __('Remove', 'propertyhive') . '</button>
                         <div class="handlediv" title="' . __('Click to toggle', 'propertyhive') . '"></div>
                         <strong>' . ($description_name != '' ? $description_name : '(' . __('untitled', 'propertyhive') . ')') . '</strong>
                     </h3>';
         echo '<div class="room-details">';
         // Description Title
         propertyhive_wp_text_input(array('id' => '', 'name' => '_description_name[]', 'label' => __('Description Title', 'propertyhive'), 'desc_tip' => false, 'value' => $description_name, 'placeholder' => __('e.g. Location, Business Rates, Parking', 'propertyhive'), 'type' => 'text'));
         // Description
         propertyhive_wp_textarea_input(array('id' => '', 'name' => '_description[]', 'label' => __('Description', 'propertyhive'), 'desc_tip' => false, 'class' => '', 'value' => get_post_meta($post->ID, '_description_' . $i, TRUE), 'custom_attributes' => array('style' => 'width:100%;')));
         echo '</div>';
         echo '</div>';
     }
     echo '</div>';
     echo '<div id="property_description_template" style="display:none">';
     echo '<div class="room">';
     echo '<h3>
                     <button type="button" class="remove_description button">' . __('Remove', 'propertyhive') . '</button>
                     <div class="handlediv" title="' . __('Click to toggle', 'propertyhive') . '"></div>
                     <strong>Description Title Here</strong>
                 </h3>';
     echo '<div class="room-details">';
     // Description Title
     propertyhive_wp_text_input(array('id' => '', 'name' => '_description_name[]', 'label' => __('Description Title', 'propertyhive'), 'desc_tip' => false, 'value' => '', 'placeholder' => __('e.g. Location, Business Rates, Parking', 'propertyhive'), 'type' => 'text'));
     // Description
     propertyhive_wp_textarea_input(array('id' => '', 'name' => '_description[]', 'label' => __('Description', 'propertyhive'), 'desc_tip' => false, 'class' => '', 'value' => '', 'custom_attributes' => array('style' => 'width:100%;')));
     echo '</div>';
     echo '</div>';
     echo '</div>';
     echo '<p class="form-field">
                 <label for="">&nbsp;</label>
                 <a href="#" class="button button-primary add_property_description"><span class="fa fa-plus"></span> Add Description</a>
             </p>';
     do_action('propertyhive_property_description_fields');
     echo '</div>';
     echo '</div>';
     echo '<script>
         
         jQuery(document).ready(function()
         {
             jQuery(\'#property_descriptions\').on(\'keyup\', \'input[name=\\\'_description_name[]\\\']\', function()
             {
                 var description_name = jQuery(this).val();
                 if (description_name == \'\')
                 {
                     description_name = \'(' . __('untitled', 'propertyhive') . ')\';
                 }
                 jQuery(this).parent().parent().parent().children(\'h3\').children(\'strong\').html(description_name);
             });
             
             jQuery(\'.add_property_description\').click(function()
             {
                 var description_template = jQuery(\'#property_description_template\').html();
                 
                 jQuery(\'#property_descriptions\').append(description_template);
                 
                 return false;
             });
             
             jQuery(document).on(\'click\', \'.remove_description\', function()
             {
                 jQuery(this).parent().parent().fadeOut(\'slow\', function()
                 {
                     jQuery(this).remove();
                 });
                 
                 return false;
             });
         });
         
     </script>';
     echo '
     <script>
         
         jQuery(document).ready(function()
         {
             //showHideDescriptionsMetaBox();
             
             jQuery(\'input[type=\\\'radio\\\'][name=\\\'_department\\\']\').change(function()
             {
                  //showHideDescriptionsMetaBox();
             });
         });
         
         function showHideDescriptionsMetaBox()
         {
              var selectedDepartment = jQuery(\'input[type=\\\'radio\\\'][name=\\\'_department\\\']:checked\').val();
              
              if (selectedDepartment == \'commercial\')
              {
                 jQuery(\'#propertyhive-property-description\').show();
              }
              else
              {
                 jQuery(\'#propertyhive-property-description\').hide();
              }
         }
         
     </script>';
 }
    /**
     * Output the metabox
     */
    public static function output($post)
    {
        global $post, $wpdb, $thepostid;
        $total_profiles = 0;
        $owner_profiles = array();
        // get properties where this is the owner
        $args = array('post_type' => 'property', 'meta_query' => array(array('key' => '_owner_contact_id', 'value' => $post->ID, 'compare' => '=')));
        $property_query = new WP_Query($args);
        if ($property_query->have_posts()) {
            while ($property_query->have_posts()) {
                $property_query->the_post();
                $owner_profiles[] = $post;
                ++$total_profiles;
            }
        }
        wp_reset_postdata();
        $applicant_profiles = array();
        $num_applicant_profiles = get_post_meta($thepostid, '_applicant_profiles', TRUE);
        if ($num_applicant_profiles == '') {
            $num_applicant_profiles = 0;
        }
        if ($num_applicant_profiles > 0) {
            $total_profiles += $num_applicant_profiles;
            for ($i = 0; $i < $num_applicant_profiles; ++$i) {
                $applicant_profiles[] = get_post_meta($thepostid, '_applicant_profile_' . $i, TRUE);
            }
        }
        $third_party_profiles = array();
        $third_party_categories = get_post_meta($thepostid, '_third_party_categories', TRUE);
        if (is_array($third_party_categories) && !empty($third_party_categories)) {
            $ph_third_party_contacts = new PH_Third_Party_Contacts();
            foreach ($third_party_categories as $third_party_category) {
                $third_party_profiles[] = $third_party_category;
                ++$total_profiles;
            }
        }
        echo '<div class="propertyhive_meta_box">';
        echo '<div class="panel-wrap">
            
            <div class="ph-tabs-back"></div>

                <ul class="contact_data_tabs ph-tabs">';
        $tab = 0;
        foreach ($owner_profiles as $property_post) {
            $owner_type = __('Property Owner', 'propertyhive');
            $department = get_post_meta($property_post->ID, '_department', TRUE);
            if ($department == 'lettings') {
                $owner_type = __('Property Landlord', 'propertyhive');
            }
            echo '<li class="property_tab' . ($tab == 0 ? ' active' : '') . '">
                        <a href="#tab_property_data_' . $property_post->ID . '">' . $owner_type . '</a>
                    </li>';
            ++$tab;
        }
        foreach ($applicant_profiles as $key => $applicant_profile) {
            $label = __('New Applicant', 'propertyhive');
            if (isset($applicant_profile['department']) && $applicant_profile['department'] == 'residential-sales') {
                $label = __('Sales Applicant', 'propertyhive');
            } elseif (isset($applicant_profile['department']) && $applicant_profile['department'] == 'residential-lettings') {
                $label = __('Lettings Applicant', 'propertyhive');
            } elseif (isset($applicant_profile['department']) && $applicant_profile['department'] == 'commercial') {
                $label = __('Commercial Applicant', 'propertyhive');
            }
            echo '<li class="property_tab' . ($tab == 0 ? ' active' : '') . '">
                        <a href="#tab_applicant_data_' . $key . '">' . $label . '</a>
                    </li>';
            ++$tab;
        }
        foreach ($third_party_profiles as $key => $third_party_profile) {
            $label = __('New Third Party', 'propertyhive');
            if ($third_party_profile != '' && $third_party_profile != 0) {
                $category_name = $ph_third_party_contacts->get_category($third_party_profile);
                if ($category_name !== false) {
                    $label = $category_name;
                }
            }
            echo '<li class="property_tab' . ($tab == 0 ? ' active' : '') . '">
                        <a href="#tab_third_party_data_' . $key . '">' . $label . '</a>
                    </li>';
            ++$tab;
        }
        echo '<li class="property_tab' . ($tab == 0 ? ' active' : '') . '">
                        <a href="#tab_add_relationship">' . __('Add Relationship', 'propertyhive') . '</a>
                    </li>';
        echo '</ul>';
        $contact_id = $thepostid;
        $tab = 0;
        foreach ($owner_profiles as $property_post) {
            $the_property = new PH_Property($property_post->ID);
            echo '<div id="tab_property_data_' . $property_post->ID . '" class="panel propertyhive_options_panel" style="' . ($tab == 0 ? 'display:block;' : 'display:none;') . '">
                        <div class="options_group" style="float:left; width:100%;">';
            echo '<p class="form-field">';
            echo '<label>' . __('Address', 'propertyhive') . '</label>';
            echo $the_property->get_formatted_summary_address('<br>');
            echo '</p>';
            echo '<p class="form-field">';
            echo '<label>' . __('Price', 'propertyhive') . '</label>';
            echo $the_property->get_formatted_price();
            echo '</p>';
            echo '<p class="form-field">';
            echo '<label>' . __('Bedrooms', 'propertyhive') . '</label>';
            echo $the_property->_bedrooms;
            echo '</p>';
            echo '<p class="form-field">';
            echo '<label>' . __('Status', 'propertyhive') . '</label>';
            echo $the_property->_on_market == 'yes' ? __('On Market', 'propertyhive') : __('Not On Market', 'propertyhive');
            echo '</p>';
            echo '<p class="form-field">';
            echo '<label></label>';
            echo '<a href="' . get_edit_post_link($property_post->ID) . '" class="button">' . __('View Property Record', 'propertyhive') . '</a>';
            echo '</p>';
            echo '
                        </div>
                    </div>';
            ++$tab;
        }
        foreach ($applicant_profiles as $key => $applicant_profile) {
            echo '<div id="tab_applicant_data_' . $key . '" class="panel propertyhive_options_panel" style="' . ($tab == 0 ? 'display:block;' : 'display:none;') . '">
                        
                        <div class="options_group applicant-fields-' . $key . '" style="float:left; width:100%;">';
            $departments = array();
            if (get_option('propertyhive_active_departments_sales') == 'yes') {
                $departments['residential-sales'] = __('Residential Sales', 'propertyhive');
            }
            if (get_option('propertyhive_active_departments_lettings') == 'yes') {
                $departments['residential-lettings'] = __('Residential Lettings', 'propertyhive');
            }
            if (get_option('propertyhive_active_departments_commercial') == 'yes') {
                $departments['commercial'] = __('Commercial', 'propertyhive');
            }
            $value = isset($applicant_profile['department']) && $applicant_profile['department'] != '' ? $applicant_profile['department'] : get_option('propertyhive_primary_department');
            $args = array('id' => '_applicant_department_' . $key, 'label' => 'Looking For', 'value' => $value, 'options' => $departments);
            if (count($departments) == 1) {
                foreach ($departments as $department_key => $value) {
                    $args['value'] = $department_key;
                }
            }
            propertyhive_wp_radio($args);
            echo '<div class="propertyhive-applicant-residential-sales-details-' . $key . '">';
            // Price
            propertyhive_wp_text_input(array('id' => '_applicant_maximum_price_' . $key, 'label' => __('Maximum Price', 'propertyhive') . ' (&pound;)', 'desc_tip' => false, 'type' => 'text', 'class' => '', 'custom_attributes' => array('style' => 'width:100%; max-width:150px;'), 'value' => isset($applicant_profile['max_price']) ? $applicant_profile['max_price'] : ''));
            echo '</div>';
            echo '<div class="propertyhive-applicant-residential-lettings-details-' . $key . '">';
            // Rent / Rent Frequency
            $rent_frequency = isset($applicant_profile['rent_frequency']) ? $applicant_profile['rent_frequency'] : '';
            echo '<p class="form-field rent_field ">
                        
                            <label for="_applicant_maximum_rent_' . $key . '">' . __('Maximum Rent', 'propertyhive') . ' (&pound;)</label>
                            
                            <input type="text" class="" name="_applicant_maximum_rent_' . $key . '" id="_applicant_maximum_rent_' . $key . '" value="' . (isset($applicant_profile['max_rent']) ? $applicant_profile['max_rent'] : '') . '" placeholder="" style="width:20%; max-width:150px;">
                            
                            <select id="_applicant_rent_frequency_' . $key . '" name="_applicant_rent_frequency_' . $key . '" class="select short">
                                <option value="pw"' . ($rent_frequency == 'pw' ? ' selected' : '') . '>' . __('Per Week', 'propertyhive') . '</option>
                                <option value="pcm"' . ($rent_frequency == 'pcm' || $rent_frequency == '' ? ' selected' : '') . '>' . __('Per Calendar Month', 'propertyhive') . '</option>
                                <option value="pq"' . ($rent_frequency == 'pq' ? ' selected' : '') . '>' . __('Per Quarter', 'propertyhive') . '</option>
                                <option value="pa"' . ($rent_frequency == 'pa' ? ' selected' : '') . '>' . __('Per Annum', 'propertyhive') . '</option>
                            </select>
                            
                        </p>';
            echo '</div>';
            echo '<div class="propertyhive-applicant-residential-details-' . $key . '">';
            // Bedrooms
            propertyhive_wp_text_input(array('id' => '_applicant_minimum_bedrooms_' . $key, 'label' => __('Minimum Bedrooms', 'propertyhive'), 'desc_tip' => false, 'type' => 'number', 'class' => '', 'custom_attributes' => array('style' => 'width:100%; max-width:75px;'), 'value' => isset($applicant_profile['min_beds']) ? $applicant_profile['min_beds'] : ''));
            // Residential Types
            ?>
                        <p class="form-field"><label for="_applicant_property_types_<?php 
            echo $key;
            ?>
"><?php 
            _e('Property Types', 'propertyhive');
            ?>
</label>
                        <select id="_applicant_property_types_<?php 
            echo $key;
            ?>
" name="_applicant_property_types_<?php 
            echo $key;
            ?>
[]" multiple="multiple" data-placeholder="Start typing to add property types..." class="multiselect attribute_values">
                            <?php 
            $options = array('' => '');
            $args = array('hide_empty' => false, 'parent' => 0);
            $terms = get_terms('property_type', $args);
            $selected_values = array();
            $term_list = isset($applicant_profile['property_types']) ? $applicant_profile['property_types'] : array();
            if (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) {
                    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('property_type', $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>';
                        }
                    }
                }
            }
            ?>
                        </select></p>
                    <?php 
            echo '</div>';
            // end 'propertyhive-applicant-residential-details-' . $key
            echo '<div class="propertyhive-applicant-commercial-details-' . $key . '">';
            $args = array('id' => '_applicant_available_as_' . $key, 'label' => 'Available As', 'value' => array('sale', 'rent'), 'options' => array('sale' => 'For Sale', 'rent' => 'To Rent'));
            if (isset($applicant_profile['available_as']) && is_array($applicant_profile['available_as'])) {
                $args['value'] = array();
                foreach ($applicant_profile['available_as'] as $value) {
                    $args['value'][] = $value;
                }
            }
            propertyhive_wp_checkboxes($args);
            // Commercial Types
            ?>
                        <p class="form-field"><label for="_applicant_commercial_property_types_<?php 
            echo $key;
            ?>
"><?php 
            _e('Property Types', 'propertyhive');
            ?>
</label>
                        <select id="_applicant_commercial_property_types_<?php 
            echo $key;
            ?>
" name="_applicant_commercial_property_types_<?php 
            echo $key;
            ?>
[]" multiple="multiple" data-placeholder="Start typing to add property types..." class="multiselect attribute_values">
                            <?php 
            $options = array('' => '');
            $args = array('hide_empty' => false, 'parent' => 0);
            $terms = get_terms('commercial_property_type', $args);
            $selected_values = array();
            $term_list = isset($applicant_profile['commercial_property_types']) ? $applicant_profile['commercial_property_types'] : array();
            if (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) {
                    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('property_type', $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>';
                        }
                    }
                }
            }
            ?>
                        </select></p>
                    <?php 
            echo '</div>';
            // end 'propertyhive-applicant-commercial-details-' . $key
            // Locations
            ?>
                        <p class="form-field"><label for="_applicant_locations_<?php 
            echo $key;
            ?>
"><?php 
            _e('Locations', 'propertyhive');
            ?>
</label>
                        <select id="_applicant_locations_<?php 
            echo $key;
            ?>
" name="_applicant_locations_<?php 
            echo $key;
            ?>
[]" multiple="multiple" data-placeholder="Start typing to add location..." class="multiselect attribute_values">
                            <?php 
            $options = array('' => '');
            $args = array('hide_empty' => false, 'parent' => 0);
            $terms = get_terms('location', $args);
            $selected_values = array();
            $term_list = isset($applicant_profile['locations']) ? $applicant_profile['locations'] : array();
            if (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) {
                    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></p>
                    <?php 
            // Additional Requirement Notes
            propertyhive_wp_textarea_input(array('id' => '_applicant_requirement_notes_' . $key, 'label' => __('Additional Requirements', 'propertyhive'), 'desc_tip' => false, 'class' => '', 'value' => isset($applicant_profile['notes']) ? $applicant_profile['notes'] : ''));
            propertyhive_wp_checkbox(array('id' => '_send_matching_properties_' . $key, 'label' => __('Send Matching Properties', 'propertyhive'), 'desc_tip' => false, 'value' => isset($applicant_profile['send_matching_properties']) && $applicant_profile['send_matching_properties'] == 'yes' || !isset($applicant_profile['send_matching_properties']) ? 'yes' : ''));
            $auto_property_match = get_option('propertyhive_auto_property_match', '');
            if ($auto_property_match == 'yes') {
                // Auto match emails are enabled. Add ability to disable on per-applicant basis
                propertyhive_wp_checkbox(array('id' => '_auto_match_disabled_' . $key, 'label' => __('Disable Auto-Match', 'propertyhive'), 'desc_tip' => false, 'value' => isset($applicant_profile['auto_match_disabled']) && $applicant_profile['auto_match_disabled'] == 'yes' ? 'yes' : ''));
            }
            echo '

                        </div>

                        <div class="actions">

                            <a 
                                href="' . admin_url('admin.php?page=ph-matching-properties&contact_id=' . $contact_id . '&applicant_profile=' . $key) . '" 
                                class="button view-matching-properties-' . $key . '" 
                                ' . (isset($applicant_profile['send_matching_properties']) && $applicant_profile['send_matching_properties'] == '' ? ' disabled title="Send Matching Properties not selected"' : '') . '
                            >' . __('View Matching Properties', 'propertyhive') . '</a>

                            <a 
                                href="' . wp_nonce_url(admin_url('post.php?post=' . $contact_id . '&action=edit#propertyhive-contact-relationships'), $key, 'delete_applicant_relationship') . '" 
                                class="button"
                                onclick="var confirmBox = confirm(\'' . __('Are you sure you wish to delete this applicant relationship?', 'propertyhive') . '\'); return confirmBox;"
                            >' . __('Delete Relationship', 'propertyhive') . '</a>

                            <div id="view_matching_properties_' . $key . '" style="display:none;">
                                
                                <div class="loading-properties" style="text-align:center;"><br><br>Loading matching properties...</div>

                                <div class="need-to-save-changes" style="text-align:center;"><br><br>Please save your changes before viewing matching properties</div>

                                <div class="matching-properties" id="matching_properties_' . $key . '" style="display:none;">

                                </div>

                            </div>

                        </div>

                    </div>

                    <script>

                        var applicant_details_changed_' . $key . ' = false;
                        jQuery(document).ready(function()
                        {
                            showHideApplicantDepartmentMetaBox_' . $key . '();

                            jQuery(\'input[type=\\\'radio\\\'][name=\\\'_applicant_department_' . $key . '\\\']\').change(function()
                            {
                                 showHideApplicantDepartmentMetaBox_' . $key . '();
                            });

                            jQuery(\'.applicant-fields-' . $key . ' input, .applicant-fields-' . $key . ' select, .applicant-fields-' . $key . ' textarea\').change(function()
                            {
                                applicant_details_changed_' . $key . ' = true;
                            });

                            jQuery(\'a.view-matching-properties-' . $key . '\').click(function(e)
                            {
                                if (applicant_details_changed_' . $key . ')
                                {
                                    alert(\'You\\\'ve made changes to the requirements. Please save the changes before viewing matching properties\');
                                    return false;
                                }

                                return true;
                            });
                        });
                        
                        function showHideApplicantDepartmentMetaBox_' . $key . '()
                        {
                            jQuery(\'.propertyhive-applicant-residential-details-' . $key . '\').hide();
                            jQuery(\'.propertyhive-applicant-residential-sales-details-' . $key . '\').hide();
                            jQuery(\'.propertyhive-applicant-residential-lettings-details-' . $key . '\').hide();
                            jQuery(\'.propertyhive-applicant-commercial-details-' . $key . '\').hide();
                            
                            switch (jQuery(\'input[type=\\\'radio\\\'][name=\\\'_applicant_department_' . $key . '\\\']:checked\').val())
                            {
                                case "residential-sales":
                                {
                                    jQuery(\'.propertyhive-applicant-residential-details-' . $key . '\').show();
                                    jQuery(\'.propertyhive-applicant-residential-sales-details-' . $key . '\').show();
                                    break;
                                }
                                case "residential-lettings":
                                {
                                    jQuery(\'.propertyhive-applicant-residential-details-' . $key . '\').show();
                                    jQuery(\'.propertyhive-applicant-residential-lettings-details-' . $key . '\').show();
                                    break;
                                }
                                case "commercial":
                                {
                                    jQuery(\'.propertyhive-applicant-commercial-details-' . $key . '\').show();
                                    break;
                                }
                            }
                            
                        }
                        
                    </script>';
            ++$tab;
        }
        foreach ($third_party_profiles as $key => $category) {
            echo '<div id="tab_third_party_data_' . $key . '" class="panel propertyhive_options_panel" style="' . ($tab == 0 ? 'display:block;' : 'display:none;') . '">
                        <div class="options_group" style="float:left; width:100%;">';
            echo '<p class="form-field rent_field ">
                        
                            <label for="_third_party_category_' . $key . '">' . __('Contact Category', 'propertyhive') . '</label>
                            
                            <select id="_third_party_category_' . $key . '" name="_third_party_category[]" class="select short">';
            if ($category == '' || $category == 0) {
                echo '<option value="0"></option>';
            }
            $categories = $ph_third_party_contacts->get_categories();
            foreach ($categories as $id => $category_name) {
                echo '<option value="' . $id . '"';
                if ($id == $category) {
                    echo ' selected';
                }
                echo '>' . $category_name . '</option>';
            }
            echo '</select>
                            
                        </p>';
            echo '
                        </div>
                    </div>';
            ++$tab;
        }
        echo '<div id="tab_add_relationship" class="panel propertyhive_options_panel" style="' . ($tab == 0 ? 'display:block;' : 'display:none;') . '">
                    <div class="options_group">';
        echo '<p class="form-field">';
        echo '<label>' . __('New Relationship Type', 'propertyhive') . '</label>';
        echo '<a href="' . wp_nonce_url(admin_url('post.php?post=' . $thepostid . '&action=edit#propertyhive-contact-relationships'), '1', 'add_applicant_relationship') . '" class="button">' . __('New Applicant Profile', 'propertyhive') . '</a><br><br>';
        echo '<a href="' . admin_url('post-new.php?post_type=property&owner_contact_id=' . $thepostid) . '" class="button">' . __('New Property Owner / Landlord', 'propertyhive') . '</a><br><br>';
        echo '<a href="' . wp_nonce_url(admin_url('post.php?post=' . $thepostid . '&action=edit#propertyhive-contact-relationships'), '1', 'add_third_party_relationship') . '" class="button">' . __('New Third Party Contact', 'propertyhive') . '</a>';
        echo '</p>';
        echo '
                        </div>
                    </div>';
        echo '<div class="clear"></div>
            
        </div>';
        echo '</div>';
        //do_action('propertyhive_contact_relationships_fields');
    }
    /**
     * 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);
    }
    /**
     * Output the metabox
     */
    public static function output($post)
    {
        global $post, $wpdb, $wp_query, $thepostid;
        $parent_post = false;
        if (isset($_GET['post_parent']) && $_GET['post_parent'] != '') {
            $parent_post = $_GET['post_parent'];
        }
        echo '<div class="propertyhive_meta_box">';
        echo '<div class="options_group">';
        $latitude = get_post_meta($thepostid, '_latitude', TRUE);
        $longitude = get_post_meta($thepostid, '_longitude', TRUE);
        $args = array('id' => '_latitude', 'label' => __('Latitude', 'propertyhive'), 'desc_tip' => false, 'type' => 'text');
        if ($parent_post !== FALSE) {
            $latitude = get_post_meta($parent_post, '_latitude', TRUE);
            $args['value'] = $latitude;
        }
        propertyhive_wp_text_input($args);
        $args = array('id' => '_longitude', 'label' => __('Longitude', 'propertyhive'), 'desc_tip' => false, 'type' => 'text');
        if ($parent_post !== FALSE) {
            $longitude = get_post_meta($parent_post, '_longitude', TRUE);
            $args['value'] = $longitude;
        }
        propertyhive_wp_text_input($args);
        echo '<div class="map_canvas" id="map_canvas" style="height:350px;"></div>';
        $zoom = 16;
        $markerSet = true;
        if ($latitude == '' || $longitude == '' || $latitude == '0' || $longitude == '0') {
            // No lat,lng. Default to whole of UK
            $latitude = 54.617959;
            $longitude = -3.66309;
            $zoom = 5;
            $markerSet = false;
        }
        echo '<small id="help-marker-not-set" style="display:' . ($markerSet ? 'none' : 'block') . ';">' . __('Manually enter the property\'s co-ordinates, or click on the map to specify the exact location.', 'propertyhive') . '</small>';
        echo '<small id="help-marker-set" style="display:' . (!$markerSet ? 'none' : 'block') . ';">' . __('Edit the co-ordinates by manually entering them, or click and drag the marker.', 'propertyhive') . '</small>';
        echo '</div>';
        echo '</div>';
        echo '
        <script>
        
            var map;
            var marker;
            var markerSet = ' . ($markerSet ? 'true' : 'false') . ';
            var geocoder;
            jQuery(document).ready(function()
            {
                jQuery(\'#_address_postcode\').change(function()
                {
                    do_address_lookup();
                });
                jQuery(\'#_address_country\').change(function()
                {
                    do_address_lookup();
                });

                function do_address_lookup()
                {
                    if (!markerSet && jQuery(\'#_address_postcode\').val() != \'\' && jQuery(\'#_address_country\').val() != \'\')
                    {
                        var address = jQuery(\'#_address_postcode\').val();
                        if (jQuery(\'#_address_street\').val() != \'\')
                        {
                            address = jQuery(\'#_address_street\').val() + \', \' + address;
                        }
                        if (jQuery(\'#_address_name_number\').val() != \'\')
                        {
                            address = jQuery(\'#_address_name_number\').val() + \' \' + address;
                        }
                        if (jQuery(\'#_address_country\').val() != \'\')
                        {
                            address = address + \', \' + jQuery(\'#_address_country\').val();
                        }
                        
                        geocoder.geocode( { \'address\': address}, function(results, status) {

                            if (status == google.maps.GeocoderStatus.OK) 
                            {
                                map.panTo(results[0].geometry.location);
                                
                                map.setZoom(16);
                                
                                jQuery(\'#_latitude\').val(results[0].geometry.location.lat());
                                jQuery(\'#_longitude\').val(results[0].geometry.location.lng());
                                
                                marker = ph_create_marker(results[0].geometry.location.lat(), results[0].geometry.location.lng());
                            }
                            else
                            {
                                alert(\'Geocode was not successful for the following reason: \' + status);
                            }
                        });
                    }
                }
                
                function ph_initialize() {
                    
                    geocoder = new google.maps.Geocoder();
                    
                    var starting_lat_lng = new google.maps.LatLng(' . $latitude . ', ' . $longitude . ');
                    var mapOptions = {
                      center: starting_lat_lng,
                      zoom: ' . $zoom . ',
                      scrollwheel: false 
                    };
                    map = new google.maps.Map(document.getElementById(\'map_canvas\'), mapOptions);
                    
                    if (markerSet)
                    {
                        // To add the marker to the map, use the \'map\' property
                        marker = ph_create_marker(' . $latitude . ', ' . $longitude . ');
                    }

                    google.maps.event.addListener(map, \'click\', function(event) 
                    {
                        marker = ph_create_marker(event.latLng.lat(), event.latLng.lng());
                        jQuery(\'#_latitude\').val(event.latLng.lat());
                        jQuery(\'#_longitude\').val(event.latLng.lng());
                    });
                }
                google.maps.event.addDomListener(window, \'load\', ph_initialize);
                
                // Watch for lat lng changing
                jQuery(\'#_latitude\').keyup(function()
                {
                    var latitude = jQuery(this).val();
                    var longitude = jQuery(\'#_longitude\').val();
                    
                    if ( latitude != \'\' && longitude != \'\' && latitude != \'0\' && longitude != \'0\' )
                    {
                        // Both lat and lng exist
                        map.setZoom(16);
                        
                        if (!markerSet)
                        {
                            marker = ph_create_marker(latitude, longitude);

                            markerSet = true;
                        }
                        else
                        {
                            marker.setPosition( new google.maps.LatLng( latitude, longitude ) );
                        }
                        map.panTo( new google.maps.LatLng( latitude, longitude ) );
                    }
                });
                
                jQuery(\'#_longitude\').keyup(function()
                {
                    var latitude = jQuery(\'#_latitude\').val();
                    var longitude = jQuery(this).val();
                    
                    if ( latitude != \'\' && longitude != \'\' && latitude != \'0\' && longitude != \'0\' )
                    {
                        // Both lat and lng exist
                        map.setZoom(16);
                        
                        if (!markerSet)
                        {
                            marker = ph_create_marker(latitude, longitude);

                            markerSet = true;
                        }
                        else
                        {
                            marker.setPosition( new google.maps.LatLng( latitude, longitude ) );
                        }
                        map.panTo( new google.maps.LatLng( latitude, longitude ) );
                    }
                });
            });
            
            function ph_create_marker(lat, lng)
            {
                if ( marker != null )
                {
                    marker.setMap(null);
                }

                marker = new google.maps.Marker({
                    position: new google.maps.LatLng(lat, lng),
                    map: map,
                    draggable: true,
                    title: \'' . __('Click and drag me to set the exact coordinates', 'propertyhive') . '\'
                });
                
                jQuery(\'#help-marker-not-set\').fadeOut(\'fast\', function()
                {
                    jQuery(\'#help-marker-set\').fadeIn();
                });
                
                google.maps.event.addListener(marker, \'dragend\', function() 
                {
                    var newPosition = marker.getPosition();
                    jQuery(\'#_latitude\').val(newPosition.lat());
                    jQuery(\'#_longitude\').val(newPosition.lng());
                });
                
                return marker;
            }
        
        </script>
        ';
    }
 /**
  * Output the metabox
  */
 public static function output($post)
 {
     echo '<div class="propertyhive_meta_box">';
     echo '<div class="options_group">';
     // Currency / Rent / Rent Frequency
     $ph_countries = new PH_Countries();
     $default_country = get_option('propertyhive_default_country', 'GB');
     $countries = get_option('propertyhive_countries', array($default_country));
     $currencies = array();
     foreach ($countries as $country) {
         $country = $ph_countries->get_country($country);
         if (!isset($currencies[$country['currency_code']])) {
             $currencies[$country['currency_code']] = $country['currency_symbol'];
         }
     }
     // Cater for when no currency selected or currencies have been updated in settings so existing currency doesn't exist
     $selected_currency = get_post_meta($post->ID, '_currency', true);
     if ($selected_currency == '' || !isset($currencies[$selected_currency])) {
         $country = $ph_countries->get_country($default_country);
         $selected_currency = $country['currency_code'];
     }
     $rent_frequency = get_post_meta($post->ID, '_rent_frequency', true);
     echo '<p class="form-field rent_field ">
     
         <label for="_rent">' . __('Rent', 'propertyhive') . (empty($currencies) || count($currencies) <= 1 ? ' (<span class="currency-symbol">' . $currencies[$selected_currency] . '</span>)' : '') . '</label>';
     if (count($currencies) > 1) {
         echo '<select id="_rent_currency" name="_rent_currency" class="select" style="width:auto; float:left;">';
         foreach ($currencies as $currency_code => $currency_sybmol) {
             echo '<option value="' . $currency_code . '"' . ($currency_code == $selected_currency ? ' selected' : '') . '>' . $currency_sybmol . '</option>';
         }
         echo '</select>';
     } else {
         echo '<input type="hidden" name="_rent_currency" value="' . $selected_currency . '">';
     }
     echo '<input type="text" class="" name="_rent" id="_rent" value="' . get_post_meta($post->ID, '_rent', true) . '" placeholder="" style="width:20%;">
         
         <select id="_rent_frequency" name="_rent_frequency" class="select" style="width:auto">
             <option value="pppw"' . ($rent_frequency == 'pppw' ? ' selected' : '') . '>' . __('Per Person Per Week', 'propertyhive') . '</option>
             <option value="pw"' . ($rent_frequency == 'pw' ? ' selected' : '') . '>' . __('Per Week', 'propertyhive') . '</option>
             <option value="pcm"' . ($rent_frequency == 'pcm' || $rent_frequency == '' ? ' selected' : '') . '>' . __('Per Calendar Month', 'propertyhive') . '</option>
             <option value="pq"' . ($rent_frequency == 'pq' ? ' selected' : '') . '>' . __('Per Quarter', 'propertyhive') . '</option>
             <option value="pa"' . ($rent_frequency == 'pa' ? ' selected' : '') . '>' . __('Per Annum', 'propertyhive') . '</option>
         </select>
         
     </p>';
     // POA
     propertyhive_wp_checkbox(array('id' => '_rent_poa', 'label' => __('Rent On Application', 'propertyhive'), 'desc_tip' => false, 'value' => get_post_meta($post->ID, '_poa', true)));
     // Deposit
     propertyhive_wp_text_input(array('id' => '_deposit', 'label' => __('Deposit', 'propertyhive'), 'desc_tip' => false, 'class' => '', 'custom_attributes' => array('style' => 'width:20%')));
     // Furnished
     $options = array('' => '');
     $args = array('hide_empty' => false, 'parent' => 0);
     $terms = get_terms('furnished', $args);
     $selected_value = '';
     if (!empty($terms) && !is_wp_error($terms)) {
         foreach ($terms as $term) {
             $options[$term->term_id] = $term->name;
         }
         $term_list = wp_get_post_terms($post->ID, 'furnished', array("fields" => "ids"));
         if (!is_wp_error($term_list) && is_array($term_list) && !empty($term_list)) {
             $selected_value = $term_list[0];
         }
     }
     $args = array('id' => 'furnished_id', 'label' => __('Furnishing', 'propertyhive'), 'desc_tip' => false, 'options' => $options);
     if ($selected_value != '') {
         $args['value'] = $selected_value;
     }
     propertyhive_wp_select($args);
     // Available Date
     propertyhive_wp_text_input(array('id' => '_available_date', 'label' => __('Available Date', 'propertyhive'), 'desc_tip' => false, 'class' => 'short date-picker', 'placeholder' => 'YYYY-MM-DD', 'custom_attributes' => array('maxlength' => 10, 'pattern' => "[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|1[0-9]|2[0-9]|3[01])")));
     do_action('propertyhive_property_residential_lettings_details_fields');
     echo '</div>';
     echo '</div>';
 }
    /**
     * 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);
        }
        echo '<div class="propertyhive_meta_box">';
        echo '<div class="options_group">';
        propertyhive_wp_text_input(array('id' => '_bedrooms', 'label' => __('Bedrooms', 'propertyhive'), 'desc_tip' => false, 'type' => 'number'));
        propertyhive_wp_text_input(array('id' => '_bathrooms', 'label' => __('Bathrooms', 'propertyhive'), 'desc_tip' => false, 'type' => 'number'));
        propertyhive_wp_text_input(array('id' => '_reception_rooms', 'label' => __('Reception Rooms', 'propertyhive'), 'desc_tip' => false, 'type' => 'number'));
        // Property Type
        $options = array('' => '');
        $args = array('hide_empty' => false, 'parent' => 0);
        $terms = get_terms('property_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('property_type', $args);
                if (!empty($subterms) && !is_wp_error($subterms)) {
                    foreach ($subterms as $term) {
                        $options[$term->term_id] = '- ' . $term->name;
                    }
                }
            }
            $term_list = wp_get_post_terms($post->ID, 'property_type', array("fields" => "ids"));
            if (!is_wp_error($term_list) && is_array($term_list) && !empty($term_list)) {
                $selected_value = $term_list[0];
            }
        }
        $args = array('id' => 'property_type_id', 'label' => __('Property Type', 'propertyhive'), 'desc_tip' => false, 'options' => $options);
        if ($selected_value != '') {
            $args['value'] = $selected_value;
        }
        propertyhive_wp_select($args);
        ?>
        <p class="form-field"><label for="parking_ids"><?php 
        _e('Parking', 'propertyhive');
        ?>
</label>
        <select id="parking_ids" name="parking_ids[]" multiple="multiple" data-placeholder="<?php 
        _e('Select parking', 'propertyhive');
        ?>
" class="multiselect attribute_values">
            <?php 
        $options = array('' => '');
        $args = array('hide_empty' => false, 'parent' => 0);
        $terms = get_terms('parking', $args);
        $selected_values = array();
        $term_list = wp_get_post_terms($post->ID, 'parking', 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) {
                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>

        <p class="form-field"><label for="outside_space_ids"><?php 
        _e('Outside Space', 'propertyhive');
        ?>
</label>
        <select id="outside_space_ids" name="outside_space_ids[]" multiple="multiple" data-placeholder="<?php 
        _e('Select outside space', 'propertyhive');
        ?>
" class="multiselect attribute_values">
            <?php 
        $options = array('' => '');
        $args = array('hide_empty' => false, 'parent' => 0);
        $terms = get_terms('outside_space', $args);
        $selected_values = array();
        $term_list = wp_get_post_terms($post->ID, 'outside_space', 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) {
                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_residential_details_fields');
        echo '</div>';
        echo '</div>';
        $post = $original_post;
        $thepostid = $original_thepostid;
        setup_postdata($post);
    }