<?php
/**
 * ------------------------------------------------------------------------
 * JA Filter Plugin - Content
 * ------------------------------------------------------------------------
 * Copyright (C) 2004-2019 J.O.O.M Solutions Co., Ltd. All Rights Reserved.
 * @license - GNU/GPL, http://www.gnu.org/licenses/gpl.html
 * Author: J.O.O.M Solutions Co., Ltd
 * Websites: http://www.joomlart.com - http://www.joomlancers.com
 * This file may not be redistributed in whole or significant part.
 * ------------------------------------------------------------------------
 */
 
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;

$input = Factory::getApplication()->input;
$supportClass = array();

$direction = !empty($this->config->Moduledirection) ? $this->config->Moduledirection : $this->config->direction;
if ($direction == 'vertical')
	$direction='';

if((!empty($this->config->isComponent) && empty($this->config->isModule)) ||
				(empty($this->config->isComponent) && !empty($this->config->isModule)) ) {
  if (!version_compare(JVERSION, '4.0', 'ge'))
  {
    require_once(JPATH_SITE . '/components/com_content/helpers/route.php');
  }

	$json = @file_get_contents(JPATH_SITE.$this->config->json);

	$user = Factory::getUser();
	$userID = $user->id;
	$groups = $user->getAuthorisedGroups();

	$array = (array) json_decode($json);
	$sefUrl = array();

  $latlongID = '__nope__';
  $latlong = array();
  $nameLocation = array();
  foreach ($this->config->fields AS $f) {
      if ($f['type'] == 'latlong') {
          $latlongID = str_replace([".value", "attr."], ["", ""], $f['field']);
          break;
      }
  }

    $i=0;
    $idToLatLong = array();
	foreach ( $array as $value)
	{
		if (isset($value->attr->{$latlongID})) {
            $v = $value->attr->{$latlongID};
            $latlong[] = str_replace(' ', '', $v->value);
            $idToLatLong["item-".$value->id] = str_replace(' ', '', $v->value);
            
		    $nameLocation["name".$i] = 
		    "<div class=\"product-item-img\"><a href=\"".$value->url."\"><img src=\"".JUri::base(true).'/'.$value->thumbnail."\" /></a></div>" .
		    "<h5 class=\"product-item-name\"><a href=\"".$value->url."\">".$value->name."</a></h5>" . 
		    "<p>".$value->desc."</p>";
		    $i++;
		}
	}
}
?>

<?php if(!empty($this->config->isComponent) && empty($this->config->isModule)): ?>
<?php	
	$hasModule = JaMegafilterHelper::hasMegafilterModule(); 
	if($hasModule) {
		$this->config->sticky = 0; 
	} 

$latitude=[];
$longitude=[];
if (!empty($latlong)) {
    foreach ($latlong AS $k => $ll) {
        $ll2 = explode(",", preg_replace("/\s+/","",$ll));
        $latitude["lat".$k] = $ll2[0];
        $longitude["long".$k] = $ll2[1];
    }
}
$latitude = (json_encode($latitude));
$latitude = preg_replace("/lat(\d+)/", "$1", $latitude);
$longitude = (json_encode($longitude));
$longitude = preg_replace("/long(\d+)/", "$1", $longitude);
$nameLocation = (json_encode($nameLocation));
$nameLocation = preg_replace("/name(\d+)/", "$1", $nameLocation);
$nameLocation = str_replace("'", "\/", $nameLocation);

// support joomla custom field render-label class
$db = Factory::getDbo();
$query = $db->getQuery(true);
$query->select('f.id, f.params')
        ->from('#__fields as f');
$db->setQuery($query);
$fields = $db->loadObjectList();
foreach ($fields AS $f) {
    $supportClass["ct".$f->id]=[];
    $p = json_decode($f->params);
    $supportClass["ct".$f->id]['params'] = ["render_class" => $p->render_class, "label_render_class" => $p->label_render_class];
}
?>

<div class="ja-megafilter-grid">
	<?php if (!empty($latitude) && !empty($longitude)): ?>
	    {jaosmap locations='{"location":<?php echo $nameLocation; ?>,"latitude":<?php echo $latitude; ?>,"longitude":<?php echo $longitude; ?>,"info":<?php echo $nameLocation; ?>,"icon":{"0":""}}' zoom='12' map_width='100%' map_height='100%' center='first' }{/jaosmap}
	<?php endif; ?>
	<?php if (isset($this->item['mparams']) && $this->item['mparams']->get('show_page_heading')) : ?>
	<div class="page-header">
		<h1> <?php echo $this->item['mparams']->get('page_heading'); ?> </h1>
	</div>
	<?php endif; ?>
	<div class="property-container container">
		<div class="row <?php echo $this->item['type'] ?> <?php echo $direction; ?> ja-megafilter-wrap clearfix">
			<?php if(!empty($this->config->fullpage) && !$hasModule): ?>
				<div data-mgfilter="content" class="<?php echo $direction ?> ja-mg-sidebar sidebar-main col">
					<a href="javascript:void(0)" class="sidebar-toggle">
						<span class="filter-open">
							<i class="fa fa-filter"></i><?php echo Text::_('COM_JAMEGAFILTER_OPEN_FILTER'); ?>
						</span>
						<span class="filter-close">
							<i class="fa fa-close"></i><?php echo Text::_('COM_JAMEGAFILTER_CLOSE_FILTER'); ?>
						</span>
					</a>
					<div class="block ub-layered-navigation-sidebar sidebar-content"></div>
					<div class="hide view-page-search">
						<div class="more-info">
							<?php echo Text::_('TPL_TRY_SEARCH') ;?>
							<a id="collapse-advanced-search" href="#">
								<?php echo Text::_('TPL_ADVANCED_SEARCH') ;?>
							</a>
							<a id="collapsed-advanced-search" href="#" style="display: none;">
								<?php echo Text::_('TPL_CLOSE_ADVANCED_SEARCH') ;?>
							</a>
						</div>
					</div>
				</div>
			<?php endif; ?>
			<?php 
				if ($hasModule || (empty($this->config->fullpage) && !$hasModule)) {
					$full_width = 'full-width';
				} else {
					$full_width = '';
				}
			?>
			<div class="main-content col <?php echo $full_width ?>"></div>
		</div>
	</div>
</div>
<?php else: ?>
<div data-mgfilter="content" class="<?php echo $direction ?> ja-mg-sidebar sidebar-main col">
	<div class="block ub-layered-navigation-sidebar sidebar-content"></div>
	<?php if(empty($this->config->isComponent)): ?>
		<div id="jamegafilter-btn" class="action-filter hide">
			<a id="jamegafilter-search-btn" class="btn btn-primary" href="javascript:void(0)"><?php echo Text::_('COM_JAMEGAFILTER_SEARCH') ?></a>
		</div>
	<?php else: ?>
		<div class="block-actions filter-actions">
	    <a class="btn btn-primary clear-all-filter action filter-clear"><?php echo Text::_('COM_JAMEGAFILTER_CLEAR_ALL'); ?></a>
		</div> 
	<?php endif;?>

	<?php if(!empty($this->config->url)): ?>
	<div class="hide view-page-search">
		<div class="more-info">
			<?php echo Text::_('TPL_TRY_SEARCH') ;?>
			<a href="<?php echo $this->config->url?>">
				<?php echo Text::_('TPL_ADVANCED_SEARCH') ;?>
			</a>
		</div>
	</div>
	<?php endif; ?>
</div>	
<?php endif; ?>

<?php if((!empty($this->config->isComponent) && empty($this->config->isModule)) || (empty($this->config->isComponent) && !empty($this->config->isModule)) ): ?>

<?php
$document = Factory::getDocument();
$document->addScriptDeclaration('
    var extendedJAOSMap = {};
    var idToLatLong =  '.json_encode($idToLatLong).';
');
?>
<script type="text/javascript">
<?php if(!empty($this->config->url)): ?>
var filter_url = '<?php echo $this->config->url?>';
<?php endif; ?>

var JABaseUrl = '<?php echo JUri::base(true); ?>';
var ja_default_sort="<?php echo $this->config->default_sort; ?>";
var ja_sort_by="<?php echo $this->config->sort_by; ?>";
var ja_layout_addition="<?php echo $this->config->layout_addition; ?>";
var ja_layout_columns=<?php echo json_encode($this->config->jacolumn); ?>;
var ja_userGroup = <?php echo json_encode($groups); ?>;
var ja_customfield_class_render = <?php echo json_encode($supportClass); ?>;
var p = <?php echo json_encode($this->jstemplate); ?>;
for (var key in p) {
  if (p.hasOwnProperty(key)) {
    var compiled = dust.compile(p[key], key);
    dust.loadSource(compiled);
  }
}

function bindCallback() {
	setTimeout(function(){
		if (jQuery('.jamegafilter-wrapper').find('.pagination-wrap').length) {
			jQuery('.jamegafilter-wrapper').removeClass('no-pagination');
		} else {
			jQuery('.jamegafilter-wrapper').addClass('no-pagination');
		}
		
		if (isMobile.apple.tablet && jQuery('#t3-off-canvas-sidebar').length) {
			jQuery('select').unbind().off().on('touchstart', function() {
    			formTouch=true;
    			fixedElement.css('position', 'absolute');
    			fixedElement.css('top', jQuery(document).scrollTop());
			});
			jQuery('html').unbind().off().on('touchmove', function() {
				if (formTouch==true) {
					fixedElement.css('position', 'fixed');
					fixedElement.css('top', '0');
					formTouch=false;
				}
			});
		}
		initScript();
        jQuery('.ja-products-wrapper .carousel').carousel({
          interval: false
        });

		jQuery(".r-price .col-md-12").html(function (i, html) {
	  	    return html.replace(/\/([a-zA-Z0-9]+)$/, '/<sup>$1</sup>');
		});

		if(jQuery('.t3-hero .ja-mg-sidebar').length) {
 			jQuery('#jamegafilter-btn').appendTo('#narrow-by-list').removeClass('hide');
 		};

 		if(jQuery('.ja-megafilter-wrap .ja-mg-sidebar').length) {
 			jQuery('#clear-all-btn').appendTo('#narrow-by-list');
 		};

 		jQuery('#collapse-advanced-search').unbind().off().on('click', function(e) {
      jQuery('.sb-horizontal.ja-mg-sidebar .filter-options .filter-field').css("display", "block");
      jQuery('#collapsed-advanced-search').css("display", "inline");
      jQuery('#collapse-advanced-search').css("display", "none");
      e.preventDefault();
	  });

	  jQuery('#collapsed-advanced-search').unbind().off().on('click', function(e) {
      jQuery('.sb-horizontal.ja-mg-sidebar .filter-options .filter-field:nth-child(6), .sb-horizontal.ja-mg-sidebar .filter-options .filter-field:nth-child(7), .sb-horizontal.ja-mg-sidebar .filter-options .filter-field:nth-child(8), .sb-horizontal.ja-mg-sidebar .filter-options .filter-field:nth-child(9), .sb-horizontal.ja-mg-sidebar .filter-options .filter-field:nth-child(10), .sb-horizontal.ja-mg-sidebar .filter-options .filter-field:nth-child(11), .sb-horizontal.ja-mg-sidebar .filter-options .filter-field:nth-child(12), .sb-horizontal.ja-mg-sidebar .filter-options .filter-field:nth-child(13), .sb-horizontal.ja-mg-sidebar .filter-options .filter-field:nth-child(14), .sb-horizontal.ja-mg-sidebar .filter-options .filter-field:nth-child(15)').css("display", "none");
      jQuery('#collapse-advanced-search').css("display", "inline");
      jQuery('#collapsed-advanced-search').css("display", "none");
      e.preventDefault();
	  });

		if (jQuery('.items.product-items').find('.item').length == 0) {
            jQuery('.toolbar-amount').each(function(){
                jQuery(this).find('.toolbar-number').first().text(0);
            });
        } else {
            jQuery('.items.product-items').find('.item.ln-item .product-item-details').off().on("click", function() {
                if (typeof idToLatLong["item-"+jQuery(this).data('id')] !== "undefined") {
                    let latLng = idToLatLong["item-"+jQuery(this).data('id')].split(",");
                    for (let x in extendedJAOSMap._targets) {
                        if (extendedJAOSMap._targets[x]._latlng !== undefined) {
                            if (extendedJAOSMap._targets[x]._latlng.lat === parseFloat(latLng[0]) &&
                                extendedJAOSMap._targets[x]._latlng.lng === parseFloat(latLng[1]))
                                {
                                    extendedJAOSMap._targets[x].openPopup();
                                    extendedJAOSMap.panTo(L.latLng(latLng[0], latLng[1]), {animate: true, duration: 1.0});
                                    return;
                                }
                        }
                    }
                }
            });
        }

        extendedJAOSMap.invalidateSize();

	  }, 100);
    // we don't need delay with this.
    jQuery(".item.product").each(function() {
        // only work if currency,price value, area value without label.
        if (jQuery(this).find(".r-currency").length || jQuery(this).find(".r-value-of-price").length) {
            let txt = jQuery(this).find(".r-price .col-md-12").text();
            let currency = jQuery(this).find(".r-currency").text();
            let typeprice = "<div class=\"value-type\">"+jQuery(this).find(".r-value-of-price").text()+"</div>";
            jQuery(this).find(".r-price .col-md-12").html("<div class=\"ct-field-value\">"+currency+""+txt+" /</div> "+typeprice);
            jQuery(this).find(".r-currency").remove();
            jQuery(this).find(".r-value-of-price").remove();
        }
        if (jQuery(this).find(".r-value-of-area").length) {
            let txt = jQuery(this).find(".r-area.r-class .col-md-6").eq(1).text();
            let areavalue = jQuery(this).find(".r-value-of-area").text();
            jQuery(this).find(".r-area.r-class .col-md-6").eq(1).html(txt+" "+areavalue);
            jQuery(this).find(".r-value-of-area").remove();
        }
    });
}

// Fix for delay from hosting
if(jQuery('.t3-hero .ja-mg-sidebar').length) {
	setTimeout(function(){
		jQuery('#jamegafilter-btn').appendTo('#narrow-by-list').removeClass('hide');
	},2000);
};

function scrolltop() {
	if (!isMobile.phone) jQuery("html, body").stop().animate({ scrollTop: jQuery('div.ja-megafilter-wrap').offset().top }, 400);
}

function MegaFilterCallback() {
	bindCallback();
	<?php echo $input->getCmd('scrolltop') ? 'scrolltop();':'' ?>
}


function afterGetData(item) {
	if (typeof(item.thumbnail) != 'undefined' && item.thumbnail != '') {
		thumbnail = item.thumbnail;
		if (!thumbnail.match(/^http|https:/)) {
			item.thumbnail = '<?php echo JUri::root(true). '/'?>'+item.thumbnail;
		}
	}

	// owner
	if (item.created_by == '<?php echo $userID ?>') 
		return false;
    if (typeof item['access'] !== 'undefined' && item['access'] !== undefined && item['access'] !== null) {
        let itemAccess = item['access'].split(',');
        for (let i=0;i<itemAccess.length;i++) {
            for (let x in ja_userGroup) {
                // super admin could see it all, public or guest.
                if (itemAccess[i] == ja_userGroup[x] || ja_userGroup[x]==8) {
                    return false;
                }
            }
        }
    }
	return true;

}

jQuery(document).ready(function() {
  var UBLNConfig = {};
  UBLNConfig.dataUrl = "<?php echo JUri::base(true).$this->config->json;  ?>";
  UBLNConfig.fields = <?php echo json_encode($this->config->fields); ?>;
  UBLNConfig.sortByOptions = <?php echo str_replace('.value','.frontend_value',json_encode($this->config->sorts)); ?>;
  UBLNConfig.defaultSortBy = "<?php echo $this->config->default_sort; ?>";
  UBLNConfig.productsPerPageAllowed = [<?php echo implode(',', $this->config->paginate); ?>];
  UBLNConfig.autopage = <?php echo $this->config->autopage ? 'true':'false' ?>;
  UBLNConfig.sticky = <?php echo $this->config->sticky ? 'true':'false' ?>;
  UBLN.main(UBLNConfig);
  MegaFilterCallback();
});
</script>

<?php 
endif;