<?php
error_reporting('E_ALL');

// No direct access to this file
defined('_JEXEC') or die('Restricted access');
$app = JFactory::getApplication();
$templateparams = $app->getTemplate(true)->params;
$politeloading = $templateparams->get('politeloading');
$lblsale = $templateparams->get('lblsale');
$lblhot = $templateparams->get('lblhot');
$lblhotcount = $templateparams->get('lblhotcount');
$lbloffer = $templateparams->get('lbloffer');
$lblsold = $templateparams->get('lblsold');
$lblnew = $templateparams->get('lblnew');
$latest_products_days = $templateparams->get('lblnewcount');

echo vmJsApi::writeJS();
$lang = JFactory::getLanguage();
$extension = 'com_virtuemart';
$lang->load($extension);

$tag            = JRequest::getVar('tag');
$products           = $this->products;
$juri             = JURI::base();
$doc            = &JFactory::getDocument();
$doc->addStylesheet($juri.'components/com_cooltags/assets/css/style.css');

$cparams          = JComponentHelper::getParams('com_cooltags');
$vm_itemid          = $cparams->get('vm_itemid');
//$cooltags_itemid      = $cparams->get('cooltags_itemid');
$items = JFactory::getApplication()->getMenu( 'site' )->getItems( 'component', 'com_cooltags' );
  //print_r($items);
    foreach ( $items as $item ) {
        if($item->query['view'] === 'productslist'){
      //print_r($item->id);
            $cooltags_itemid= $item->id;
      
        }
    }
$show_price           = $cparams->get('show_price','1');
$credits          = $cparams->get('credits','0');
echo '<h3 class="module-title"><span><span>'.JText::_('COM_COOLTAGS_TAGGED_AS').': '.$tag.'</h3></span></span>';
echo '<div class="pagination2" >';
echo $this->pagination->getResultsCounter();
echo '</div></br>';

function jsonRemoveUnicodeSequences($struct) {
   return preg_replace("/\\\\u([a-f0-9]{4})/e", "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", json_encode($struct));
}
defined('DS') or define('DS', DIRECTORY_SEPARATOR);
if (!class_exists( 'CurrencyDisplay' )) require(JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_virtuemart'.DS.'helpers'.DS.'currencydisplay.php');
if (!class_exists( 'shopFunctionsF' )) require(JPATH_SITE.DS.'components'.DS.'com_virtuemart'.DS.'helpers'.DS.'shopfunctionsf.php');

if (!class_exists( 'VmConfig' ))
  require(JPATH_ADMINISTRATOR . '/components/com_virtuemart/helpers/config.php');
VmConfig::loadConfig();

?>
<?php
$product_model = VmModel::getModel('product');
$ratingModel = VmModel::getModel('ratings');
$mainframe = Jfactory::getApplication();
$virtuemart_currency_id = $mainframe->getUserStateFromRequest( "virtuemart_currency_id", 'virtuemart_currency_id',JRequest::getInt('virtuemart_currency_id',0) );
$tags = array();
foreach($products as $product){
   //var_dump ($product);

  $tags[] = $product->virtuemart_product_id;
 } 
 $prods_tags = $product_model->getProducts($tags);
    //var_dump ($releted);
    $product_model->addImages($prods_tags); 
    $currency = CurrencyDisplay::getInstance( );


?>
<div id="product_list" class="list layout2 tags">
          <ul id="slider" class="vmproduct">
          <?php // Start the Output
          foreach ( $prods_tags as $product ) {
             //var_dump ($product);
          if (isset($product->step_order_level))
            $step=$product->step_order_level;
          else
            $step=1;
          if($step==0)
            $step=1;
          $alert=JText::sprintf ('COM_VIRTUEMART_WRONG_AMOUNT_ADDED', $step);
          $discont = $product->prices['discountAmount'];
          $discont = abs($discont);
          $currency = CurrencyDisplay::getInstance( );
             $show_price = $currency->createPriceDiv('salesPrice', '', $product->prices,true);
            foreach ($product->categoryItem as $key=>$prod_cat) {
            $virtuemart_category_id=$prod_cat['virtuemart_category_id'];
             }
          ?>
                    <li>
                          <input type="hidden" class="quick_ids" name="virtuemart_product_id" value="<?php echo $product->virtuemart_product_id ?>"/>

                       <div class="product-box hover spacer <?php if ($discont>0) { echo 'disc';} ?> ">
                        <?php if ($product->prices['override'] == 1 && ($product->prices['product_price_publish_down'] > 0)){
              $data = $product->prices['product_price_publish_down'];
            $data = explode(' ', $data);
            $time = explode(':', $data[1]);
            $data = explode('-', $data[0]);
            //var_dump($data);
             $year = $data[0];
             $month = $data[1];
             $data = $data[2];
            //var_dump($time);
              ?>
              <div class="count_holder_small">
              <div class="count_info"><?php echo JText::_('DR_LIMITED')?></div>
              <div id="CountSmallFeatured<?php echo $product->virtuemart_product_id ?>" class="count_border">
               <script type="text/javascript">
              jQuery(function () {    
                jQuery('#CountSmallFeatured<?php echo $product->virtuemart_product_id ?>').countdown({
                  until: new Date(<?php echo $year; ?>, <?php echo $month; ?> - 1, <?php echo $data; ?>), 
          labels: ['Years', 'Months', 'Weeks', '<?php echo JText::_('DR_DAYS')?>', '<?php echo JText::_('DR_HOURS')?>', '<?php echo JText::_('DR_MINUTES')?>', '<?php echo JText::_('DR_SECONDS')?>'],
          labels1:['Years','Months','Weeks','<?php echo JText::_('DR_DAYS')?>','<?php echo JText::_('DR_HOURS')?>','<?php echo JText::_('DR_MINUTES')?>','<?php echo JText::_('DR_SECONDS')?>'],
                  compact: false});
              });
               </script>
               </div>
               </div>
              <?php } ?>
                       <div class="left-img">
                            <div class="browseImage ">
                      <?php
                        $stockhandle = VmConfig::get ('stockhandle', 'none');
                        if (($stockhandle == 'disableit' or $stockhandle == 'disableadd') and (($product->product_in_stock - $product->product_ordered) < 1) || 
                                (($product->product_in_stock - $product->product_ordered) < $product->min_order_level ))  { ?>
                                <div class="discount sold"><?php echo JText::_('DR_SOLD');?></div>
                         <?php } ?>   
                             <?php if ($product->prices['override'] == 1 && ($product->prices['product_price_publish_down'] > 0)){ ?>
                            <div class="discount limited"><?php echo JText::_('DR_LIMITED_OFFER');?></div>
                              <?php } elseif($discont >0 && $product->product_sales < 20 ) { ?>
                             <div class="discount"><?php echo JText::_('DR_SALE');?></div>
                                <?php } elseif ($product->product_sales > 20) {?>
                                  <div class="hit"><?php echo JText::_('DR_HOT');?></div>
                                  <?php } ?>
                                  <div class="img-wrapper">
                                   <?php
                                            $image = $product->images[0]->displayMediaThumb('class="browseProductImage featuredProductImageFirst" id="Img_to_Js_'.$product->virtuemart_product_id.'" border="0"',false) ;
                      if(!empty($product->images[1])){
                       $image2 = $product->images[1]->displayMediaThumb('class="browseProductImage featuredProductImageSecond"  border="0"',false) ;
                      } else {$image2= $product->images[0]->displayMediaThumb('class="browseProductImage featuredProductImageSecond"  border="0"',false) ;}
                                            echo JHTML::_('link', JRoute::_('index.php?option=com_virtuemart&view=productdetails&virtuemart_product_id='.$product->virtuemart_product_id.'&virtuemart_category_id='.$virtuemart_category_id),'<div class="front">'.$image.'</div><div class="back">'.$image2.'</div>');
                                    ?>
                                    </div>
                                    
                            
                            
                            </div>  
                            </div>      
                            <div class="slide-hover">
                                <div class="wrapper">
                                            <div class="Title">
                                            <?php echo JHTML::link(JRoute::_('index.php?option=com_virtuemart&view=productdetails&virtuemart_product_id='.$product->virtuemart_product_id.'&virtuemart_category_id='.$virtuemart_category_id), shopFunctionsF::limitStringByWord($product->product_name,'40','...'), array('title' => $product->product_name)); ?>
                                            </div>
                                            <div class="clear"></div>
                                         <?php
                      $showRating = $ratingModel->showRating($product->virtuemart_product_id);
                     if ($showRating=='true'){
                                        $rating = $ratingModel->getRatingByProduct($product->virtuemart_product_id);
                                        if( !empty($rating)) {
                                            $r = $rating->rating;
                                        } else {
                                            $r = 0;
                                        }
                                        $maxrating = VmConfig::get('vm_maximum_rating_scale',5);
                                                        $ratingwidth = ( $r * 100 ) / $maxrating;//I don't use round as percetntage with works perfect, as for me
                                            ?>
                                          <?php  if( !empty($rating)) {  ?>                        
                                                <span class="vote">
                                                    <span title="" class="vmicon ratingbox" style="display:inline-block;">
                                                        <span class="stars-orange" style="width:<?php echo $ratingwidth;?>%">
                                                        </span>
                                                    </span>
                                                    <span class="rating-title"><?php echo JText::_('COM_VIRTUEMART_RATING').' '.round($rating->rating, 2) . '/'. $maxrating; ?></span>
                                                </span>
                                           <?php } else { ?>
                                              <span class="vote">
                                                    <span title="" class="vmicon ratingbox" style="display:inline-block;">
                                                        <span class="stars-orange" style="width:<?php echo $ratingwidth;?>%">
                                                        </span>
                                                    </span>
                                                    <span class="rating-title"><?php echo JText::_('COM_VIRTUEMART_RATING').' '.JText::_('COM_VIRTUEMART_UNRATED') ?></span>
                                               </span>
                                            <?php } } ?>
                                            <?php 
                                   if ((!empty($product->prices['salesPrice'])) && !$product->images[0]->file_is_downloadable) { ?>   
                                  <div class="Price">            
                                         <div class="product-price marginbottom12" id="productPrice<?php echo $this->product->virtuemart_product_id ;?>">
                    <?php if ($product->prices['basePriceWithTax']>0 && $discont>0)
                                            echo '<span class="PricebasePriceWithTax">'.$currency->createPriceDiv('basePriceWithTax', '', $product->prices,true).'</span>';
                                        ?>
                                        <?php if ($product->prices['salesPrice']>0)
                                            echo '<span class="PricesalesPrice">' .$currency->createPriceDiv('salesPrice', '', $product->prices,true).'</span>';
                                        ?>
                                 </div>
                                 </div>
                                 <?php } else {
                  if ($product->prices['salesPrice']<=0 and VmConfig::get ('askprice', 1) ) { ?>
                  <div class="call-a-question">
                                      <a class="call modal"  rel="{handler: 'iframe', size: {x: 460, y: 550}}" href="<?php echo JRoute::_('index.php?option=com_virtuemart&view=productdetails&task=askquestion&virtuemart_product_id='.$product->virtuemart_product_id.'&virtuemart_category_id='.$virtuemart_category_id.'&tmpl=component'); ?>" ><?php echo JText::_('COM_VIRTUEMART_PRODUCT_ASKPRICE') ?></a>
                                    </div>
                  <?php } } ?>
                                <div class="clear"></div>
                                <?php // Product Short Description
                  if(!empty($product->product_s_desc)) { ?>
                  <div class="desc1"><?php echo shopFunctionsF::limitStringByWord($product->product_s_desc, 250, '...') ?></div>
                <?php } ?>
                                </div>
                                    <div class="wrapper-slide">
                                    <?php if (!empty($show_price)){
                                  if ((!VmConfig::get('use_as_catalog', 0) and !empty($product->prices['salesPrice'])) && !$product->images[0]->file_is_downloadable) { ?>
                  <div class="addtocart-area2">
                    <?php 
              $stockhandle = VmConfig::get ('stockhandle', 'none');
if (($stockhandle == 'disableit' or $stockhandle == 'disableadd') and (($product->product_in_stock - $product->product_ordered) < 1) || (($product->product_in_stock - $product->product_ordered) < $product->min_order_level ))  {
       ?>
                      <a class="addtocart-button" title="<?php echo JText::_('COM_VIRTUEMART_CART_NOTIFY') ?>" href="<?php echo JRoute::_('index.php?option=com_virtuemart&view=productdetails&layout=notify&virtuemart_product_id='.$product->virtuemart_product_id); ?>"><?php echo JText::_('COM_VIRTUEMART_CART_NOTIFY') ?><span></span></a>
                    <?php } else { ?>
                    <form method="post" class="product" action="index.php" id="addtocartproduct<?php echo $product->virtuemart_product_id ?>">
                                          <input name="quantity" type="hidden" value="<?php echo $step ?>" />
                    <div class="addtocart-bar2">
                                        <script type="text/javascript">
                          function check(obj) {
                          // use the modulus operator '%' to see if there is a remainder
                          remainder=obj.value % <?php echo $step?>;
                          quantity=obj.value;
                          if (remainder  != 0) {
                            alert('<?php echo $alert?>!');
                            obj.value = quantity-remainder;
                            return false;
                            }
                          return true;
                          }
                      </script> 
                      <?php // Display the quantity box 
                       if (!empty($product->customfields)) {
                          foreach ($product->customfields as $k => $custom) {
                            if (!empty($custom->layout_pos)) {
                              $product->customfieldsSorted[$custom->layout_pos][] = $custom;
                              unset($product->customfields[$k]);
                            }
                          }
                          $product->customfieldsSorted['normal'] = $product->customfields;
                          unset($product->customfields);
                        }
                      $position = 'addtocart';
                      if (!empty($product->customfieldsSorted[$position])) { ?>
                      <span class="attributes"><b>*</b> Product has attributes</span>
                                            <div class="addtocart_button2">
                      <?php echo JHTML::link($product->link, JText::_('DR_VIRTUEMART_SELECT_OPTION').'<span>&nbsp;</span>', array('title' =>JText::_('DR_VIRTUEMART_SELECT_OPTION'),'class' => 'addtocart-button')); ?>
                                          </div>
                    
                    <?php } else { ?>
                    <span class="quantity-box">
                      <input type="text" class="quantity-input js-recalculate" name="quantity[]" onblur="check(this);" value="<?php if (isset($product->step_order_level) && (int)$product->step_order_level > 0) {
      echo $product->step_order_level;
    } else if(!empty($product->min_order_level)){
      echo $product->min_order_level;
    }else {
      echo '1';
    } ?>"/>
                    </span>
                    <span class="quantity-controls">
                      <input type="button" class="quantity-controls quantity-plus" />
                      <input type="button" class="quantity-controls quantity-minus" />
                    </span>
                    <?php // Add the button
                      $button_lbl = JText::_('COM_VIRTUEMART_CART_ADD_TO');
                      $button_cls = 'addtocart-button cart-click hasTooltips'; //$button_cls = 'addtocart_button';
                    ?>
                      <?php // Display the add to cart button ?>
                      <div class="clear"></div>
                      <span class="addtocart_button2">
                        <button type="submit" value="<?php echo $button_lbl ?>" title="<?php echo JText::_('COM_VIRTUEMART_CART_ADD_TO');?>" class="<?php echo $button_cls ?>"><?php echo $button_lbl ?><span>&nbsp;</span></button>
                      </span>
                                            
                    <input type="hidden" class="pname" value="<?php echo $product->product_name ?>"/>
                    <input type="hidden" name="option" value="com_virtuemart" />
                    <input type="hidden" name="view" value="cart" />
                    <noscript><input type="hidden" name="task" value="add" /></noscript>
                                        <input type="hidden" class="item_id" name="virtuemart_product_id[]" value="<?php echo $product->virtuemart_product_id ?>"/>
                    <input type="hidden" name="virtuemart_category_id[]" value="<?php echo $virtuemart_category_id ?>" /> 
                    <?php }?>
                  </div>
                  </form>
                  <?php } ?>
                                    </div>
              <?php } }?>
                             <?php if(is_file(JPATH_BASE.DS."components/com_wishlists/template/wishlists.tpl.php")){  ?>
                                 <div class="wishlist list_wishlists<?php echo $product->virtuemart_product_id;?>">
                    <?php require(JPATH_BASE.DS."components/com_wishlists/template/wishlists.tpl.php"); ?>
                                     </div>
                                 <?php } ?>       
                                     <?php if(is_file(JPATH_BASE.DS."components/com_comparelist/template/comparelist.tpl.php")){  ?>
                                 <div class="jClever compare_cat list_compare<?php echo $product->virtuemart_product_id;?>">
                    <?php require(JPATH_BASE.DS."components/com_comparelist/template/comparelist.tpl.php"); ?>
                                     </div>
                                 <?php } ?>       
                                     <div class="clear"></div>
                                    </div>
                                     <?php 
                   
                  foreach($products as $prod){
                  if ($product->virtuemart_product_id == $prod->virtuemart_product_id){
      
                       echo '<div class="product_tags" >';
                $sep_tags = explode(',',$prod->accented_tags);
                  echo '<i class="icon-tags" title="'.JText::_('COM_COOLTAGS_TAGS').'"  class="hasTooltip" ></i> ';
                  for($i=0; $i< count($sep_tags);$i++){
                    if($sep_tags[$i] !='' && $sep_tags[$i]!=' ')
                      echo '<a class="vm_tags" href="'.JRoute::_('index.php?option=com_cooltags&view=productslist&tag='.$sep_tags[$i].'&Itemid='.$cooltags_itemid).'">'.$sep_tags[$i].'</a>&nbsp; ';
                  }
                
              echo '</div>';  
                      }
               } 

          ?>
                                    
                                </div>
                               
                                <div class="clear"></div>
                               
                            </div>
                           <div class="clear"></div>                    
          </li>
            
              
          <?php } ?>
          
          </ul>
</div>
</br>
<?php                    
echo '<div class="pagination2" >';
echo $this->pagination->getResultsCounter();
echo $this->pagination->getPagesLinks();
echo $this->pagination->getPagesCounter();
echo '</div>';
?>
<script type="text/javascript">
 jQuery(document).ready(function($) {
   $(function() {
      $('#product_list.layout2 div.product-box').each(function() {        
        var tip = $(this).find('div.count_holder_small');

        $(this).hover(
            function() { tip.appendTo('body'); },
            function() { tip.appendTo(this); }
        ).mousemove(function(e) {
            var x = e.pageX + 60,
                y = e.pageY + 50,
                w = tip.width(),
                h = tip.height(),
                dx = $(window).width() - (x + w),
                dy = $(window).height() - (y + h);

            if ( dx < 50 ) x = e.pageX - w - 60;
            if ( dy < 50 ) y = e.pageY - h + 130;

            tip.css({ left: x, top: y });
          });         
      });

    });


});
</script>

