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

	if(file_exists(JPATH_SITE.DS.'components'.DS.'com_rsform'.DS.'rsform.php'))
	{
	@session_start();
	require_once(JPATH_SITE.DS.'components'.DS.'com_rsform'.DS.'controller'.DS.'adapter.php');
	require_once(JPATH_SITE.DS.'components'.DS.'com_rsform'.DS.'controller'.DS.'functions.php');
	require_once(JPATH_SITE.DS.'components'.DS.'com_rsform'.DS.'controller'.DS.'validation.php');
	
	$RSadapter = new RSadapter();
	$GLOBALS['RSadapter'] = $RSadapter;

	//require backend language file
	require_once(JPATH_SITE.DS.'components'.DS.'com_rsform'.DS.'languages'.DS._RSFORM_FRONTEND_LANGUAGE.'.php');
	}

class rseventsViewEvents extends JView
{
	function display($tpl = null)
	{
		//initialize main variables
		global $mainframe;
		$document = & JFactory::getDocument();
		$db = & JFactory::getDBO();
		
		//adds the css style
		$document->addStyleSheet(JURI::root().'components/com_rsevents/style.css');
		
		//is the user admin?
		$isAdmin = $this->get('Admin');
		$this->assignRef('isAdmin',$isAdmin);
		
		//get page parameters
		$parameters = clone($mainframe->getParams('com_rsevents'));
		$this->assignRef('parameters', $parameters);
		
		//adds the main rsevents config
		$rseventsConfig = $mainframe->getUserState('rseventsConfig');
		$this->assignRef('rseventsConfig',$rseventsConfig);
		
		$Itemid = intval(JRequest::getVar('Itemid','','request'));
		$itemId = ($Itemid == '') ? '' : '&Itemid='.$Itemid;
		
		$this->assignRef('itemId',$itemId);
		$this->assignRef('Itemid',$Itemid);
		
		$direction = JRequest::getVar('direction');
		if(empty($direction)) $direction =  $parameters->get('order');
		
		$this->assignRef('direction',$direction);
		
		//switch on layout
		$layout = JRequest::getVar('layout','','request');
		switch($layout)
		{
			case 'archive':
			case 'listmyevents':
			case 'listdaysevents':
			case 'listcategoryevents':
			case 'listlocationevents':
			case 'featureevents':
			case 'search':
			default:
			{
				
				if ($layout == 'listcategoryevents')
				{
					$cid = intval(JRequest::getVar('cid','','request'));
					$db->setQuery("SELECT CategoryName FROM #__rsevents_categories WHERE IdCategory = ".$cid);
					$catName = $db->loadResult();
					$title = $document->getTitle();
					$document->setTitle($title.' - '.$catName);
					$this->assignRef('catName',$catName);
				}
			
				//get all the parameters
				
				$eventsList = $this->get('data');
				$total = $this->get('Total');
				$pagination = $this->get('Pagination');
				$cid = intval(JRequest::getVar('cid',0,'request'));
				
				// Get the page/component configuration
				$params = &$mainframe->getParams();
				
				$startDate = $params->get('startDate','01/01/1999');
				$endDate = $params->get('endDate','01/01/2037');
				$startTime = $params->get('startTime','00:00');
				$endTime = $params->get('endTime','00:00');
				
				$search_location = $params->get('searchloc','1');
				
				
				$archive_search = $params->get('search','0');

				$category_filter = JRequest::getVar('cat_filter','','request');
				$location_filter = JRequest::getVar('loc_filter','','request');
				$search_filter = JRequest::getVar('rse_search_archive','','request');
				
				//get categories for the category filter
				$db->setQuery("SELECT IdCategory as val, CategoryName  FROM #__rsevents_categories");

				$catlist[]         = JHTML::_('select.option',  '0', JText::_( 'RSE_EVENT_SELECT_CATEGORY' ), 'val', 'CategoryName' );
				$catlist         = array_merge( $catlist, $db->loadObjectList() );
				$lists['categories']      = JHTML::_('select.genericlist', $catlist, 'cat_filter', 'size="1"','val', 'CategoryName', $category_filter  );
				
				//get locations fot the location filter
				$db->setQuery("SELECT IdLocation as val, LocationName  FROM #__rsevents_locations");

				$loclist[]         = JHTML::_('select.option',  '0', JText::_( 'RSE_EVENT_SELECT_LOCATION' ), 'val', 'LocationName' );
				$loclist         = array_merge( $loclist, $db->loadObjectList() );
				$lists['locations']      = JHTML::_('select.genericlist', $loclist, 'loc_filter', 'size="1"','val', 'LocationName', $location_filter  );
				
				$this->assignRef('search_filter',$search_filter);
				$this->assignRef('archive_search',$archive_search);
				$this->assignRef('search_location',$search_location);
				$this->assignRef('lists',$lists);
				
				$pathway 	= & $mainframe->getPathWay();
				$pathway->addItem(JText::_('RSE_BC_'.strtoupper($layout)), '');
				
				//add alternate feed link
				if($params->get('show_feed_link', 1) == 1)
				{
					$link	= '&format=feed&limitstart=';
					$attribs = array('type' => 'application/rss+xml', 'title' => 'RSS 2.0');
					$document->addHeadLink(JRoute::_($link.'&type=rss'), 'alternate', 'rel', $attribs);
					$attribs = array('type' => 'application/atom+xml', 'title' => 'Atom 1.0');
					$document->addHeadLink(JRoute::_($link.'&type=atom'), 'alternate', 'rel', $attribs);
				}
				
				//replace the placeholders
				if(!empty($eventsList))
				{
					$layouts = array();
					foreach($eventsList as $i => $objList)
					{
						$layout = $rseventsConfig['layouts.eventintro'];
						
						// event link
						$eventLink = html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=show&cid='.$objList->IdEvent.':'.JFilterOutput::stringURLSafe($objList->EventName).$itemId));
						//location link
						$locationLink = html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=locations&layout=show&cid='.$objList->IdLocation.'&IdEvent='.$objList->IdEvent.$itemId));
						
						$categoryname = array();
						$db->setQuery("SELECT c.CategoryName , c.IdCategory FROM #__rsevents_categories c LEFT JOIN #__rsevents_events_cat ec ON ec.IdCategory = c.IdCategory WHERE ec.IdEvent =".$objList->IdEvent);
						$categs = $db->loadObjectList();
						
						foreach($categs as $categ)
							$categoryname[] = '<a href="'.html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=listcategoryevents&cid='.$categ->IdCategory.':'.JFilterOutput::stringURLSafe($categ->CategoryName).$itemId)).'">'.$categ->CategoryName.'</a>';
						
						$categoryname = implode(',',$categoryname);
						
						//get the icon of the event
						$small_icon = str_replace('.jpg','_'.$rseventsConfig['event.icon.small'].'.jpg',$objList->EventIcon);
						if($rseventsConfig['enable.event.icon'] && $objList->EventIcon != '')
							$eventIcon = '<div class="rsevents_icon"><a href="'.$eventLink.'"><img src="'.JURI::root().'components/com_rsevents/images/thumbs/'.$small_icon.'" /></a></div>';
						else 
							$eventIcon = '';
						
						$db->setQuery("SELECT EventEnableRegistration FROM #__rsevents_events WHERE IdEvent = ".$objList->IdEvent);
						$enableReg = $db->loadResult();
						
						if($enableReg == 1)
							$subscribeevent = '<a href="'.JRoute::_('index.php?option=com_rsevents&view=events&layout=subscribe&cid='.$objList->IdEvent.$itemId,false).'">'.JText::_('RSE_MENU_EVENT_SUBSCRIBE').'</a>';
						else 
							$subscribeevent = '';
	
						$bad  = array('{EventLink}','{CategoryName}','{LocationLink}','{EventIcon}','{EventSubscribe}');
						$good = array($eventLink,$categoryname,$locationLink,$eventIcon,$subscribeevent);
						
						$layout = str_replace($bad,$good,$layout);
						$properties = array();
						$values = array();
						$objList->EventStartDate = rseventsHelper::translateDate(date($rseventsConfig['global.dateformat'],$objList->EventStartDate));
						$objList->EventEndDate = rseventsHelper::translateDate(date($rseventsConfig['global.dateformat'],$objList->EventEndDate));
						$objList->EventDescription = rseventsHelper::strip_html_tags(rseventsModelEvents::shorten($objList->EventDescription));
						
						foreach($objList as $property => $value)
						{
							$properties[] = '{'.$property.'}';
							$values[] = $value;
						}
	
						$layouts[] = str_replace($properties, $values, $layout);
						
					}
				}
	
					$this->assignRef('pagination',$pagination);
					$this->assignRef('cid',$cid);
					$this->assignRef('layouts',$layouts);
					$this->assignRef('startDate',$startDate);
					$this->assignRef('endDate',$endDate);
					$this->assignRef('startTime',$startTime);
					$this->assignRef('endTime',$endTime);
			} break;
			
			case 'show':
			{
				rseventsHelper::showEvent();
			} break;
			
			case 'addeditevent':
			case 'duplicateevent':
			{
				//get all the variables
				global $mainframe;
				$document->addScript(JURI::root().'components/com_rsevents/rsevents.js'); 
				$db = JFactory::getDBO();
				$task= JRequest::getVar('task','','request');
				$cid=JRequest::getVar('cid',0,'request');
				$cid = intval($cid);
				$user =& JFactory::getUser();
				$event = $this->get('Event');
				
				if(empty($event->EventURL) && $event->IdEvent == 0)
					$event->EventURL = 'http://';
				
				$pathway 	= & $mainframe->getPathWay();
				if($task == 'duplicateevent')
				$pathway->addItem(JText::_('RSE_BC_DUPLICATE'), '');
				else
				$pathway->addItem(JText::_('RSE_BC_ADDEDIT'), '');
				
				
				$permissions = $this->get('Permissions');
				$locationPermission = @$permissions['allowLocations'];
				$eventPermission = @$permissions['enablePosts'];
				$canEdit = @$permissions['canEdit'];
				
				if($task == 'duplicateevent')
				{
				$event->IdEvent = 0;
				$event->EventName = JText::_('RSE_COPY_OF').' '.$event->EventName;
				$event->EventAlias = JText::_('RSE_COPY_OF').' '.$event->EventName;
				}
				$files=$this->get('Files');
				$extras = $this->get('Extras');
				$userid = $user->id;
				$page = intval(JRequest::getVar('page','','request'));
				
				//check not to enter to second page and edit it
				
				if ( $cid == 0 && $page == 2) $mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=addeditevent'.$itemId)));
			
				
				//IF ( I am the Administrator OR (Event Exists AND You have permission for editing) OR You are the OWNER )
				if ($isAdmin || (empty($event->IdEvent) && $eventPermission == 1 ) || (!empty($event->IdEvent) && $canEdit == 1) || ($userid === $event->IdUser)) 
				{ 
					// set default permission to the files
					
					$on = JURI::root().'administrator/components/com_rsevents/images/icons/tick.png';
					$off = JURI::root().'administrator/components/com_rsevents/images/icons/delete.png';
						if(!empty($files))
						{
							foreach($files as $i=>$file)
							{
								if(empty($file->FilePermission))
								$file->FilePermission = '111111';
								
								$files[$i]->fp0 = ($file->FilePermission[0]==0 ? '<img src="'.$off.'">' : '<img src="'.$on.'">');		
								$files[$i]->fp1 = ($file->FilePermission[1]==0 ? '<img src="'.$off.'">' : '<img src="'.$on.'">');		
								$files[$i]->fp2 = ($file->FilePermission[2]==0 ? '<img src="'.$off.'">' : '<img src="'.$on.'">');			
								$files[$i]->fp3 = ($file->FilePermission[3]==0 ? '<img src="'.$off.'">' : '<img src="'.$on.'">');			
								$files[$i]->fp4 = ($file->FilePermission[4]==0 ? '<img src="'.$off.'">' : '<img src="'.$on.'">');			
								$files[$i]->fp5 = ($file->FilePermission[5]==0 ? '<img src="'.$off.'">' : '<img src="'.$on.'">');					
							}
						}
					
					//prepare the category dropdown
					if($task == 'duplicateevent')
						$db->setQuery("SELECT IdCategory FROM #__rsevents_events_cat WHERE IdEvent = ".$cid);
					else
						$db->setQuery("SELECT IdCategory FROM #__rsevents_events_cat WHERE IdEvent = ".$event->IdEvent);
					$categ_selected = $db->loadResultArray();
					
					$sql = 'SELECT IdCategory,CategoryName FROM #__rsevents_categories WHERE published = 1 ORDER BY CategoryName ASC';
					$db->setQuery($sql);
					
					$categoryNumber = count($db->loadObjectList());
					$res =$db->loadObjectList();
					if($categoryNumber == 1) $idCat = $res[0]->IdCategory; else $idCat='';
					
					$catlist[]         = JHTML::_('select.option',  '0', JText::_( 'RSE_EVENT_SELECT_CATEGORY' ), 'IdCategory', 'CategoryName' );
					$catlist         = array_merge( $catlist, $db->loadObjectList() );
					$lists['categories']      = JHTML::_('select.genericlist', $catlist, 'IdCategory[]', 'class="inputbox" size="5" multiple="multiple"','IdCategory', 'CategoryName', empty($categ_selected) ? 0 : $categ_selected );
				
					//prepare the location dropdown
					
					$sql = 'SELECT IdLocation,LocationName FROM #__rsevents_locations WHERE published = 1 ORDER BY LocationName ASC';
					$db->setQuery($sql);
					$locationsList = $db->loadObjectList();
					
					$loclist[]         = JHTML::_('select.option',  '0', JText::_( 'RSE_EVENT_SELECT_LOCATION' ), 'IdLocation', 'LocationName' );
					$loclist         = array_merge( $loclist,$locationsList  );
					$lists1['locations']      = JHTML::_('select.genericlist', $loclist, 'IdLocation', 'class="inputbox" size="1"','IdLocation', 'LocationName', intval( $event->IdLocation ) );
				
					
					//prepare the users dropdown
					
					$sql= 'SELECT id , username FROM #__users';
					$db->setQuery($sql);
					
					$catlist3         = $db->loadObjectList(); 
					$lists3['username']      = JHTML::_('select.genericlist', $catlist3, 'IdUser', 'class="inputbox" size="5"','id', 'username', $event->IdUser );
					
					
					
					
					$this->assignRef('data',$event);
					$this->assignRef('extras',$extras);
					$this->assignRef('isAdmin',$isAdmin);
					$this->assignRef('files',$files);
					$this->assignRef('lists',$lists);
					$this->assignRef('lists1',$lists1);
					$this->assignRef('lists3',$lists3);
					$this->assignRef('numCat',$categoryNumber);
					$this->assignRef('idCat',$idCat);
					$this->assignRef('locationPermission',$locationPermission);
					$this->assignRef('eventPermission',$eventPermission);
					$this->assignRef('userid',$userid);
					$this->assignRef('locationsList',$locationsList);
				
				} else 
				{
					$msg = JText::_('RSE_ACCESS_DENIED');
					$link = html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events'.$itemId));
					$mainframe->redirect($link,$msg);
				}
				
			} break;
			
			case 'selectdesign':
			{
				//loading the designs
				$designs = $this->get('Designs');
				$this->assignRef('data',$designs);
				
			} break;
			
			case 'printevent':
			{
				
				$event = $this->get('Event');
				$this->assignRef('data',$event);
				
			} break;

			case 'guestssendmessage':
				
				//get variables
				global $mainframe;
				$user = &JFactory::getUser();
				$event = $this->get('Event');
				if ($user->usertype == 'Super Administrator' || $user->id == $event->IdUser)
				rseventsHelper::showEvent('guestsendmessage');
				else  $mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=show&cid='.$event->IdEvent.':'.JFilterOutput::stringURLSafe($event->EventName).$itemId)),JText::_('RSE_ACCESS_DENIED'));
				
				$pathway 	= & $mainframe->getPathWay();
				$pathway->addItem(JText::_('RSE_BC_SENDMESSAGE'), '');
				
			break;
			
			case 'invite':
				global $mainframe;

				rseventsHelper::showEvent('invite');
				
				$pathway 	= & $mainframe->getPathWay();
				$pathway->addItem(JText::_('RSE_BC_INVITE'), '');
				
				
				$importedContacts = JRequest::getVar('importedContacts',array(),'post');
				$this->assignRef('importedContacts',implode(',',$importedContacts));
			break;
			
			case 'photos':
			{
				global $mainframe;
				rseventsHelper::showEvent('subscribe');
				
				$user = &JFactory::getUser();
				$cid = JRequest::getVar('cid',0,'request');
				$cid = intval($cid);
				$event = $this->get('Event');
				if($rseventsConfig['events.extras.flickr'])
				$this->assignRef('data',$event);
				else
				$mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=show&cid='.$cid.$itemId)),JText::_('RSE_ACCESS_DENIED'));
				
			} break;
			
			case 'youtube':
			case 'flash':
			case 'mp3':
			case 'chat':
			case 'flickr':
			{
				global $mainframe;
				$user = &JFactory::getUser();
				$cid = JRequest::getVar('IdEvent',0,'request');
				$cid = intval($cid);
				$row = & JTable::getInstance('Rsevents_Events','Table');
				$row->load($cid);
				
				if($user->usertype == 'Super Administrator' || $user->id == $row->IdUser )
				{
					$data = $this->get('Extra');
					$this->assignRef('data',$data);
				} else $mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=show&cid='.$event->IdEvent.$itemId)),JText::_('RSE_ACCESS_DENIED'));
			
			} break;
			
			case 'subscribe':
			{
				rseventsHelper::showEvent('subscribe');
				
				$pathway 	= & $mainframe->getPathWay();
				$pathway->addItem(JText::_('RSE_BC_SUBSCRIBE'), '');
				
				//get variables
				$db = & JFactory::getDBO();
				$user = & JFactory::getUser();
				$userid = $user->id;
				$cid = JRequest::getVar('cid',0,'request');
				$cid = intval($cid);
				$post = JRequest::get('post'); 
				$privateUrl = JRequest::getVar('privateUrl','','request');
				
				
				//loading the event
				$event =  $this->get('Event');
				$this->assignRef('data',$event);
				
				//populate the First Name and the Last Name				
				$info = $this->get('Info');
				$name=explode(' ',$info->Name); 
				$fName=@$name[0];
				$lName ='';
				if (count($name) > 1)
				{
					unset($name[0]);
					$lName = implode(' ',$name);
				}
				$email = $info->Email;
				
				$this->assignRef('fName',$fName);	
				$this->assignRef('lName',$lName);	
				$this->assignRef('Email',$email);	
					
				//see if the user is allready registered at this event
				$isRegistered = $this->get('Subscriber');
				if($isRegistered && $rseventsConfig['event.multiple.reg']==0)
					$mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=show&cid='.$cid.$itemId)),JText::_('RSE_EVENT_ALLREADY_REGISTERED'));
				
				
				// IF the event allows registration AND ( Event is public OR (Event is private AND privateURL == EventPrivateUrl) )
				if($event->EventEnableRegistration && ( $event->EventType || (!$event->EventType && $privateUrl == $event->EventPrivateUrl)))
				{
					if($rseventsConfig['event.redirect.registration']==0 && $userid == 0)
					{ 
						if($rseventsConfig['event.enable.guests'] == 0)
						if ($rseventsConfig['cb.redirect'] == 1 && file_exists(JPATH_SITE.DS.'components'.DS.'com_comprofiler'.DS.'comprofiler.php'))
							$mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_comprofiler&task=registers')));
						else
							$mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_user&task=register')));
					}
					//else
					//{	
						$formids = array();					
						//Trigger Event - rse_f_onAfterLoadRegistrationForm
						$mainframe->triggerEvent('rse_f_onAfterLoadRegistrationForm',array(array('formids'=>&$formids,'event'=>&$event)));
						
						
						
						$sql= "SELECT IdTicket,  TicketName, TicketPrice, TicketMaxAudience, TicketDescription FROM #__rsevents_tickets WHERE IdEvent='".$cid."' ORDER BY ordering";
						$db->setQuery($sql);
						
						$tickets =  $db->loadObjectList();
						$ticket_list = array();
						$ticket_descriptions = '';
						if(!empty($tickets))
						foreach($tickets as $i => $objTicketDetails)
						{
							$db->setQuery("SELECT SUM(st.TicketsSubscribed) FROM #__rsevents_subscription_tickets st LEFT JOIN #__rsevents_subscriptions s ON s.IdSubscription=st.IdSubscription WHERE st.IdTicket='".$objTicketDetails->IdTicket."' AND s.SubscriptionState IN (1,0)");
							$result = $db->loadResult();
							
						switch($event->EventOverbooking)
						{
							case 0:
								if($tickets[$i]->TicketMaxAudience > $result || $tickets[$i]->TicketMaxAudience == 0)
								{
									$objTicketDetails->value = (($objTicketDetails->TicketPrice == '0') ? $objTicketDetails->TicketName . ' (' . JText::_('RSE_TICKETS_FREE').')' : $objTicketDetails->TicketName . ' (' . number_format($objTicketDetails->TicketPrice,$rseventsConfig['payment.nrdecimals'], $rseventsConfig['payment.decimal'], $rseventsConfig['payment.thousands']).' '.$rseventsConfig['payment.currency'].')');
									$ticket_list[] = $objTicketDetails;
									$ticketPrices[] = $objTicketDetails->TicketPrice;
									$ticket_descriptions .= '<div id="rsevents_ticket_'.$objTicketDetails->IdTicket.'" style="display:'.($i==0 ? 'inline':'none').';">'.$objTicketDetails->TicketDescription.'</div>';
								}
								if(empty($ticket_list) && $event->EventOverbooking == 0) $mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=show&cid='.$cid.$itemId)) , $rseventsConfig['event.full.booking']);
							break;
							
							case 1:
								$objTicketDetails->value = (($objTicketDetails->TicketPrice == '0') ? $objTicketDetails->TicketName . ' (' . JText::_('RSE_TICKETS_FREE').')' : $objTicketDetails->TicketName . ' (' . number_format($objTicketDetails->TicketPrice,$rseventsConfig['payment.nrdecimals'], $rseventsConfig['payment.decimal'], $rseventsConfig['payment.thousands']).' '.$rseventsConfig['payment.currency'].')');
								$ticket_list[] = $objTicketDetails;
								$ticketPrices[] = $objTicketDetails->TicketPrice;
								$ticket_descriptions .= '<div id="rsevents_ticket_'.$objTicketDetails->IdTicket.'" style="display:'.($i==0 ? 'inline':'none').';">'.$objTicketDetails->TicketDescription.'</div>';
							break;
						} 
						}
						else $mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=show&cid='.$cid.$itemId)) , JText::_('RSE_EVENT_NO_TICKETS'));
						
						$lists['tickets']      = JHTML::_('select.genericlist', $ticket_list, 'IdTicket', 'class="inputbox" size="1" onchange="rse_hidePayment(this.value,0);rse_change_ticket(this.value);"','IdTicket', 'value' ,'text' );
						if(empty($ticket_list) && $event->EventOverbooking == 0) $mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=show&cid='.$cid.$itemId)) , $rseventsConfig['event.full.booking']);
					
						$payment_items = array();
						
						if(defined('RSEVENTS_PAYPAL'))
						{
							$payment_items[] = JHTML::_('select.option', 'paypal', JText::_('RSE_PAYPAL_METHOD'));
						}
						if(defined('RSEVENTS_WIRE'))
						{
							$payment_items[] = JHTML::_('select.option', 'wire', JText::_('RSE_WIRE_METHOD'));
						}
						if(defined('RSEVENTS_2CO'))
						{
							$payment_items[] = JHTML::_('select.option', '2co', JText::_('RSE_2CO_METHOD'));
						}
						$lists['payments']      = JHTML::_('select.radiolist', $payment_items, 'payment', 'class="inputbox" size="1"', 'value' ,'text',$rseventsConfig['payment.default']);
						
						//if all the tickets have the price 0 we will not show the payment options
						foreach($ticketPrices as $i => $ticketPrice)
							if($ticketPrice == 0)
								unset($ticketPrices[$i]);
						$stop = ''; 
						if( empty($ticketPrices)) $stop = 1; else $stop = 0;
						
						
						$this->assignRef('lists',$lists);
						$this->assignRef('formids',$formids);
						$this->assignRef('stop',$stop);
						$this->assignRef('ticketList',$ticket_list);
						$this->assignRef('ticket_descriptions',$ticket_descriptions);
					
					//} 
				
				} else 
				{
					$mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents'.$itemId)), JText::_('RSE_ACCESS_DENIED'));
				}
			} break;
			
			case 'importyahoo':
			$document->addScript(JURI::root().'components/com_rsevents/rsevents.js'); 
			
			if(extension_loaded('curl'))
			{
				rseventsHelper::showEvent('importyahoo');
				rseventsHelper::importyahoo();
				
			} else $mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=invite&cid='.$cid.$itemId)));
			break;

			case 'importgmail':
				{
				$document->addScript(JURI::root().'components/com_rsevents/rsevents.js'); 
				
				if(extension_loaded('curl'))
				{
					rseventsHelper::showEvent('importgmail');
					rseventsHelper::importgmail();
				} else 	
					$mainframe->redirect(html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=invite&cid='.$cid.$itemId)));
					
				}	break;
				
				case 'album':
				{				
					//loading the extras
					global $mainframe;
					
					$extras = $this->get('ExtraPhotos');
					if($rseventsConfig['events.extras.flickr'] && !empty($extras->ExtraValue))
					$this->assignRef('data',$extras);
					else $mainframe->redirect(JRoute::_('index.php?option=com_rsevents'));
				
				}	break;
				
				case 'wire':
					
					$cid = JRequest::getVar('cid',0,'request');
					$plugin =& JPluginHelper::getPlugin( 'system', 'rseventswire' ); 	//Get a reference to this plugin
					$params = new JParameter( $plugin->params );
					$wire_details = $params->get('desc','');
					
					$this->assignRef('wireDetails',$wire_details);
					$this->assignRef('cid',$cid);
					
				break;
				
				
			
		}
		parent::display($tpl);
	}
	
	function getPhotos($idExtra, $extraValue)
	{
		//Get RSEvents Configs
		global $mainframe;
		$rseventsConfig = $mainframe->getUserState('rseventsConfig');
		
		if($rseventsConfig['events.extras.flickr'])
		{
			//Get rid of the trailing slash
			$extraValue = trim($extraValue);
			$data = explode('/',$extraValue);
			$latest = strlen($extraValue)-1;
			if($extraValue[$latest] == '/') $extraValue = substr($extraValue,0,$latest);
			
			//Get the photosetid
			$photosetid = end(explode('/',$extraValue));
	
			//Get the username
			$usernameid = $data[4];
			
			//Get the api key
			$api_key = $rseventsConfig['flikr.key'];
			
			//Get from rseventsConfig the number of photos
			$photos = $rseventsConfig['flikr.num.photos'];
			if($photos == 0 || $photos == '') $photos = '3';
			
			//Load photos TODO (get xml)
			$xml = new JSimpleXML();
			$file = "http://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&api_key=" . $api_key . "&photoset_id=" . $photosetid . "&per_page=" . $photos . "&page=1";
			
			//Try getting the xml
			$xml_string = rseventsHelper::fopen($file);
			
			if($xml_string)
			{
			
				$xml->loadString($xml_string);
				//if the user doesnt input the flickr api key
				
				if($rseventsConfig['flikr.key'] != '')
				{
				
					//Get the total number of photos
					$total = $xml->document->photoset[0]->attributes('total');
					
					//Load the result
					//$result = '<p>'.JText::_('RSE_EVENT_PHOTOS').'</p>';
					$result = '';
					for ($k = 0; $k < $photos; $k++) 
					{
						if (empty($xml->document->photoset[0]->photo[$k])) continue;
						$photo = $xml->document->photoset[0]->photo[$k];
						$id = $photo->attributes('id');
						if (!empty($id))
						{
							$result .= '<li><a href="http://www.flickr.com/photos/'.$usernameid.'/'.$photo->attributes('id').'" target="_blank">
									<img src="http://farm'.$photo->attributes('farm').'.static.flickr.com/'.$photo->attributes('server').'/'.$photo->attributes('id').'_'.$photo->attributes('secret').'_s.jpg">
								</a></li>';
						}
					}
					$result .= '<li><a href="'.html_entity_decode(JRoute::_('index.php?option=com_rsevents&view=events&layout=album&cid='.$idExtra)).'" target="_blank">'.JText::_('RSE_MORE').'</a></li>';
					$result .= '<span class="rsevents-clear"/>';

					return $result;
				}
			}
			else{
				return JText::_('RSE_EXTRA_FLICKR_FOPEN_ERROR');
			}
		}
		return '';		
	}
	

function rsform($formId)
{
	$output = '';
	$RSadapter = $GLOBALS['RSadapter'];

	if(isset($_SESSION['form'][$formId]['thankYouMessage']) && !empty($_SESSION['form'][$formId]['thankYouMessage']))
	{
		$output .= RSshowThankyouMessage($formId);
	}
	else
	{
		if(!empty($_POST))
		{
			$invalid = RSprocessForm($formId);
			if($invalid)
			{
				//the invalid variable is returned
				$output .= RSshowForm($formId, $_POST['form'], $invalid);
			}
		}
		else
		{
			
			if(isset($_SESSION['form'][$formId]['thankYouMessage']) && empty($_SESSION['form'][$formId]['thankYouMessage']))
			{
				unset($_SESSION['form'][$formId]['thankYouMessage']);

				//is there a return url?
				$query = mysql_query("SELECT ReturnUrl FROM `{$RSadapter->tbl_rsform_forms}` WHERE `formId` = '$formId'");
				$returnUrl = mysql_fetch_assoc($query);
				if(!empty($returnUrl['ReturnUrl']))
				{
					if(!isset($_SESSION['form'][$formId]['submissionId']))$_SESSION['form'][$formId]['submissionId'] = '';
					$returnUrl['ReturnUrl'] = RSprocessField($returnUrl['ReturnUrl'],$_SESSION['form'][$formId]['submissionId']);
					unset($_SESSION['form'][$formId]['submissionId']);

					$RSadapter->redirect($returnUrl['ReturnUrl']);
				}

				$output .= _RSFORM_FRONTEND_THANKYOU;
			}
			$output .= RSshowForm($formId);
		}
	}

	return $output;
}

function showSearch()
{
	global $mainframe;
	
	// Get the page/component configuration
	$params = &$mainframe->getParams();
	
	//search variables
	$show_search = $params->get('enablesearch',0);
	$show_categ = $params->get('showcateg',0);
	$show_loc = $params->get('showloc',0);
	$filter = JRequest::getVar('rse_filter','','request');
	
	$html = '';
	
	if ($show_search == 1) 
	{
		$html .='
			<div style="text-align:center;">
			<form method="post" action="">
			<input type="text" id="rse_filter" name="rse_filter" onclick="this.select();" value="'.$filter.'"/>'; 
	if ($show_categ == 1)
		$html .= $this->lists['categories'];
	if ($show_loc == 1) 
		$html .= $this->lists['locations'];
		
		$html .= '<button type="submit">'.JText::_('RSE_SEARCH').'</button>
				</form>
				</div><br/>';
	}
	
	return $html;
}

}