<?php
/**
* @version 1.0.0
* @package RSEvents! 1.0.0
* @copyright (C) 2009 www.rsjoomla.com
* @license GPL, http://www.gnu.org/copyleft/gpl.html
*/

defined( '_JEXEC' ) or die( 'Restricted access' ); 
require_once(JPATH_SITE.DS.'components'.DS.'com_rsevents'.DS.'models'.DS.'events.php');

class RSEventsCalendar
{
	/**
	 * Array containing the order of week days
	 * @var array
	 */
	var $_weekdays = array();
	
	/**
	 * Week starts on this day
	 * @var int 
	 * @val 0,1,6
	 */
	var $_weekstart = 1;
	
	/**
	 * Week ends on this day
	 * @var int 
	 * @val 6,0,5
	 */
	var $_weekend = 0;
	
	/**
	 * Array containing all months
	 * @var array
	 */
	var $_months = array();
	
	/**
	 * Show title
	 * @var int 
	 * @val 1-12
	 */
	var $showtitle;
	
	/**
	 * Current month
	 * @var int 
	 * @val 1-12
	 */
	var $_month;
	
	/**
	 * Number of days in current month
	 * @var int 
	 * @val 28-31
	 */
	var $_month_days;
	
	/**
	 * The first day of the month in unix format
	 * @var int 
	 */
	var $_month_start_unixdate;
	
	/**
	 * The first day of the month in week format
	 * @var int 
	 * @val 1-7
	 */
	var $_month_start_day;
	
	/**
	 * Current year
	 * @var int 
	 */
	var $_year;
	
	/**
	 * Unix date used in calculations
	 * @var int 
	 */
	var $_unixdate;
	
	/**
	 * Today's date j.n.Y
	 * @var string
	 */
	var $today;
	
	/**
	 * If US format, starts with Sunday instead of Monday
	 * @var boolean
	 */
	var $is_us_format = false;
	
	/**
	 * If is module, shows the small calendar
	 * @var boolean
	 */
	var $is_module = false;
	
	/**
	 * If is module, set the class suffix
	 * @var string
	 */
	var $class_suffix ;
	
	/**
	 * Array of events
	 * @var array
	*/
	var $_events = array();
	
	/**
	 * Array of dates that contain events
	 * @var array
	*/
	var $_event_dates = array();
	
	/**
	 * List of events 
	 * @var string
	*/
	var $_event_list = null;
	
	/**
	 * List of event details 
	 * @var string
	*/
	var $_event_details = null;
	
	/**
	* Initializes the calendar based on today's date
	*/
	function RSEventsCalendar()
	{
		global $mainframe;
		$params = &$mainframe->getParams();
		$this->_weekstart = $params->get('startday','1');
		
		$startday = JRequest::getVar('startday', false);
		if ($startday !== false)
			$this->_weekstart = $startday;
		$this->_getEvents();
		
		$this->today = date('j.n.Y');
		$this->setDate();
	}
	
	/**
	* Sets the date
	* @access public
	* @return true if successful
	*/
	function setDate($month=0, $year=0)
	{
		$this->setWeekStart($this->_weekstart);
		$this->_setMonths();
		$month = $month == 0 ? date('n') : $month;
		$year = $year == 0 ? date('Y') : $year;
		
		if (is_numeric($year) && $year >=1970)
			$this->_year = (int) $year;
			
		if (is_numeric($month) && $month >= 1 && $month <= 12)
		{
			$this->_month = (int) $month;
			$this->_setDate();
			$this->_month_days = date('t', $this->_unixdate);
			$this->_month_start_unixdate = strtotime(date('Y-m-01', $this->_unixdate));
			$this->_month_start_day = date('w', $this->_month_start_unixdate);
			
			$this->_createMonthObject();
		}
		return true;
	}
	
	function setWeekStart($i)
	{
		switch ($i)
		{
			case 0:
			if($this->is_module)
			$this->_weekdays = array(
			0 => JText::_('RSE_MONTH_SHORT_SUNDAY'),
			1 => JText::_('RSE_MONTH_SHORT_MONDAY'),
			2 => JText::_('RSE_MONTH_SHORT_TUESDAY'),
			3 => JText::_('RSE_MONTH_SHORT_WEDNESDAY'),
			4 => JText::_('RSE_MONTH_SHORT_THURSDAY'),
			5 => JText::_('RSE_MONTH_SHORT_FRIDAY'),
			6 => JText::_('RSE_MONTH_SHORT_SATURDAY')
			);
			else $this->_weekdays = array(
			0 => JText::_('RSE_MONTH_SUNDAY'),
			1 => JText::_('RSE_MONTH_MONDAY'),
			2 => JText::_('RSE_MONTH_TUESDAY'),
			3 => JText::_('RSE_MONTH_WEDNESDAY'),
			4 => JText::_('RSE_MONTH_THURSDAY'),
			5 => JText::_('RSE_MONTH_FRIDAY'),
			6 => JText::_('RSE_MONTH_SATURDAY')
			);
			$this->_weekstart = 0;
			$this->_weekend = 6;
			break;
			
			case 1:
			if($this->is_module)
			$this->_weekdays = array(
			1 => JText::_('RSE_MONTH_SHORT_MONDAY'),
			2 => JText::_('RSE_MONTH_SHORT_TUESDAY'),
			3 => JText::_('RSE_MONTH_SHORT_WEDNESDAY'),
			4 => JText::_('RSE_MONTH_SHORT_THURSDAY'),
			5 => JText::_('RSE_MONTH_SHORT_FRIDAY'),
			6 => JText::_('RSE_MONTH_SHORT_SATURDAY'),
			0 => JText::_('RSE_MONTH_SHORT_SUNDAY')
			);
			else $this->_weekdays = array(
			1 => JText::_('RSE_MONTH_MONDAY'),
			2 => JText::_('RSE_MONTH_TUESDAY'),
			3 => JText::_('RSE_MONTH_WEDNESDAY'),
			4 => JText::_('RSE_MONTH_THURSDAY'),
			5 => JText::_('RSE_MONTH_FRIDAY'),
			6 => JText::_('RSE_MONTH_SATURDAY'),
			0 => JText::_('RSE_MONTH_SUNDAY')
			);
			$this->_weekstart = 1;
			$this->_weekend = 0;
			break;
			
			case 6:
			if($this->is_module)
			$this->_weekdays = array(
			6 => JText::_('RSE_MONTH_SHORT_SATURDAY'),
			0 => JText::_('RSE_MONTH_SHORT_SUNDAY'),
			1 => JText::_('RSE_MONTH_SHORT_MONDAY'),
			2 => JText::_('RSE_MONTH_SHORT_TUESDAY'),
			3 => JText::_('RSE_MONTH_SHORT_WEDNESDAY'),
			4 => JText::_('RSE_MONTH_SHORT_THURSDAY'),
			5 => JText::_('RSE_MONTH_SHORT_FRIDAY')
			);
			else $this->_weekdays = array(
			6 => JText::_('RSE_MONTH_SATURDAY'),
			0 => JText::_('RSE_MONTH_SUNDAY'),
			1 => JText::_('RSE_MONTH_MONDAY'),
			2 => JText::_('RSE_MONTH_TUESDAY'),
			3 => JText::_('RSE_MONTH_WEDNESDAY'),
			4 => JText::_('RSE_MONTH_THURSDAY'),
			5 => JText::_('RSE_MONTH_FRIDAY')
			);
			$this->_weekstart = 6;
			$this->_weekend = 5;
			break;
		}
	}
	
	function _setMonths()
	{
		$this->_months = array(
		'1' => JText::_('RSE_JANUARY'),
		'2' => JText::_('RSE_FEBRUARY'),
		'3' => JText::_('RSE_MARCH'),
		'4' => JText::_('RSE_APRIL'),
		'5' => JText::_('RSE_MAY'),
		'6' => JText::_('RSE_JUNE'),
		'7' => JText::_('RSE_JULY'),
		'8' => JText::_('RSE_AUGUST'),
		'9' => JText::_('RSE_SEPTEMBER'),
		'10' => JText::_('RSE_OCTOBER'),
		'11' => JText::_('RSE_NOVEMBER'),
		'12' => JText::_('RSE_DECEMBER')
		);
	}
	
	/**
	* Sets the unix date used in calculations
	* @access private
	*/
	function _setDate()
	{
		$this->_unixdate = mktime(0,0,0,$this->_month,1,$this->_year);
	}
	
	/**
	* Get the events
	* @access private
	*/
	function _getEvents()
	{
		global $mainframe;
		$params = &$mainframe->getParams();
		require_once(JPATH_SITE.DS.'components'.DS.'com_rsevents'.DS.'models'.DS.'events.php');
		$events = rseventsModelEvents::getEventCalendar($params);
		
		foreach ($events as $event)
		{
			$this->_events[$event->IdEvent] = $event;
			
			// Event start date
			$this->_event_dates[date('d.m.Y', $event->EventStartDate)][$event->IdEvent] = $event->IdEvent;
			
			// Event occuring dates
			$start = mktime(0, 0, 0, date('n', $event->EventStartDate), date('j', $event->EventStartDate), date('Y', $event->EventStartDate));
			$end = mktime(0, 0, 0, date('n', $event->EventEndDate), date('j', $event->EventEndDate), date('Y', $event->EventEndDate));
			for ($i=$start; $i<=$end; $i+=86400)
				$this->_event_dates[date('d.m.Y', $i)][$event->IdEvent] = $event->IdEvent;
				
			// Event end date	
			$this->_event_dates[date('d.m.Y', $event->EventEndDate)][$event->IdEvent] = $event->IdEvent;
		}
	}
	
		
	/**
	* Show details of the events
	* @access private
	*/
	function _showDetails($event, $type)
	{
		$details = '';
		switch ($type)
		{
			case 'component': $details = $this->_showDetailsComponent($event); break;
			case 'module': $details = $this->_showDetailsModule($event); break;
		}
		return $details;
	}
	
	function _showDetailsComponent($event)
	{
		global $mainframe;
		
		$rseventsConfig = $mainframe->getUserState('rseventsConfig');
		
		$details = '';
		$details .= JText::_('RSE_STARTS_ON').' '.rseventsHelper::translateDate(date($rseventsConfig['global.dateformat'],$event->EventStartDate)).'<br/>';
		$details .= JText::_('RSE_ENDS_ON').' '.rseventsHelper::translateDate(date($rseventsConfig['global.dateformat'],$event->EventEndDate)).'<br/>';
		$details .= JText::_('RSE_AT_LOCATION').': '.$event->LocationName.'<br/>';
		
		return $details;
	}
	
	function _showDetailsModule($event)
	{
		$lang =& JFactory::getLanguage();
		$lang->load('com_rsevents',JPATH_SITE);
		
		$details = '';
		if (!empty($event))
		{
			$count = count($event);
			
			$details = $count.' '.JText::_('RSE_EVENT_MODULE').($count > 1 ? JText::_('RSE_EVENT_MODULE_PLURAL') : '').'::';
			$i = 0;
			foreach ($event as $IdEvent)
			{
				$i++;
				$details .= $this->_events[$IdEvent]->EventName.($i != $count ? ', ' : '');
			}
		}
		else
			$details = JText::_('RSE_NO_EVENTS_MODULE').'::';
		
		return $details;
	}
	
	function _createMonthObject()
	{
		$month = new stdClass();
		// Days in order
		$month->weekdays = $this->_weekdays;
		// Number of days in month
		$month->nr_days = $this->_month_days;
		// Days
		$month->days = array();
		
		// Days in previous month
		if ($this->_month_start_day != $this->_weekstart)
		{
			$day->day = $this->_weekstart;
		
			$i = 0;
			foreach ($this->_weekdays as $position => $weekday)
				if ($position == $this->_month_start_day)
					break;
				else
					$i++;
			
			for ($i; $i>0; $i--)
			{
				$day = new stdClass();
				$unixdate = strtotime('-'.$i.' days', $this->_month_start_unixdate);
				$day->unixdate = $unixdate;
				$day->day = date('w', $unixdate);
				$day->week = date('W', $unixdate);
				$day->class = 'prev-month';
				$day->events = false;
				if (!empty($this->_event_dates[date('d.m.Y', $unixdate)]))
					$day->events = $this->_event_dates[date('d.m.Y', $unixdate)];
				if (!empty($day->events))
					$day->class .= ' has-events';
				
				$month->days[] = $day;
			}
		}
		
		// Days in current month
		for ($i=1; $i<=$month->nr_days; $i++)
		{
			$day = new stdClass();
			$unixdate = mktime(0, 0, 0, $this->_month, $i, $this->_year);
			$day->unixdate = $unixdate;
			$day->day = date('w', $unixdate);
			$day->week = date('W', $unixdate);
			$day->class = 'curr-month';
			if (date('d.m.Y', $day->unixdate) == date('d.m.Y'))
				$day->class .= ' curr-day';
			$day->events = false;
				if (!empty($this->_event_dates[date('d.m.Y', $unixdate)]))
					$day->events = $this->_event_dates[date('d.m.Y', $unixdate)];
			if (!empty($day->events))
				$day->class .= ' has-events';
			
			$month->days[] = $day;
		}
		
		// Days in next month
		$i = 1;
		if ($day->day != $this->_weekend)
			while($day->day != $this->_weekend)
			{
				$day = new stdClass();
				$unixdate = mktime(0, 0, 0, $this->_month, $month->nr_days+$i, $this->_year);
				$day->unixdate = $unixdate;
				$day->day = date('w', $unixdate);
				$day->week = date('W', $unixdate);
				$day->class = 'next-month';
				$day->events = false;
				if (!empty($this->_event_dates[date('d.m.Y', $unixdate)]))
					$day->events = $this->_event_dates[date('d.m.Y', $unixdate)];
				if (!empty($day->events))
					$day->class .= ' has-events';
				$i++;
				
				$month->days[] = $day;
			}
		
		$this->_days = $month;
	}
	
	/**
	* Display the calendar 
	* @access private
	*/
	function display() 
	{
		global $mainframe;
		$db =& JFactory::getDBO();
		$idcateg = JRequest::getVar('idcat','','post');
		
		
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		
		$params = &$mainframe->getParams();
		$show_week = $params->get('sweek','1');
		$show_details = $params->get('detailview','1');
		$show_catfil = $params->get('catfil','1');
		
		$db->setQuery("SELECT IdCategory,CategoryName FROM #__rsevents_categories WHERE published = 1");
			
		$catlist[]           = JHTML::_('select.option',  '', JText::_( 'RSE_EVENT_SELECT_CATEGORY' ), 'IdCategory', 'CategoryName' );
		$catlist         	 = array_merge( $catlist, $db->loadObjectList() );
		$lists['categories'] = JHTML::_('select.genericlist', $catlist, 'idcat', 'size="1"','IdCategory', 'CategoryName', $idcateg );
	
		$suffix       = $this->is_module ? 'module' : 'component';
	?>
	
		<div id="rsevents_calendar_<?php echo $suffix; ?>" class="rsevents_calendar_<?php echo $suffix.$this->class_suffix; ?>">
		<?php if(!$this->is_module) { ?><form action="<?php echo JRoute::_('index.php?option=com_rsevents&view=calendar'.$itemId);?>" method="post"><?php } ?>
		
		<table cellpadding="0" cellspacing="2" border="0" width="100%">
			<tr>
				<td align="left">
					<a rel="nofollow" href="<?php echo JRoute::_('index.php?option=com_rsevents&view=calendar&month='.date('m', strtotime('-1 month', $this->_unixdate)).'&year='.date('Y', strtotime('-1 month', $this->_unixdate)).($this->is_module ? '&format=raw&tmpl=component' : '').$itemId); ?>" <?php if($this->is_module){ ?> onclick="rse_calendar_change_month('<?php echo JURI::root(); ?>index.php?option=com_rsevents&view=calendar&month=<?php echo date('m', strtotime('-1 month', $this->_unixdate)).'&year='.date('Y', strtotime('-1 month', $this->_unixdate));?>&format=raw&tmpl=component&startday=<?php echo $this->_weekstart; ?><?php echo $itemId; ?>'); return false;" <?php } ?>>&laquo;</a>
				</td>
				<?php if($this->is_module) { ?>
				<td align="center"><?php echo $this->_months[$this->_month].' '.date('Y', $this->_unixdate); ?></td>
				<?php } else { ?>
				<td align="center">
					<input type="hidden" name="option" value="com_rsevents" />
					<input type="hidden" name="view" value="calendar" />
					<select name="month">
					<?php foreach ($this->_months as $i => $month) { ?>
					<option <?php echo $this->_month == $i ? 'selected="selected"' : ''; ?> value="<?php echo $i; ?>"><?php echo $month; ?></option>
					<?php } ?>
					</select>
					<select name="year">
					<?php for($i=1999;$i<=2037;$i++) {  ?>
					<option <?php echo $this->_year == $i ? 'selected="selected"' : ''; ?> value="<?php echo $i; ?>"><?php echo $i; ?></option>
					<?php } ?>
					</select>
					<?php if($show_catfil) echo $lists['categories']; ?>
					<button type="submit"><?php echo JText::_('RSE_GO'); ?></button>
				</td>
				<?php } ?>
				<td align="right">
					<a rel="nofollow" href="<?php echo JRoute::_('index.php?option=com_rsevents&view=calendar&month='.date('m', strtotime('+1 month', $this->_unixdate)).'&year='.date('Y', strtotime('+1 month', $this->_unixdate)).($this->is_module ? '&format=raw&tmpl=component' : '').$itemId); ?>" <?php if($this->is_module){ ?> onclick="rse_calendar_change_month('<?php echo JURI::root(); ?>index.php?option=com_rsevents&view=calendar&month=<?php echo date('m', strtotime('+1 month', $this->_unixdate)).'&year='.date('Y', strtotime('+1 month', $this->_unixdate));?>&format=raw&tmpl=component&startday=<?php echo $this->_weekstart; ?><?php echo $itemId; ?>'); return false;"<?php } ?>>&raquo;</a>
				</td>
			</tr>
		</table>
		
		<table class="rsevents_calendar_<?php echo $suffix; ?>" cellpadding="0" cellspacing="0" width="100%">
			<thead>
				<tr>
					<?php  if(!$this->is_module && $show_week ==1) { ?><th width="3%"><?php echo JText::_('RSE_WEEK'); ?></th><?php } ?>
					<?php foreach ($this->_days->weekdays as $weekday) { ?>
					<th><?php echo $weekday; ?></th>
					<?php } ?>
				</tr>
			</thead>
			<tbody>
			<?php foreach ($this->_days->days as $day) {
					if ($day->day == $this->_weekstart) { ?>
						<tr>
						<?php if (!$this->is_module && $show_week ==1) { ?>
							<td class="week"><a href="<?php echo JRoute::_('index.php?option=com_rsevents&view=calendar&layout=week&date='.date('m/d/Y', $day->unixdate).$itemId); ?>"><?php echo $day->week; ?></a></td>
						<?php } ?>
					<?php } ?>
					
					<td class="<?php echo $day->class; ?>"><a href="<?php echo JRoute::_('index.php?option=com_rsevents&view=calendar&layout=day&date='.date('m/d/Y',$day->unixdate).$itemId);?>" <?php echo $this->is_module ? 'class="editlinktip hasTip" title="'.$this->_showDetails($day->events, $suffix).'"' : ''; ?>>
					<?php echo date('j', $day->unixdate); ?></a>
						<?php if (!empty($day->events) && !$this->is_module && $show_details == 0) { ?> 
							<div class="rse_event">
								<a style="text-decoration:none;cursor:pointer;" class="editlinktip hasTip" title="<?php echo $this->_showDetails($day->events, 'module'); ?>"><?php echo count($day->events).' '.(count($day->events) > 1 ? JText::_('RSE_EVENTS') : JText::_('RSE_EVENT')); ?></a>
							</div>
						<?php } ?>
					<?php if (!empty($day->events) && !$this->is_module && $show_details == 1) foreach ($day->events as $event) { ?>
						<div class="rse_event">
							<a href="<?php echo JRoute::_('index.php?option=com_rsevents&view=events&layout=show&cid='.$event.$itemId); ?>" class="editlinktip hasTip" title="<?php echo $this->_events[$event]->EventName; ?>::<?php echo $this->_showDetails($this->_events[$event], $suffix); ?>"><?php echo $this->_events[$event]->EventName; ?></a>
						</div>
					<?php } ?>
					</td>
					<?php if ($day->day == $this->_weekend) { ?></tr><?php } ?>
			<?php } ?>			
			</tbody>
		</table>
		<?php if(!$this->is_module) { ?>
		<br/>
		<?php if($show_catfil) { ?>
		<input type="hidden" name="fromcalendar" value="1" />
		<?php } ?>
		</form>
		<?php } ?>
		</div>
	<?php } 
	
}