<?php

/**
* @version 2.8.15
* @package Joomla 2.5
* @subpackage DT Register
* @copyright Copyright (C) 2006 DTH Development
* @copyright contact dthdev@dthdevelopment.com
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/

 global $Itemid,$month_arr,$now,$xhtml_url,$googlekey,$amp,$show_event_image,$eventListOrder,$spots_column,$hide_full_event,$showlocationfilter,$locationdistanceunit,$eventListOrder;

 $config = $this->getModel('config');

 $categoryTable = $this->getModel('category')->table;
 
 $locationTable = $this->getModel('location')->table;

 $eventTable = $this->getModel('event')->table;

 $document =& JFactory::getDocument();

 $document->addScript( JURI::root(true).'/components/com_dtregister/assets/js/dt_jquery.js');

 $document->addScript( JURI::root(true).'/components/com_dtregister/assets/js/jquery.lightbox.js');

  if(!JModuleHelper::isEnabled('s5_box')){
     $document->addStyleSheet(JURI::root(true).'/components/com_dtregister/assets/css/jquery.lightbox.css');
  }
 
 $document->addStyleSheet(JURI::root(true).'/components/com_dtregister/assets/css/main.css');

 if($config->getGlobal('googlekey','')!==""){

   //$document->addScript( "http://maps.google.com/maps?file=api".$amp."v=2.x".$amp."key=".$googlekey);

 }
 
 //$document->addScript("http://maps.googleapis.com/maps/api/js?sensor=false&language=ja");

 $limit = trim( JRequest::getVar('limit',$config->getGlobal('event_list_number','')) );

$where = array();

$limitstart = trim( JRequest::getVar('limitstart', 0 ) );

$month = JRequest::getVar('month','');

$year = JRequest::getVar('year','');//date('Y',$now->toUnix(true))

jimport('joomla.html.pagination');

$category = JRequest::getVar('category',"");
$location = JRequest::getVar('location',"");
$moderator = JRequest::getVar('moderator',"");
$cartcontinue = JRequest::getVar('cart','');
$advance_search = JRequest::getVar('advance_search',"");
$search = JRequest::getVar('search');
$zip = JRequest::getVar('zip',"");
$distance = JRequest::getVar('distance',"");
$task = JRequest::getVar('task',''); 

$categories = array();
if($task == "category"){

	$cats = array();

	for($i=1;$i<=12;$i++){

	   $cat_id = JRequest::getInt('list'.$i,'');

	   if( $cat_id > 0){
           $categories[] = $cat_id;
		  $cats[] = $config->getDBO()->quote($config->getDBO()->getEscaped( $cat_id));

	   }

	}
    $cat_id = JRequest::getInt('category','');
	if($cat_id > 0){
		$categories[] = $cat_id;
		$cats[] = $config->getDBO()->quote($config->getDBO()->getEscaped( $cat_id));
	}
    
	if(isset($_REQUEST['cat']) && $_REQUEST['cat'] && $_REQUEST['cat'] != 'all') {
		foreach($_REQUEST['cat'] as $cat_id) {
			if($cat_id > 0) {
				$categories[] = $cat_id;
			    $cats[] = $config->getDBO()->quote($config->getDBO()->getEscaped( $cat_id));
			}
			
		}
	}
	
	if(count($cats)>0){

	  // $where[] = " ( c.categoryId in( ".implode(",",$cats)." ) or c.parent_id in (".implode(",",$cats).") )";
	   
	}

 }

if (isset($location) && $location != "") {
	$locations[] = $location;
	// pr($locations);
	$where[] = "  b.location_id in( ".implode(",",$locations)." ) ";
}
$this->show_distance_col = false;

if($zip !== "") {
	
	if($distance != "") {
		$loc = $this->lnglat($zip);
		if($loc['success']) {
			$where['distance'] = array('lat'=>$loc['location']->lat,'lng'=>$loc['location']->lng,'distance'=>$distance);
			//$where['distance'] = "(GLENGTH( LINESTRING(( POINTFROMWKB( POINT( ".$loc['location']->lat." , ".$loc['location']->lng." ))), ( POINTFROMWKB( POINT( l.lat, l.lng ) ))))) * 100 < '$distance'";
			//$where[] = " l.zip = '$zip'";
			//pr($where);
			$this->show_distance_col = true;
		} else {
		
			$where[] = " l.zip = '$zip'";
		
		}
		
	} else {
		$where[] = " l.zip = '$zip'";
	}
}
$search = $config->getDBO()->getEscaped( trim( strtolower( $search ) ) );

if ($search){

   $where[] = "(b.event_describe LIKE '%{$search}%' OR b.title LIKE '%{$search}%' OR c.categoryName LIKE '%{$search}%'  OR l.name LIKE '%{$search}%' OR b.dtstart LIKE '%{$search}%' OR b.dtend LIKE '%{$search}%' OR l.zip like '%{$search}%'  OR l.city like '%{$search}%'  OR l.state like '%{$search}%'  OR l.country like '%{$search}%') ";
	$searchs[] = $search;
	//$where[] = "  b.title LIKE  '%".implode(",",$searchs)."%' ";
	//$where[] = "(b.title LIKE '%{$search}%') ";
	if($moderator != "") {
		
		$where[] = " (u.id = $moderator) ";
		
	}
	if($category != "") {
		$categories[] = $cat_id;
		//$where[] = " (c.categoryId = $category) ";
		
	}
	if($location != "") {
		
		$where[] = " ( l.id = $location ) ";
		
	}

}else if($search && $advance_search != "") {
/*	
title
date
category name
location name
location city, state, country
description
moderator name / username
*/
	
	$where[] = "(b.event_describe LIKE '%{$search}%' OR b.title LIKE '%{$search}%' OR c.categoryName LIKE '%{$search}%'  OR l.name LIKE '%{$search}%' OR b.dtstart LIKE '%{$search}%' OR b.dtend LIKE '%{$search}%' OR u.name LIKE '%{$search}%' OR u.username LIKE '%{$search}%' OR l.city LIKE '%{$search}%' OR l.state LIKE '%{$search}%' OR l.country LIKE '%{$search}%') ";
	
	if($moderator != "") {
		
		$where[] = " (u.id = $moderator) ";
		
	}
	
	if($category != "") {
		$categories[] = $category;
		//$where[] = " (c.categoryId = $category) ";
		
	}
	
	if($location != "") {
		
		$where[] = " ( l.id = $location ) ";
		
	}
} else if($search == "" && $advance_search != "") {
	
	if($moderator != "") {
		
		$where[] = " (u.id = $moderator) ";
		
	}
	
	if($category != "") {
		$categories[] = $category;
		//$where[] = " (c.categoryId = $category) ";
		
	}
	
	if($location != "") {
		
		$where[] = " ( l.id = $location ) ";
		
	}
	
} else {
 if($moderator != "") {
		
		$where[] = " (u.id = $moderator) ";
		
	}

}

if($cartcontinue == 'continue' && DT_Session::get('register.User') && count(DT_Session::get('register.User'))){
 // pr($_SESSION);
  $eventId =  DT_Session::get('register.User.0.eventId');
  $evtTcart = $this->getModel('event')->table;
  $evtTcart->load($eventId);
  $where[] = " b.payment_id = ".$evtTcart->payment_id;
 // prd($_SESSION);
    	
}

if(!$config->getGlobal('show_past_event',0)){

   $where[] = " (b.dtend >= '". $now->toFormat('%Y-%m-%d') ."' or b.dtend = '0000-00-00' or b.dtend Is Null) ";

}

$conf =& JFactory::getConfig();

$tzoffest = $conf->getValue('config.offset');

if($month !="" && $year !="" ){
   
   if(isset($_REQUEST['day'])) {
   		$start_date = new JDate($year."-".$month."-".$_REQUEST['day']);
   } else {
   		$start_date = new JDate($year."-".$month."-01");
   }  

$start_date->setOffset($conf->getValue('config.offset'));

$end_month = $month + 1;

if($end_month > 12){

      $end_month = "01";

	  $end_year = $year + 1;

   }else{

      $end_year = $year;

   }
   
   if(isset($_REQUEST['day'])) { 
        $end_date = new JDate($year."-".$month."-".$_REQUEST['day']);
   } else {
   		$end_date = new JDate($end_year."-".$end_month."-01");
   }

$end_date->setOffset($conf->getValue('config.offset'));
if(isset($_REQUEST['day'])) { 

  $where[] = "( b.dtstart <= '".($start_date->format('Y-m-d'))."'   and b.dtend >=  '".($end_date->format('Y-m-d'))."' )";
} else {
   $where[] = " b.dtstart >= '".($start_date->format('Y-m-d'))."' and b.dtstart <  '".($end_date->format('Y-m-d'))."' ";
}

}

if($month =="" && $year !="" ){

   $start_date = $year."-01-01";

   $end_year =  $year + 1;

   $end_date = $end_year."-01-01";

   $where[] = " b.dtstart >= '".($start_date)."' and b.dtstart <  '".($end_date)."' ";

}

$my = & JFactory::getUser();

if(!$my->id){  // not logged in view only public event

}
$user =& JFactory::getUser();
$access_levels = $user->authorisedLevels();
/*$rows1 = $categoryTable->find('published = 1 and access in('.implode(",",$access_levels).')','lft asc');

$rows2 = $locationTable->find(' 1=1 ');
$arrLocation = array();
foreach ($rows2 as $rows) {
	$arrLocation[$rows->id] = $rows->name;
}

$arrCategory = array();

for ($i=0,$n=count($rows1);$i<$n;$i++) {

	$row1 = $rows1[$i];
	$catId = $row1->categoryId;
	$catName = $row1->categoryName;
	$tmpArr=array($catId=>$catName);
	DTrCommon::array_push_associative($arrCategory,$tmpArr);

}*/

//$rows = $eventListOrder->findalldetail();

//$rows = $eventTable->findalldetail($where,'c.lft asc, b.ordering ASC',0,10);

//$pageNav = new JPagination( $event->getLastCount(), $limitstart, $limit );

		//$limit = trim( JRequest::getVar('limit',$config->getGlobal('event_list_number')) );

		if($limit==""){

			//$limit = $config->getGlobal('event_list_number');

		}

		$limitstart = trim( JRequest::getVar('limitstart', 0 ) );
		$having = array();
if($hide_full_event){
   $having[] = "if(b.max_registrations > 0 and( b.max_registrations - sum(a.memtot))<1 , 0 , 1 )";
   $where['having'] = $having;
}
$ordering = "b.ordering ASC";
$groupby = " group by b.slabId ";
if($eventListOrder == 3) {
   $ordering = " c.lft asc, b.ordering ASC ";
   $groupby = "  group by c.categoryId , b.slabId ";
}

$where['group'] = $groupby;
        $rows = $eventTable->findallevents($categories,array_filter($where)," $ordering ",$limitstart,$limit);
		pr($rows);
		$cnt = $eventTable->getLastCount($eventTable->count_sql); unset($eventTable->count_sql);
		pr($cnt);
		$pageNav = new DtPagination( $cnt, $limitstart, $limit );
        pr($pageNav);
		$link="index.php?option=".DTR_COM_COMPONENT."&Itemid=$Itemid";
  // $this->assign('pageNav',$pageNav);
// pr($rows);

?>

 <script type="text/javascript">

    //<![CDATA[

	DTjQuery(function(){ 

	  window.status='test';

	  DTjQuery(".colorbox").colorbox({width:550, height:550,iframe:true});

	  DTjQuery().bind('cbox_complete', function(){

		 // initialize();

        //setTimeout($.fn.colorbox.next, 1500);

       });

	});

    //]]>

</script>

<form action="<?php echo  JRoute::_("index.php?option=".DTR_COM_COMPONENT."&Itemid=".$Itemid, $xhtml_url ); ?>" method="post" name="frmcart">
	
	<h2><?php echo JText::_( 'DT_EVENT_REGISTRATION' );?></h2>

    <div style="clear:both; margin:0 0 10px 0" class="event_message"><?php echo JText::_( 'DT_EVENT_LIST_INSTRUCTIONS' );?></div>

   <table class="event_message" width="100%" style="border: none; border-collapse: collapse">

    <tr style="border: none; border-collapse: collapse">

    <td align="left" style="border: none; border-collapse: collapse">

    <?php if($config->getGlobal('event_search_show',0)==1){ ?>

    <b><?php echo JText::_( 'DT_SEARCH' ); ?>:</b> 

    <input type="text" name="search" value="<?php echo JRequest::getVar('search',''); ?>" class="inputbox" />

    <input type="submit" value="<?php echo JText::_( 'DT_SEARCH_GO' );?>" />

    <?php } ?>

    </td>

    <td style="border: none; border-collapse: collapse">

    <?php 

	if($config->getGlobal('month_filter_show',0)){ // month filter flag 

	  $month_opts=DtHtml::options($month_arr,JText::_( 'DT_SELECT_MONTH' ));

	  echo JHTML::_('select.genericlist', $month_opts,"month",'onchange="submit()"',"value","text",$month); 

      $year_opts = array();

	  $year_opts[] = JHTML::_('select.option',"",JText::_( 'DT_SELECT_YEAR' ));

      for($i=2020; $i > 2012; $i-- ){

	    $year_opts[]=JHTML::_('select.option',$i,$i);

	  }

	  echo JHTML::_('select.genericlist', $year_opts,"year",'onchange="submit()"',"value","text",$year); 

	  ?>

       </td>     

       <?php }else{

	     $month = "";

	   } ?> 

    	<td align="right" style="border: none; border-collapse: collapse">

         <?php if($config->getGlobal('event_filter_show',0)==1){?>

        <?php

		$options = DtHtml::options( $categoryTable->optionslist_filtered(),JText::_( 'DT_CATEGORY_VIEW' ));
		echo JHTML::_('select.genericlist', $options,"category",'onchange="submit()"',"value","text",JRequest::getVar('category','')); ?>

        <?php } ?>

      </td>
      
      	<td align="right" style="border: none; border-collapse: collapse">

         <?php if($config->getGlobal('event_location_show',0)==1){?>

        <?php

		 $options = DtHtml::options( $locationTable->optionslist(),JText::_( 'DT_LOCATION_VIEW' ));

		 echo JHTML::_('select.genericlist', $options,"location",'onchange="submit()"',"value","text",JRequest::getVar('location','')); ?>

         <?php } ?>

      </td>      
      <?php if($showlocationfilter) {?>
      <td align="right" style="border: none; border-collapse: collapse">

         <?php echo JText::_('DT_ZIPCODE');?>  <input size="5" type="text" name="zip" value="<?php echo JRequest::getVar('zip',''); ?>" class="inputbox" />

         <?php echo JText::_('DT_WITHIN')."&nbsp;";

         $options = DtHtml::options( array(5=>5,10=>10,20=>20,30=>30,50=>50,100=>100,200=>200),JText::_( 'DT_DISTANCE' ));

		 echo JHTML::_('select.genericlist', $options,"distance",'onchange="submit()"',"value","text",JRequest::getVar('distance',''));

		 if($locationdistanceunit == 'km') {
		  	
			 echo JText::_('DT_KILOMETERS');
			 
		 } else {
		 	
			 echo JText::_('DT_MILES');		 				
		 }
		 ?>
         
      </td>      
      <?php } ?>
     </tr>

   </table>

   <table class="event_message" width="100%">
      <?php
	     $page_links = $pageNav->getPagesLinks($link);
	   if(strlen(trim($page_links))) {
	  		echo '<tr><td colspan="6"><div class="pagination">'.$pageNav->getPagesLinks($link)."</div></td></tr>";
	   }
	  ?>
      <tr>
      <?php if($show_event_image){?>
       <th class="coltitle" align="left"> </th>
       <?php } ?>
      <th class="coltitle" align="left" width="<?php echo $config->getGlobal('event_field_width',0); ?>"><?php echo JText::_( 'DT_EVENT' );?></th>

         <?php $j=2;
		  if( $config->getGlobal('event_date_show',0)){ 
		  $j++;
		   ?>
 
		    <th class="coltitle" align="left" width="<?php echo $config->getGlobal('event_date_width',0); ?>"><?php echo JText::_( 'DT_DATE' );?></th>

        <?php } ?>

	<?php

		if($config->getGlobal('price_column',0)){

           $j++;

			echo '<th class="coltitle" align="left">'.JText::_( 'DT_PRICE' ). '</th>';

		}

		if($config->getGlobal('capacity_column',0)){

           $j++;

			echo '<th class="coltitle" align="left">'.JText::_( 'DT_CAPACITY' ). '</th>';

		}

		if($config->getGlobal('registered_column',0)){

          $j++;

			echo '<th class="coltitle" align="left">'.JText::_( 'DT_REGISTERED' ).'</th>';
			
		}
		if($spots_column) {
			$j++;

			echo '<th class="coltitle" align="left">'.JText::_( 'DT_SPOTS' ).'</th>';
		}
		
		if($this->show_distance_col) {
		  $j++;
		  echo '<th class="coltitle" align="left">'.JText::_( 'DT_DISTANCE' ).'</th>';
		}
	
	?>

	</tr>

    <?php

	if($rows){

     
	//Get the number of registrants

	//End the number of registrants

	$link="index.php?option=com_dtregister&Itemid=$Itemid";

	$prevCat=NULL;

	$currCat=NULL;

	// Display an event on each row

    $k = 0;

	$prevCat = NUll;

	$parent = $categoryTable;
    
	for($i=0,$n=count($rows);$i<$n;$i++){

		if($k == 0){$bgRow='eventListRow1';}else{$bgRow='eventListRow2';}

		$row=$rows[$i];
		
        if($row->max_registrations > 0  && $hide_full_event == 1 && ($row->max_registrations - $row->registered) < 1) {
			
			//continue;
		}
		$currCat = $row->categoryId;

		if(($currCat!=$prevCat || $currCat=="") && $eventListOrder == 3){
	
				$cat_str = "";
				foreach( $parent->getPath($row->categoryId) as $cat) {
					if(strtolower($cat->categoryName) ==  'root'){
					   continue;
					}
					if($cat_str != "") {
					     $cat_str .= " >> ";
					 }
					$cat_str .= $cat->categoryName;
				}
				if($cat_str != "")
				echo '<tr class="categoryRow"><td colspan="'.$j.'"  >'.$cat_str .'</td></tr>';

		}

        $this->assign('row',$row);

		$this->assign('bgRow',$bgRow);

		$this->assign('prevCat',$prevCat);

		$this->assign('currCat',$currCat);

		echo $this->loadTemplate('row');

		$prevCat = $currCat;

		$k = 1-$k;

	} ?>

	<br />

	<?php 

	  $link="index.php?option=".DTR_COM_COMPONENT."&Itemid=$Itemid";
      if(strlen(trim($page_links))) {
		  
	  		echo '<tr><td colspan="6"><div class="pagination">'.$pageNav->getPagesLinks($link)."</div></td></tr>";
			
	  }

	}else if (!$rows && $search){

		echo "<tr><td colspan='2'>".JText::_( 'DT_NO_SEARCH_RESULTS' )."</td></tr>";

	} else {

		// no events to list

		echo "<tr><td colspan='2'>".JText::_( 'DT_NO_EVENTS' )."</td></tr>";

	} // END -> if($rows)

	?>

   </table> 

   <input type="hidden" name="option" value="<?php echo DTR_COM_COMPONENT; ?>" />
   <input type="hidden" name="controller" value="event" />
   <input type="hidden" name="task" value="category" />
   <input type="hidden" name="limitstart" value="<?php echo $pageNav->limitstart; ?>" />
    <?php
   if($advance_search !="") {
   ?>
   	<input type="hidden" name="advance_search" value="yes" />  
    
   <?php
    }
   ?>
   
    <?php
   if($moderator !="") {
   ?>
   	<input type="hidden" name="moderator" value="<?php echo $moderator ?>" />
   <?php
    }
   ?>
   <?php
   if($config->getGlobal('event_filter_show',0)!=1 && $advance_search !="" && $category !=""){
   ?>	   
	 
     <input type="hidden" name="category" value="<?php echo $category ?>" />
   <?php  
   }
   ?>

   <?php
   if($config->getGlobal('event_location_show',0)!=1 && $advance_search !="" && $location !=""){
   ?>	   
	 
     <input type="hidden" name="location" value="<?php echo $location ?>" />
   <?php  
   }
   ?>
</form>
<script type="text/javascript">
	
	DTjQuery(function() {
		
		DTjQuery('#simple_search').click(function(){
			reset_adv_search();
			
			document.frmcart.submit();
		});
		
	});
	function reset_adv_search() {
		
		document.frmcart.limitstart.value = '0';
		if(typeof document.frmcart.moderator != 'undefined')
		document.frmcart.moderator.value = "";
		if(typeof document.frmcart.advance_search != 'undefined')
		document.frmcart.advance_search.value = "";
		
	}

</script>