<?php
/**
 * Template for building Portfolio Teasers inside
 * WordPress Loop.
 *
 * This template must be called in a multiple post page
 * such as taxonomy-portfolio_category.php or custom page
 * that will display the portfolio listing.
 *
 * @variables
 *
 * @author jason.xie@victheme.com
 */
?>
<?php
// Preprocess Portfolio variables first

global $wp;

$page_url = add_query_arg($wp->query_string, '', home_url($wp->request));

// Allow other to inject posts
// This is needed for shortcodes
if (!isset($posts) && !isset($query)) {

  global $post;
  global $wp_query;

  // Try to use the WordPress Main Query
  $posts = $wp_query->posts;
  $query = $wp_query;


  // This template is called outside normal
  // WordPress main loop, booting custom
  // loop to get Portfolio Items
  if (is_page()) {

    // User can customize the query arguments
    // by passing valid arguments for WP_Query
    // in the $args
    // @see http://codex.wordpress.org/Class_Reference/WP_Query for valid args
    $args = array();

    $query = VTCore_Portfolio_Utility::buildPortfolioPost($args);
    $posts = $query->get_posts();
  }
}


// Building the Taxonomies terms related
// to all posts, this is for the taxonomy
// isotope (or direct link) links
if (empty($terms)) {
  //$terms = VTCore_Portfolio_Utility::buildTaxonomy($posts);
}


// Get random id for multiple instance in
// a single page.
$unique = new VTCore_Uid();
$random = $unique->getID();


// Get current active taxonomy for active links
$current = get_query_var('portfolio_category');


// Get user configuration for portfolio grids
if (!isset($portfolioConfigObject) || $portfolioConfigObject instanceof VTCore_Portfolio_Config == FALSE) {
  $portfolioConfigObject = new VTCore_Portfolio_Config();
}

if (!isset($portfolioConfig)) {
  $portfolioConfig = $portfolioConfigObject->get('grid');
}

// Building the Taxonomies terms related
// to all posts, this is for the taxonomy
// isotope (or direct link) links
if (empty($terms)) {
  $parent = FALSE;
  if (empty($portfolioConfig['isotope']) || empty($portfolioConfig['doajax'])) {
    $parent = TRUE;
  }
  $terms = VTCore_Portfolio_Utility::buildTaxonomy($posts, $parent);
}

if (!isset($show)) {
  $show = $portfolioConfig['show'];
}

if (!isset($buildall)) {
  $buildall = $portfolioConfig['buildall'];
}

if (!isset($buildcategory)) {
  $buildcategory = $portfolioConfig['category'];
}

// Build title
if (!isset($title)) {
  if (is_singular()) {
    $title = get_the_title($post);
  }
  else {
    $title = __('Browsing category : ', BASE_THEME) . $current;
  }
}

// Build content
if (!isset($content) || empty($content)) {
  if (is_singular() && isset($post)) {
    setup_postdata($post);
    $content = get_the_content();
    wp_reset_postdata();
  }
  else {
    $content = $portfolioConfig['content'];
  }
}


// Build isotope
$isotopetarget = '';
$isotopesource = '';
$jsmode = FALSE;
if (!empty($portfolioConfig['isotope'])) {
  $isotopetarget = 'isotope-target';
  $isotopesource = 'isotope-sources';
  $jsmode = 'isotope';
}

if (!isset($mode) || empty($mode)) {
  $mode = $portfolioConfigObject->get('grid.mode');
}

// Get template file
if ($mode == 'grid') {
  $isotopetarget = 'isotope-target';
  $gridfile = VTCore_Wordpress_Utility::locateTemplate('portfolio-grid.php');
  $teasercolumn = VTCore_Wordpress_Utility::getBootstrapGrid($portfolioConfig['teaser_column']);
}

if ($mode == 'list') {
  $gridfile = VTCore_Wordpress_Utility::locateTemplate('portfolio-list.php');
  $teasercolumn = 'col-xs-12 col-sm-12 col-md-12 col-lg-12';
}

// Load Assets, Theme may want to disable this.
VTCore_Wordpress_Utility::loadAsset('jquery-resizeend');
VTCore_Wordpress_Utility::loadAsset('jquery-isotope');
VTCore_Wordpress_Utility::loadAsset('portfolio-base');
VTCore_Wordpress_Utility::deregisterAsset('portfolio-base', TRUE, FALSE);


// ----------------------------
// AJAX ADDITONAL CONFIGURATION
// ----------------------------

// Record all post id so ajax wont fetch double post
$filters = array();
foreach ($posts as $post) {
  $filters[] = $post->ID;
}

// Pass pagination variable to JS
// this will be calculated again in the loop
$pagination = $portfolioConfig['pagination'];
$viewport = $portfolioConfig['viewport'];
$doajax = $portfolioConfig['doajax'];

// Load wp-ajax
if ($doajax) {
  VTCore_Wordpress_Utility::loadAsset('wp-ajax');
  wp_localize_script('wp-ajax-wp-ajax.js', 'ajaxurl', admin_url('admin-ajax.php'));
}

// Get WP Nonce key
$nonce = wp_create_nonce('vtcore-ajax-nonce-admin');


// Finish booting, start building the HTML markups
?>

<?php if ($show['main_title'] && !empty($title)) : ?>
  <h2 class="post-title text-center element-title title-large text-uppercase">
    <span class="text">
      <?php echo $title; ?>
    </span>
  </h2>
<?php endif; ?>

<?php if ($show['main_content'] && !empty($content)) : ?>
  <div class="post-content text-center portfolio-content">
    <?php echo $content; ?>
  </div>
<?php endif; ?>


<!-- Portfolio Menu -->
<?php if ($buildcategory || $jsmode == 'isotope') : ?>
  <ul
    class="portfolio-source unstyled inline text-center clearfix <?php echo esc_attr($isotopesource); ?>"
    data-target="<?php echo esc_attr($random); ?>">

    <?php if ((is_page() || !empty($isotopesource)) && $buildall): ?>
      <li>

        <a href="<?php echo esc_url(add_query_arg($_GET, $page_url)); ?>"
           class="term-link btn btn-primary" data-id="*"
           data-target="<?php print esc_attr($random); ?>">
          <?php echo __('All', BASE_THEME); ?>

        </a>

      </li>
    <?php endif; ?>


    <?php foreach ($terms as $term) : ?>

      <li <?php if ($term->slug == $current) : ?> class="active" <?php endif; ?>>

        <?php
        $element_id = 'portfolio-isotope-button-' . $term->slug . '-' . $random;
        $totalfetch = $viewport - count(VTCore_Portfolio_Utility::getPostBySlug($posts, $term->slug));

        $object = new VTCore_Html_HyperLink(array(
          'text' => $term->name,
          'attributes' => array(
            'href' => get_term_link($term),
            'id' => $element_id,
            'class' => array(
              'term-link',
              'btn',
              'btn-primary',
              'btn-ajax'
            ),
          ),
          'data' => array(
            'id' => $term->slug,
            'target' => $random,
            'nonce' => $nonce,
            'ajax-loading-text' => __('Loading...', BASE_THEME),
            'ajax-action' => 'vtcore_ajax_framework',
            'ajax-object' => 'VTCore_Portfolio_Ajax_Grid',
            'ajax-mode' => 'data',
            'ajax-group' => 'portfolio-' . $random,
            'ajax-target' => '#' . $element_id,
            'ajax-value' => array(
              'pagination' => $totalfetch,
              'mode' => $mode,
              'target' => 'ul.isotope-target[data-target=' . $random . ']',
              'source' => '#' . $element_id,
              'filter' => $filters,
              'slug' => $term->slug,
              'viewport' => $viewport,
              'jsscript' => $jsmode,
              'config' => $portfolioConfig,
            ),
            'ajax-marker' => array(
              'mode' => 'portfolio',
              'target' => '#' . $element_id,
              'container' => 'ul.isotope-target[data-target=' . $random . ']',
            ),
            'ajax-queue' => array(
              'portfolio-' . $random . '-' . $term->slug,
            ),
          ),
        ));

        // Remove ajax if certain condition are met.
        if (!$doajax || $totalfetch < 1) {
          $object->removeClass('btn-ajax');
        }

        $object->render();

        ?>


      </li>

    <?php endforeach; ?>

  </ul>
<?php endif; ?>

<!-- Portfolio Items -->
<ul class="portfolio clearfix unstyled row <?php echo esc_attr($isotopetarget); ?>"
    data-target="<?php print esc_attr($random); ?>"
    data-gutter="0">

  <?php global $post; ?>
  <?php foreach ($posts as $post) : ?>

    <?php setup_postdata($post); ?>
    <?php $slug = VTCore_Portfolio_Utility::buildSlug($post); ?>
    <?php include $gridfile; ?>
    <?php wp_reset_postdata(); ?>
  <?php endforeach; ?>

</ul>
