<?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();
 
jimport( 'joomla.application.component.model' );

class rseventsModelEvents extends JModel
{
	var $_query;
	var $_data;
	var $_total=null;
	var $_pagination=null;
	var $_componentList=null;
	
	//buiding the display query
	
	function _buildQuery()
	{
		global $mainframe;
		$rseventsConfig = $mainframe->getUserState('rseventsConfig');
		$post = JRequest::get('post');
		$db= & JFactory::getDBO();
		$user = & JFactory::getUser();
		
		$layout = JRequest::getVar('layout','','request');
		$cid = intval(JRequest::getVar('cid',0,'request'));
		$filter = JRequest::getVar('rse_filter','','request');
		$direction = JRequest::getVar('direction','','request');
		$c_filter = intval(JRequest::getVar('cat_filter','','request'));
		$l_filter = intval(JRequest::getVar('loc_filter','','request'));
		
		$params = &$mainframe->getParams();
		
		switch($layout)
		{
			case 'listmyevents':
				
				$where = " AND e.IdUser=".$user->id; 
				$published = '';
				$filter ='';
			break;
			
			case 'archive':
			
				$esearch = $params->get('search','0');
				$search_filter = JRequest::getVar('rse_search_archive','','request');
				$where = ''; 
				if($esearch == 1) $where  = " AND e.EventName LIKE '%".$db->getEscaped($search_filter)."%' ";
				$published = ' AND e.published = -1 ';
				$filter ='';
			break;
			
			case 'listdaysevent':
				
				$startDate = $params->get('startDate','01/01/1999');
				$endDate = $params->get('endDate','01/01/2037');
				$startTime = $params->get('startTime','00');
				$endTime = $params->get('endTime','00');
				$start = strtotime($startDate.' '.$startTime.':00');
				$end = strtotime($endDate.' '.$endTime.':00');
			
				$published = " AND e.published = 1 ";
				
				$q1 = ' AND e.EventStartDate >= '.$start;
				$q2 = ' AND e.EventEndDate <= '.$end;
				$q3 = ' AND e.EventType = 1 ';
				$where = $q1 . $q2 . $q3;
				$filter ='';
			break;
			
			case 'listcategoryevents':
				
				$published = " AND e.published = 1 ";
				$where = " AND c.IdCategory = ".$cid;
				$where .= " AND e.EventType = 1 ";
				$filter ='';
			break;
			
			case 'listlocationevents':
			
				$published = " AND e.published = '1' ";
				$where = " AND l.IdLocation = '".$cid."'";
				$where .= " AND e.EventType = '1' ";
				$filter ='';
			break;
			
			case 'featureevents':
			
				$days = intval($params->get('days','3'));
				$sTime = time();
				$eTime = $sTime + ( $days * 86400);
				$published = " AND e.published = '1' ";
				$where = " AND e.EventStartDate >= ".$sTime." AND e.EventStartDate <= ".$eTime." ";
				$filter ='';
			break;
			
			case 'search':
			
			$where = '';
			$published = " AND e.published = 1 "; 
			$filter = '';
			
			if(isset($post['IdCategory']))
			{
				$categIds = implode(',',$post['IdCategory']);
				$where .= " AND c.IdCategory IN (".$categIds.") ";
			}
			
			if(isset($post['IdLocation']))
			{
				$locIds = implode(',',$post['IdLocation']);
				$where .= " AND l.IdLocation IN (".$locIds.") ";
			}
			
			if(isset($post['rseStartDate']))
			{
				$sdate = strtotime($post['rseStartDate']);
				$where .= " AND e.EventStartDate >= ".$sdate." ";
			}
			
			if(isset($post['rseEndDate']))
			{
				$edate = strtotime($post['rseEndDate']);
				$where .= " AND e.EventEndDate <= ".$edate." ";
			}
			
			if(isset($post['rse_keyword']))
			$filter = " AND e.EventName LIKE '%".$db->getEscaped($post['rse_keyword'])."%' ";
			
			break;
			
			default:
				
				if($params->get('expired','0') == 1)
				$published = " AND e.published IN ('-1','1') ";
				else
				$published = " AND e.published = '1' ";
				$where = " AND e.EventType = '1' ";
				$expired ='';
				if ($c_filter == 0) $categ_filter = ''; else $categ_filter = " AND c.IdCategory = '".$c_filter."' ";
				if ($l_filter == 0) $loc_filter = ''; else $loc_filter = " AND l.IdLocation = '".$l_filter."' ";
				$filter =" AND (e.EventName LIKE '%".$db->getEscaped($filter)."%' OR e.EventDescription LIKE '%".$db->getEscaped($filter)."%' OR c.CategoryName LIKE '%".$db->getEscaped($filter)."%' OR l.LocationName LIKE '%".$db->getEscaped($filter)."%') ".$categ_filter.$loc_filter;
			break;
		}
		
		if(!empty($direction))
			$ordering = $direction;
		else	
			$ordering = $params->get('order','DESC');
		
		$columns[] = 'e.IdEvent';
		$columns[] = 'e.EventName';
		$columns[] ='e.EventSubtitle';
		$columns[] ='e.EventDescription';
		$columns[] ='l.LocationName';
		$columns[] ='e.EventStartDate';
		$columns[] ='e.EventEndDate';
		$columns[] ='e.EventHost';
		$columns[] ='l.IdLocation';
		$columns[] ='e.EventIcon';
		$columns[] ='e.EventCreation';
		$columns = implode(',',$columns);
		
		$this->_query = "SELECT ".$columns." FROM #__rsevents_events e "
					  ."LEFT JOIN #__rsevents_locations l ON e.IdLocation=l.IdLocation "
					  ."LEFT JOIN #__rsevents_events_cat ec ON ec.IdEvent = e.IdEvent "
					  ."LEFT JOIN #__rsevents_categories c ON c.IdCategory = ec.IdCategory "
					  ."WHERE 1=1 ".$published.$where.$filter." GROUP BY e.IdEvent  ORDER BY e.EventStartDate ".$ordering;
		
		
		//echo $this->_query;
	}
	
	
	function __construct($calendar=false)
	{	
		parent::__construct();
		
		if ($calendar)
			JRequest::setVar('cid', 0);
		
		$this->_buildQuery();
		global $mainframe, $option;

		// Get pagination request variables
		$limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
		$limitstart	= JRequest::getVar('limitstart', 0, '', 'int');
		
		// In case limit has been changed, adjust it
		$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
		
		if ($calendar)
		{
			$limit = 0;
			$limitstart = 0;
		}
		
		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);
	}
	
	//getting all the data 
	
	function getData()
	{
		if (empty($this->_data))
		{
			$this->_data=$this->_getList($this->_query,$this->getState('limitstart'), $this->getState('limit'));
		}
		return $this->_data;
	}
	
	function getTotal()
	{
		// Load the content if it doesn't already exist
		if (empty($this->_total))
		{
			$this->_total = $this->_getListCount($this->_query);	
		}
		return $this->_total;
	}
	
	function getPagination()
	{
		// Load the content if it doesn't already exist
		if (empty($this->_pagination))
		{
			jimport('joomla.html.pagination');
			$this->_pagination = new JPagination($this->getTotal(), $this->getState('limitstart'), $this->getState('limit'));
		}
		return $this->_pagination;
	}
	
	//load the event
	
	function getEvent($idEvent=null)
	{
		global $mainframe;
		$db = & JFactory::getDBO();
		$rseventsConfig = $mainframe->getUserState('rseventsConfig');
		$idEvent= ($idEvent == null) ? JRequest::getVar('cid',0) : $idEvent;
		$idEvent= intval($idEvent);
		$db->setQuery("SELECT e.*, d.DesignName , l.IdLocation, l.LocationName, l.LocationAddress, l.LocationCity ,l.LocationCountry, l.LocationState ,l.IdLocation , l.LocationZip , l.locationCountry, f.FileName, f.FileLocation , u.username AS EventOwner "
					  ."FROM #__rsevents_events e "
					  ."LEFT JOIN #__rsevents_locations l ON e.IdLocation = l.IdLocation   "
					  ."LEFT JOIN #__rsevents_events_cat ec ON ec.IdEvent = e.IdEvent "
					  ."LEFT JOIN #__rsevents_categories c ON c.IdCategory = ec.IdCategory "
					  ."LEFT JOIN #__rsevents_designs d ON e.IdDesign = d.IdDesign "
					  ."LEFT JOIN #__users u ON e.IdUser = u.id "
					  ."LEFT JOIN #__rsevents_files f ON f.IdEvent=e.IdEvent "
					  ."WHERE e.IdEvent='".$idEvent."'");
		$row=$db->loadObject();
		
		if(empty($row)) $row=rseventsModelEvents::initEvent();
		if(empty($row->EventStartDate))
		{
			$row->EventStartDate = time();
			if($rseventsConfig['enable.12format'] == 1)
			{
				$row->EventStartDateH='11';
				$row->EventStartDateM='00';
			} else 
			{
				$row->EventStartDateH='20';
				$row->EventStartDateM='00';
			}
		} else 
		{
			if($rseventsConfig['enable.12format'] == 1)
				$row->EventStartDateH = date('g',$row->EventStartDate);
			else
				$row->EventStartDateH = date('H',$row->EventStartDate);
			$row->EventStartDateM = date('i',$row->EventStartDate);
		}
		
		if(empty($row->EventEndDate)) 
		{
			$row->EventEndDate = $row->EventStartDate;
			if($rseventsConfig['enable.12format'] == 1)
			{
				$row->EventEndDateH = '12';
				$row->EventEndDateM = '00';
			} else 
			{
				$row->EventEndDateH = '22';
				$row->EventEndDateM = '00';
			}
		} else 
		{
			if($rseventsConfig['enable.12format'] == 1)
				$row->EventEndDateH = date('g',$row->EventEndDate);
			else
				$row->EventEndDateH = date('H',$row->EventEndDate);
			$row->EventEndDateM = date('i',$row->EventEndDate);
		}

		return $row;
	}
	
	//initialize the event if the cid is 0
	
	function initEvent()
	{
		$idEvent=intval(JRequest::getVar('cid',0,'request'));
		$row = & JTable::getInstance('Rsevents_Events','Table');
		$row->load($idEvent);
		$row->IdEvent = 0;
		$row->DesignName = 'default';
		$row->LocationName = '';
		$row->LocationAddress = '';
		$row->FileName = '';
		$row->FileLocation = '';
		$row->EventOwner = '';
		
		return $row;
	}
	
	
	//loads all the designs installed
	
	function getDesigns()
	{
		$db = JFactory::getDBO();
		$db->setQuery("SELECT IdDesign , DesignName FROM #__rsevents_designs WHERE published = 1 ORDER BY DesignDefault DESC, DesignName ");
		$rows = $db->loadObjectList();
		return $rows;

	}
	
	//loads the files attached to an event
	
	function getFiles()
	{
		$db = JFactory::getDBO();
		$cid = JRequest::getVar('cid',0);
		$cid = intval($cid);
		$db->setQuery("SELECT IdFile, IdEvent, FileName , FileLocation, FilePermission FROM #__rsevents_files WHERE IdEvent='".$cid."'");
		$rows = $db->loadObjectList();
		return $rows;
	}
	
	//loads all the extras 
	
	function getExtras()
	{
		$db = JFactory::getDBO();
		$idEvent = JRequest::getVar('cid',0,'request');
		$idEvent = intval($idEvent);
		$db->setQuery("SELECT IdExtra,ExtraName , ExtraValue FROM #__rsevents_extras WHERE IdEvent='".$idEvent."'");
		$rows = $db->loadObjectList();
		return $rows;
	}	
	
	function getExtraPhotos()
	{
		$cid = JRequest::getVar('cid');
		$cid = intval($cid);
		$row= & JTable::getInstance('Rsevents_Extras','Table');
		$row->load($cid);
		return $row;
	}	
	
	
	//loads the extras for an event
	
	function getExtra()
	{
		$cid = JRequest::getVar('cid');
		$cid = intval($cid);
		$idEvent = JRequest::getVar('IdEvent',0);
		$row= & JTable::getInstance('Rsevents_Extras','Table');
		$row->load($cid);
		$row->IdEvent = $idEvent;
		return $row;
	}

	//return if the user is Super Administrator
	
	function getAdmin()
	{
		$my = & JFactory::getUser();
		if($my->usertype == 'Super Administrator')
		$ans = 1;
		else
		$ans = 0;
		return $ans;
	}
	
	//returns the info of the logged users
	
	function getInfo()
	{
		$my = & JFactory::getUser();
		$row = new stdClass();
		$row->Name = $my->name;
		$row->Email = $my->email;
		
		return $row;
	}
	
	//return if an user is alredy subscribed to the event
	
	function getSubscriber()
	{
		global $mainframe;
		$rseventsConfig = $mainframe->getUserState('rseventsConfig');
		$my = & JFactory::getUser();
		$db = & JFactory::getDBO();
		$cid = intval(JRequest::getVar('cid',0,'request'));
		if(($rseventsConfig['event.enable.guests'] == 1 && $my->id > 0) || $my->id > 0)
		{
		$db->setQuery("SELECT COUNT(IdSubscription) FROM #__rsevents_subscriptions WHERE IdEvent='".$cid."' AND IdUser='".$my->id."'");
		$row = $db->loadResult();
		if( $row == 0 ) return 0; else return 1;
		} else return 0;
	}
	
	//get parameters
	
	function getParams()
	{
		$menu =& JSite::getMenu();
		$item   = $menu->getActive();
		$params = new JParameter(null,null);
		if(isset($item->id))
			$params   =& $menu->getParams($item->id);
		return $params;
	}
	
	//get permissions for user groups
	
	function getPermissions()
	{
		$db = & JFactory::getDBO();
		$user =& JFactory::getUser();
		$gid = $user->gid;
		if($gid == 0) $gid = 29;
		$db->setQuery("SELECT gp.PermissionValue, gp.PermissionName FROM #__rsevents_groups g LEFT JOIN #__rsevents_groups_acl ga ON g.IdGroup = ga.IdGroup "
					."LEFT JOIN #__rsevents_group_permissions gp ON g.IdGroup = gp.IdGroup WHERE ga.GroupAcl = ".$gid);
		$permissionRows = $db->loadObjectList();
		$permissions = array();
		if(!empty($permissionRows))
		{
			foreach($permissionRows as $permissionObj)
			{
				$permissions[$permissionObj->PermissionName] = $permissionObj->PermissionValue;
			}
		}
		return $permissions;
	}
		
	//get permissions for cancelation
	
	function getCancelationPermission()
	{
		$db = & JFactory::getDBO();
		$user =& JFactory::getUser();
		$gid = $user->gid;
		$db->setQuery("SELECT gp.PermissionValue FROM #__rsevents_groups g LEFT JOIN #__rsevents_groups_acl ga ON g.IdGroup = ga.IdGroup "
					."LEFT JOIN #__rsevents_group_permissions gp ON g.IdGroup = gp.IdGroup WHERE ga.GroupAcl = '".$gid."' AND gp.PermissionName = 'allowRegistrationCancel'");
		$row = $db->loadResult();
		return $row;
	}
	
	
	//load the google map
	
	function getMap($num = '') 
{		
			global $mainframe;
			$rseventsConfig = $mainframe->getUserState('rseventsConfig');
			$model = $this->getModel('locations');
			$row= & JTable::getInstance('Rsevents_Locations','Table');
			$row->load($num);

if (!empty($row->LocationLat) && !empty($row->LocationLon)) 
{		
			if (empty($num)) { $num = ''; }
		
$map ='
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key='.$rseventsConfig['locations.gMaps.key'].'" type="text/javascript"></script>
<script src="http://www.google.com/uds/api?file=uds.js&v=1.0&key='.$rseventsConfig['locations.gMaps.key'].'" type="text/javascript"></script>
<script src="http://www.google.com/uds/solutions/localsearch/gmlocalsearch.js" type="text/javascript"></script>

<style type="text/css">
	@import url("http://www.google.com/uds/css/gsearch.css");
	@import url("http://www.google.com/uds/solutions/localsearch/gmlocalsearch.css");
</style>
<script type="text/javascript">

	function addListener(element, baseName, handler) {
		if (element.addEventListener)
			element.addEventListener(baseName, handler, false);
		else if (element.attachEvent)
			element.attachEvent("on"+baseName,handler);
	}
	
	
	function initialize'.$num.'() 
	{
	
		if (GBrowserIsCompatible()) 
		{
			var map'.$num.' = new GMap2(document.getElementById("google_map'.$num.'"),{mapTypes:['.$rseventsConfig['google.map'].']});
			var point = new GLatLng('.$row->LocationLat.','.$row->LocationLon.');
			map'.$num.'.setCenter(new GLatLng('.$row->LocationLat.','.$row->LocationLon.'),4);
			var mapControl = new GMapTypeControl();
			map'.$num.'.addControl(mapControl);
			map'.$num.'.addControl(new GLargeMapControl());
			map'.$num.'.addControl(new GOverviewMapControl());
			map'.$num.'.enableDoubleClickZoom();
			map'.$num.'.enableScrollWheelZoom();
			var bounds = new GLatLngBounds;
			
			var myIcon = new GIcon();
			myIcon.image = "http://www.google.com/mapfiles/marker.png";
			myIcon.iconAnchor = new GPoint((markerImage1.width/2),markerImage1.height);
			
			
			
			bounds.extend(point);
			setBounds(map'.$num.',bounds);				
			
			function createMarker(point) 
			{
				var marker = new GMarker(point);
				GEvent.addListener(marker,"click", function() {
				var myHtml = "<b>'.addslashes($row->LocationName).'</b><br/>'.addslashes($row->LocationAddress).' , '.addslashes($row->LocationCity).' - '.addslashes($row->LocationCountry).'";
				map'.$num.'.openInfoWindowHtml(point, myHtml);
				});
				return marker;
			}
			map'.$num.'.addOverlay(createMarker(point));
		}
	}
				
	function setBounds(map'.$num.',bounds) 
	{
		map'.$num.'.setZoom(15);
		map'.$num.'.setCenter(bounds.getCenter());
	}					

	function chargement() 
	{	
		markerImage1 = new Image(); 
		markerImage1.src = "http://www.google.com/mapfiles/marker.png";
		setTimeout("initialize'.$num.'()", 500); 
	}

	addListener(window, "load", chargement);
</script>
<span style="clear:both; display:block;"></span>
<div style="width: 100%;">
	<div id="google_map'.$num.'" style="width: 100%; height: 300px; overflow:hidden;"></div>
</div>';
} 	else $map = '';
			return $map;
}

    function email($email)
    {
        if($email == '') return true;
        if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email))
        {
            return false;
        }
        $email_array = explode("@", $email);
        $local_array = explode(".", $email_array[0]);
        for ($i = 0; $i < sizeof($local_array); $i++)
        {
            if (!ereg("^(([A-Za-z0-9!#$%&'*+/=?^_`{|}~-][A-Za-z0-9!#$%&'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$", $local_array[$i]))
            {
            return false;
            }
        }
        if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1]))
        {
            $domain_array = explode(".", $email_array[1]);
            if (sizeof($domain_array) < 2)
            {
            return false; // Not enough parts to domain
            }
            for ($i = 0; $i < sizeof($domain_array); $i++)
            {
                if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i]))
                {
                return false;
                }
            }
        }
        return true;
    }
	
	function getRegistered()
	{
		$db = &JFactory::getDBO();
		$cid = JRequest::getVar('cid',0,'request');
		$cid = intval($cid);
		$db->setQuery("SELECT u.username , u.id FROM #__rsevents_subscriptions s LEFT JOIN #__users u ON s.IdUser=u.id WHERE s.IdEvent='".$cid."' AND s.SubscriptionState = '1'");
		$rows = $db->loadObjectList();
		$i = 0;
		foreach($rows as $j => $row)		
			if(empty($row->id))  
			{
				unset($rows[$j]);
				$i++;
			}
			
		settype($details,'array');
		
		$details['data'] = $rows; 
		$details['guests'] = $i; 
		
		return $details;
		
	}
	
	function shorten($string,$max=255,$more=' ...')
	{
		$string_tmp = '';
		$exp = explode(' ',$string);
		for ($i=0; $i<count($exp); $i++)
		{
			if (strlen($string_tmp) + strlen($exp[$i]) < $max)
			$string_tmp .= $exp[$i].' ';
			else
			break;
		}
	return substr($string_tmp,0,-1).(strlen($string) > strlen($string_tmp) ? $more : '');
	}
	
	function getEventDays($start , $end=0,$order)
	{
		//get variables
		$db = &JFactory::getDBO();
		
		if($end == 0)
		$where = " AND ((e.EventStartDate <= '".$start."' AND e.EventEndDate >= '".$start."') OR (e.EventStartDate >= '".$start."' AND e.EventStartDate <= '".($start+86400)."')) ";
		else
		$where = " AND ((e.EventStartDate <= '".$start."' AND e.EventEndDate >= '".$start."') OR (e.EventStartDate >= '".$start."' AND e.EventStartDate <= '".($end)."')) ";
		
		$db->setQuery("SELECT e.IdEvent , e.EventName , e.EventSubtitle , e.EventDescription , e.EventStartDate , e.EventEndDate , e.EventHost , l.LocationName , c.CategoryName , l.LocationCity , e.EventIcon , l.IdLocation , c.IdCategory FROM #__rsevents_events e LEFT JOIN #__rsevents_locations l ON e.IdLocation=l.IdLocation LEFT JOIN #__rsevents_events_cat ec ON ec.IdEvent = e.IdEvent LEFT JOIN #__rsevents_categories c ON c.IdCategory = ec.IdCategory WHERE 1=1 AND e.published = 1 AND e.EventType = 1 ".$where." GROUP BY e.IdEvent ORDER BY e.EventStartDate $order ");
		
		return $db->loadObjectList();
	}
	
	function getEventCalendar($params)
	{
		$db = JFactory::getDBO();
		$post = JRequest::get('post');
		$user = JFactory::getUser();
		$catids = $params->get('catids','');
		$locids = $params->get('locids','');
		$userev = $params->get('userev','');
		$arhive = $params->get('arhive','0');
		$order  = $params->get('order','DESC');
		$where = '';
		
		if($arhive == 1)
			$where .= " AND e.published IN ('-1','1') ";
		elseif($arhive == 0) $where .= " AND e.published = 1 ";
		
		$categories = (count($catids) > 1) ? implode(',',$catids) : $catids;
		$locations = (count($locids) > 1) ? implode(',',$locids) : $locids;
		
		if ($userev && $user->id != 0) $where .= " AND e.IdUser = ".$user->id." ";
		
		if(isset($post['fromcalendar']) && $post['fromcalendar'] == 1 )
		{
			if ($post['idcat'] == 0) $where .= ''; else $where .= "  AND c.IdCategory = ".intval($post['idcat']);
		} else
		{
			if(!$userev)
			{
				if(!empty($catids) && !empty($locids)) $where .=" AND (c.IdCategory IN (".$categories.") OR l.IdLocation IN (".$locations.")) ";
				if(!empty($catids) && empty($locids)) $where .= " AND c.IdCategory IN (".$categories.") ";
				if(!empty($locids) && empty($catids)) $where .= " AND l.IdLocation IN (".$locations.") ";
			}
		}
		
		$ordering = " ORDER BY e.EventStartDate $order ";
		
		
		$db->setQuery("SELECT e.IdEvent , e.EventName , e.EventStartDate , e.EventEndDate , l.LocationName FROM #__rsevents_events e LEFT JOIN #__rsevents_locations l ON l.IdLocation = e.IdLocation LEFT JOIN #__rsevents_events_cat ec ON ec.IdEvent = e.IdEvent LEFT JOIN #__rsevents_categories c ON c.IdCategory = ec.IdCategory WHERE 1=1 ".$where.$ordering);
		
		return $db->loadObjectList();
	}
	
}