/**
  * Filter the events after getting all (overbooked etc. - should all be moved sometime)
  *
  * @param   array   $rows        - The events
  * @param   int     $art         - The art
  * @param   int     $limitstart  - The limit start
  * @param   int     $limit       - The cur limit
  * @param   string  $leftjoin    - The leftjoin
  * @param   string  $search      - The search
  * @param   string  $order_by    - The orderby
  * @oaram   array   $where       - Orderby array
  * @param   string  $bookdate    - The bookdate
  *
  * @return mixed
  */
 public static function filterEvents($rows, $art, $limitstart, $limit, $leftjoin, $search, $order_by, $where, $bookdate)
 {
     $db = JFactory::getDbo();
     // Abzug der Kurse, die wegen Ausbuchung nicht angezeigt werden sollen
     $abzug = 0;
     $abid = array();
     if ($art == 0) {
         foreach ((array) $rows as $row) {
             if ($row->stopbooking == 2) {
                 $gebucht = MatukioHelperUtilsEvents::calculateBookedPlaces($row);
                 if ($row->maxpupil - $gebucht->booked < 1) {
                     $abzug++;
                     $abid[] = $row->id;
                 }
             }
         }
     }
     if (count($abid) > 0) {
         $abid = implode(',', $abid);
         $where[] = "r.id NOT IN ({$abid})";
     }
     $total = count($rows) - $abzug;
     if (!is_numeric($limitstart)) {
         $limitstart = explode("=", $limitstart);
         $limitstart = end($limitstart);
         if (!is_numeric($limitstart)) {
             $limitstart = 0;
         }
     }
     if ($total <= $limitstart) {
         $limitstart = $limitstart - $limit;
     }
     if ($limitstart < 0) {
         $limitstart = 0;
     }
     $ttlimit = "";
     if ($limit > 0) {
         $ttlimit = "\nLIMIT {$limitstart}, {$limit}";
     }
     $db->setQuery("SELECT a.*, r.*, a.id as eventid, cat.title as category, cat.params as catparams" . $bookdate . " FROM #__matukio_recurring AS r\n\t\t\tLEFT JOIN #__matukio AS a ON r.event_id = a.id\n\t\t    LEFT JOIN #__categories AS cat ON cat.id = a.catid" . $leftjoin . (count($where) ? "\nWHERE " . implode(' AND ', $where) : "") . $search . "\nORDER BY " . $order_by . $ttlimit);
     $rows = $db->loadObjectList();
     return $rows;
 }
			<tfoot>
			<tr>
				<td colspan="16"><?php 
echo $this->pagination->getListFooter();
?>
</td>
			</tr>
			</tfoot>
			<tbody>
			<?php 
foreach ($this->items as $i => $l) {
    $checked = JHTML::_('grid.id', $i, $l->id);
    $published = JHTML::_('grid.published', $l, $i);
    $link = JRoute::_('index.php?option=com_matukio&controller=eventlist&task=editEvent&id=' . $l->id);
    $curdate = MatukioHelperUtilsDate::getCurrentDate();
    $booked = MatukioHelperUtilsEvents::calculateBookedPlaces($l)->booked;
    $status_img = MatukioHelperUtilsBasic::getStatusImage($l);
    $available_img = MatukioHelperUtilsBasic::getAvailableImage($l, $booked);
    $bookable_image = MatukioHelperUtilsBasic::getBookableImage($l);
    $rating_image = MatukioHelperUtilsBasic::getRatingImage($l);
    // Triggers publish / unpublish
    $published_image = MatukioHelperUtilsBasic::getPublishedImage($l, $i);
    // Triggers canceld / active
    $cancel_image = MatukioHelperUtilsBasic::getCancelImage($l, $i);
    $title = strlen($l->title) < 70 ? $l->title : substr($l->title, 0, 67) . "...";
    $category = strlen($l->category) < 25 ? $l->title : substr($l->category, 0, 22) . "...";
    $begin = JHTML::_('date', $l->begin, MatukioHelperSettings::getSettings('date_format_without_time', 'd-m-Y')) . ", " . JHTML::_('date', $l->begin, MatukioHelperSettings::getSettings('time_format', 'H:i'));
    $end = JHTML::_('date', $l->end, MatukioHelperSettings::getSettings('date_format_without_time', 'd-m-Y')) . ", " . JHTML::_('date', $l->end, MatukioHelperSettings::getSettings('time_format', 'H:i'));
    $bplaces = '<a href="index.php?option=com_matukio&view=bookings&event_id=' . $l->id . '" value="' . $booked . '">' . $booked . "</a>";
    ?>
				<tr class="<?php 
 /**
  * Shows the form
  *
  * @param   string  $tpl  - The tmpl
  *
  * @return  bool|mixed|object
  */
 public function display($tpl = NULL)
 {
     $database = JFactory::getDBO();
     $my = JFactory::getuser();
     $dateid = JFactory::getApplication()->input->getInt('dateid', 1);
     $catid = JFactory::getApplication()->input->getInt('catid', 0);
     $search = JFactory::getApplication()->input->get('search', '', 'string');
     $limit = JFactory::getApplication()->input->getInt('limit', 5);
     $limitstart = JFactory::getApplication()->input->getInt('limitstart', 0);
     $cid = JFactory::getApplication()->input->getInt('cid', 0);
     $uid = JFactory::getApplication()->input->getInt('uid', 0);
     $todo = JFactory::getApplication()->input->get('todo', 'print_eventlist');
     // print_eventlist, print_booking, print_myevents, print
     $rows = null;
     $status = null;
     $headertext = null;
     $neudatum = MatukioHelperUtilsDate::getCurrentDate();
     if ($limitstart < 0) {
         $limitstart = 0;
     }
     $ttlimit = "";
     if ($limit > 0) {
         $ttlimit = "\nLIMIT {$limitstart}, {$limit}";
     }
     /**
      * 65O9805443904 =    public ?!
      * 653O875032490 =    Meine Angebote
      * 6530387504345 =  Meine Buchungen / Buchungsbestätigung ?!
      *
      * 3728763872762 =
      * csv
      */
     $where = array();
     $where[] = "a.pattern = ''";
     $where[] = "a.published = '1'";
     switch ($todo) {
         case "print_eventlist":
             $navioben = explode(" ", MatukioHelperSettings::getSettings('frontend_topnavshowmodules', 'SEM_NUMBER SEM_SEARCH SEM_CATEGORIES SEM_RESET'));
             break;
         case "print_booking":
             $navioben = explode(" ", MatukioHelperSettings::getSettings('frontend_topnavbookingmodules', 'SEM_NUMBER SEM_SEARCH SEM_CATEGORIES SEM_RESET'));
             break;
         case "print_myevents":
             $navioben = explode(" ", MatukioHelperSettings::getSettings('frontend_topnavoffermodules', 'SEM_NUMBER SEM_SEARCH SEM_CATEGORIES SEM_RESET'));
             break;
         case "print_teilnehmerliste":
             $navioben = "";
             break;
     }
     if ($todo != "print_teilnehmerliste" && $todo != "csvlist" && $todo != "certificate" && $todo != "invoice") {
         if (in_array('SEM_TYPES', $navioben)) {
             switch ($dateid) {
                 case "1":
                     $where[] = "a.end > '{$neudatum}'";
                     break;
                 case "2":
                     $where[] = "a.end <= '{$neudatum}'";
                     break;
             }
         }
     }
     switch ($todo) {
         default:
         case "print_eventlist":
             if (!in_array('SEM_TYPES', $navioben)) {
                 $where[] = "r.end > '{$neudatum}'";
             }
             if ((isset($_GET["catid"]) or in_array('SEM_CATEGORIES', $navioben)) and $catid > 0) {
                 $where[] = "a.catid ='{$catid}'";
             }
             $headertext = JTEXT::_('COM_MATUKIO_EVENTS');
             if ($cid) {
                 $where[] = "r.id= '{$cid}'";
                 $headertext = JTEXT::_('COM_MATUKIO_EVENT');
             }
             $database->setQuery("SELECT a.*, r.*, cc.title AS category FROM #__matukio_recurring AS r" . "\nLEFT JOIN #__matukio AS a ON r.event_id = a.id" . "\nLEFT JOIN #__categories AS cc ON cc.id = a.catid" . (count($where) ? "\nWHERE " . implode(' AND ', $where) : "") . "\nAND (r.semnum LIKE'%{$search}%' OR a.teacher LIKE '%{$search}%' OR a.title LIKE '%{$search}%'" . " OR a.shortdesc LIKE '%{$search}%' OR a.description LIKE '%{$search}%')");
             $rows = $database->loadObjectList();
             // Abzug der Kurse, die wegen Ausbuchung nicht angezeigt werden sollen
             if (!$cid) {
                 $abid = array();
                 foreach ($rows as $row) {
                     if ($row->stopbooking == 2) {
                         $gebucht = MatukioHelperUtilsEvents::calculateBookedPlaces($row);
                         if ($row->maxpupil - $gebucht->booked < 1) {
                             $abid[] = $row->id;
                         }
                     }
                 }
                 if (count($abid) > 0) {
                     $abid = implode(',', $abid);
                     $where[] = "r.id NOT IN ({$abid})";
                 }
             }
             $database->setQuery("SELECT a.*, r.*, cc.title AS category FROM #__matukio_recurring AS r" . "\nLEFT JOIN #__matukio AS a ON r.event_id = a.id" . "\nLEFT JOIN #__categories AS cc" . "\nON cc.id = a.catid" . (count($where) ? "\nWHERE " . implode(' AND ', $where) : "") . "\nAND (a.semnum LIKE'%{$search}%' OR a.teacher LIKE '%{$search}%' OR a.title LIKE '%{$search}%' OR a.shortdesc LIKE '%{$search}%' OR a.description LIKE '%{$search}%')" . "\nORDER BY r.begin" . $ttlimit);
             $rows = $database->loadObjectList();
             $status = array();
             $paid = array();
             $abid = array();
             for ($i = 0, $n = count($rows); $i < $n; $i++) {
                 $row =& $rows[$i];
                 $gebucht = MatukioHelperUtilsEvents::calculateBookedPlaces($row);
                 $gebucht = $gebucht->booked;
                 if (MatukioHelperUtilsDate::getCurrentDate() > $row->booked or $row->maxpupil - $gebucht < 1 and $row->stopbooking == 1 or $my->id == $row->publisher and MatukioHelperSettings::getSettings('booking_ownevents', 1) == 0) {
                     $status[$i] = JTEXT::_('COM_MATUKIO_UNBOOKABLE');
                 } elseif ($row->maxpupil - $gebucht < 1 && $row->stopbooking == 0) {
                     $status[$i] = JTEXT::_('COM_MATUKIO_BOOKING_ON_WAITLIST');
                 } elseif ($row->maxpupil - $gebucht < 1 && $row->stopbooking == 2) {
                     $abid[] = $row->id;
                 } else {
                     $status[$i] = JTEXT::_('COM_MATUKIO_NOT_EXCEEDED');
                 }
                 $database->setQuery("SELECT * FROM #__matukio_bookings WHERE semid='{$row->id}' AND userid='{$my->id}'");
                 $temp = $database->loadObjectList();
                 if (count($temp) > 0) {
                     $status[$i] = JTEXT::_('COM_MATUKIO_ALREADY_BOOKED');
                     if ($temp[0]->paid == 1) {
                         $rows[$i]->fees = $rows[$i]->fees . " - " . JTEXT::_('COM_MATUKIO_PAID');
                     }
                 }
                 $rows[$i]->codepic = "";
             }
             break;
             // My bookings ?!
         // My bookings ?!
         case "print_booking":
             $headertext = JTEXT::_('COM_MATUKIO_MY_BOOKINGS') . " - " . $my->name;
             if (in_array('SEM_CATEGORIES', $navioben) and $catid > 0) {
                 $where[] = "a.catid ='{$catid}'";
             }
             $where[] = "cc.userid = '" . $my->id . "'";
             if ($cid) {
                 $where[] = "cc.semid = '" . $cid . "'";
                 $headertext = JTEXT::_('COM_MATUKIO_BOOKING_CONFIRMATION') . " - " . $my->name;
             }
             $database->setQuery("SELECT a.*, r.*, cat.title AS category, cc.bookingdate AS bookingdate, cc.id AS bookid, cc.status AS bookingstatus\r\n\t\t\t\t\tFROM #__matukio_recurring AS r\r\n\t\t\t\t\tLEFT JOIN #__matukio AS a ON r.event_id = a.id\r\n\t\t\t\t\tLEFT JOIN #__matukio_bookings AS cc ON cc.semid = r.id\r\n\t\t\t\t\tLEFT JOIN #__categories AS cat ON cat.id = a.catid" . (count($where) ? "\nWHERE " . implode(' AND ', $where) : "") . "\nAND (r.semnum LIKE'%{$search}%' OR a.teacher LIKE '%{$search}%' OR a.title LIKE '%{$search}%' OR a.shortdesc LIKE '%{$search}%'\r\n                        OR a.description LIKE '%{$search}%')" . "\nORDER BY r.begin" . $ttlimit);
             $rows = $database->loadObjectList();
             $status = array();
             for ($i = 0, $n = count($rows); $i < $n; $i++) {
                 $row =& $rows[$i];
                 $database->setQuery("SELECT * FROM #__matukio_bookings WHERE semid = '{$row->id}' ORDER BY id");
                 $temps = $database->loadObjectList();
                 $status[$i] = MatukioHelperUtilsBooking::getBookingStatusName($row->bookingstatus);
                 $rows[$i]->codepic = $row->bookid;
                 if ($temps[0]->paid == 1) {
                     $rows[$i]->fees = $rows[$i]->fees . " - " . JTEXT::_('COM_MATUKIO_PAID');
                 }
             }
             break;
             // My events ?!
         // My events ?!
         case "print_myevents":
             if (in_array('SEM_CATEGORIES', $navioben) and $catid > 0) {
                 $where[] = "a.catid ='{$catid}'";
             }
             $where[] = "a.publisher = '" . $my->id . "'";
             $database->setQuery("SELECT a.*, r.* cat.title AS category FROM #__matukio_recurring AS r\r\n\t\t\t \t    LEFT JOIN #__matukio AS a ON r.eventid = a.id\r\n\t\t\t\t\tLEFT JOIN #__categories AS cat ON cat.id = a.catid" . (count($where) ? "\nWHERE " . implode(' AND ', $where) : "") . "\nAND (r.semnum LIKE'%{$search}%' OR a.teacher LIKE '%{$search}%' OR a.title LIKE '%{$search}%' OR a.shortdesc LIKE '%{$search}%' OR a.description LIKE '%{$search}%')" . "\nORDER BY r.begin" . $ttlimit);
             $rows = $database->loadObjectList();
             $status = array();
             $headertext = JTEXT::_('COM_MATUKIO_MY_OFFERS') . " - " . $my->name;
             for ($i = 0, $n = count($rows); $i < $n; $i++) {
                 $row =& $rows[$i];
                 $status[$i] = MatukioHelperUtilsBooking::getBookingStatusName($row->bookingstatus);
                 $rows[$i]->codepic = "";
             }
             break;
         case "print_teilnehmerliste":
             // TODO implement userchecking
             $art = JFactory::getApplication()->input->getInt('art', 0);
             $this->art = $art;
             if ($art == 1) {
                 $this->setLayout("signaturelist");
             } else {
                 $this->setLayout("participants");
             }
             break;
         case "csvlist":
             // TODO implement userchecking
             $art = JFactory::getApplication()->input->getInt('art', 0);
             $this->art = $art;
             $this->cid = $cid;
             $this->setLayout("csv");
             break;
         case "certificate":
             // TODO implement userchecking
             $art = JFactory::getApplication()->input->getInt('art', 0);
             $uid = JFactory::getApplication()->input->getInt('uid', 0);
             $this->art = $art;
             $this->uid = $uid;
             $this->setLayout("certificate");
             break;
         case "invoice":
             // TODO implement userchecking
             $art = JFactory::getApplication()->input->getInt('art', 0);
             $uid = JFactory::getApplication()->input->getInt('uid', 0);
             $this->art = $art;
             $this->uid = $uid;
             $this->setLayout("invoice");
             break;
     }
     $this->rows = $rows;
     $this->status = $status;
     $this->headertext = $headertext;
     parent::display($tpl);
 }
         }
         $htxt .= "<br />\n<span class=\"sem_cat\">" . JTEXT::_('COM_MATUKIO_DATE_OF_BOOKING') . ": " . JHTML::_('date', $buchopt[2][0]->bookingdate, MatukioHelperSettings::getSettings('date_format', 'd-m-Y, H:i')) . $cltimezone . "</span>";
     } else {
         $cltimezone = "";
         if (MatukioHelperSettings::getSettings('show_timezone', '1')) {
             $cltimezone = " (GMT " . JHTML::_('date', $row->booked, 'P') . ")";
         }
         if ($row->cancelled == 1) {
             $htxt .= "<br />\n<span class=\"sem_cat\">" . JTEXT::_('COM_MATUKIO_CLOSING_DATE') . ": <del>" . JHTML::_('date', $row->booked, MatukioHelperSettings::getSettings('date_format', 'd-m-Y, H:i')) . $cltimezone . "</del></span>";
         } else {
             $htxt .= "<br />\n<span class=\"sem_cat\">" . JTEXT::_('COM_MATUKIO_CLOSING_DATE') . ": " . JHTML::_('date', $row->booked, MatukioHelperSettings::getSettings('date_format', 'd-m-Y, H:i')) . $cltimezone . "</span>";
         }
     }
 }
 // Infozeile anzeigen
 $gebucht = MatukioHelperUtilsEvents::calculateBookedPlaces($row);
 if (MatukioHelperSettings::getSettings('event_showinfoline', 1) == 1) {
     $htxt .= "<br />\n<span class=\"sem_cat\">" . JTEXT::_('COM_MATUKIO_CATEGORY') . ": " . $row->category;
     if ($row->nrbooked > 0) {
         $htxt .= " - " . JTEXT::_('COM_MATUKIO_BOOKED_PLACES') . ": " . $gebucht->booked . " - " . JTEXT::_('COM_MATUKIO_BOOKABLE') . ": " . $buchopt[4] . " - " . JTEXT::_('COM_MATUKIO_HITS') . ": " . $row->hits;
         $htxt .= "</span>";
     }
 }
 $html .= MatukioHelperUtilsEvents::getTableCell($htxt, 'd', '', '98%', "sem_row");
 // Zertifikatdruck erlauben
 if (MatukioHelperSettings::getSettings('frontend_certificatesystem', 0) > 0 and $this->art == 1) {
     if ($buchopt[2][0]->certificated == 1 and $row->nrbooked > 0) {
         if (JFactory::getUser()->id > 0) {
             $htxt = MatukioHelperUtilsEvents::getPrintWindow(1, $row->sid, $buchopt[2][0]->id, '');
             $htbr = 30;
         }
 /**
  * Displays the templates view
  *
  * @param   string  $tpl  - Differen template
  *
  * @return  mixed|void
  */
 public function display($tpl = null)
 {
     $database = JFactory::getDBO();
     $startjahr = 2007;
     $stats = array();
     $mstats = array();
     $temp = array();
     $Monate = array(JTEXT::_('JANUARY'), JTEXT::_('FEBRUARY'), JTEXT::_('MARCH'), JTEXT::_('APRIL'), JTEXT::_('MAY'), JTEXT::_('JUNE'), JTEXT::_('JULY'), JTEXT::_('AUGUST'), JTEXT::_('SEPTEMBER'), JTEXT::_('OCTOBER'), JTEXT::_('NOVEMBER'), JTEXT::_('DECEMBER'));
     $stats[0] = new stdClass();
     $stats[0]->courses = 0;
     $stats[0]->bookings = 0;
     $stats[0]->certificated = 0;
     $stats[0]->hits = 0;
     $stats[0]->maxpupil = 0;
     $stats[0]->year = JTEXT::_('COM_MATUKIO_COMMON_PERIOD');
     for ($i = 0, $n = 12; $i < $n; $i++) {
         $month = $i + 1;
         $database->setQuery("SELECT a.*, r.* FROM #__matukio_recurring AS r\n\t\t\t\tLEFT JOIN #__matukio AS a ON r.event_id = a.id\n\t\t\t\tWHERE MONTH(r.begin)='{$month}' AND pattern = ''");
         $rows = $database->loadObjectList();
         $bookings = 0;
         $certificated = 0;
         $hits = 0;
         $maxpupil = 0;
         foreach ($rows as $row) {
             $gebucht = MatukioHelperUtilsEvents::calculateBookedPlaces($row);
             $bookings = $bookings + $gebucht->booked;
             $certificated = $certificated + $gebucht->certificated;
             $hits = $hits + $row->hits;
             $maxpupil = $maxpupil + $row->maxpupil;
         }
         $temp[$i] = new stdClass();
         $temp[$i]->courses = count($rows);
         $stats[0]->courses += $temp[$i]->courses;
         $temp[$i]->bookings = $bookings;
         $stats[0]->bookings += $temp[$i]->bookings;
         $temp[$i]->certificated = $certificated;
         $stats[0]->certificated += $temp[$i]->certificated;
         $temp[$i]->hits = $hits;
         $stats[0]->hits += $temp[$i]->hits;
         $temp[$i]->maxpupil = $maxpupil;
         $stats[0]->maxpupil += $temp[$i]->maxpupil;
         $temp[$i]->year = $Monate[$i];
     }
     $mstats[0] = $temp;
     $zaehler = 0;
     for ($i = 0, $n = 25; $i < $n; $i++) {
         $aktjahr = $startjahr + $i;
         $database->setQuery("SELECT COUNT(*) AS courses FROM #__matukio_recurring AS r\n\t\t\t\tLEFT JOIN #__matukio AS a ON r.event_id = a.id\n\t\t\t\tWHERE YEAR(r.begin)='{$aktjahr}' AND a.pattern = ''");
         $rows = $database->loadObjectList();
         if ($rows[0]->courses == 0) {
             continue;
         }
         $temp = array();
         $zaehler++;
         $stats[$zaehler] = new stdClass();
         $stats[$zaehler]->courses = 0;
         $stats[$zaehler]->bookings = 0;
         $stats[$zaehler]->certificated = 0;
         $stats[$zaehler]->hits = 0;
         $stats[$zaehler]->maxpupil = 0;
         $stats[$zaehler]->year = $aktjahr;
         for ($l = 0, $m = 12; $l < $m; $l++) {
             $month = $l + 1;
             $database->setQuery("SELECT a.*, r.* FROM #__matukio_recurring AS r\n\t\t\t\t\tLEFT JOIN #__matukio AS a ON r.event_id = a.id\n\t\t\t\t\tWHERE MONTH(r.begin)='{$month}' AND YEAR(r.begin)='{$aktjahr}' AND pattern = ''");
             $rows = $database->loadObjectList();
             $bookings = 0;
             $certificated = 0;
             $hits = 0;
             $maxpupil = 0;
             foreach ($rows as $row) {
                 $gebucht = MatukioHelperUtilsEvents::calculateBookedPlaces($row);
                 $bookings = $bookings + $gebucht->booked;
                 $certificated = $certificated + $gebucht->certificated;
                 $hits = $hits + $row->hits;
                 $maxpupil = $maxpupil + $row->maxpupil;
             }
             $temp[$l] = new stdClass();
             $temp[$l]->courses = count($rows);
             $stats[$zaehler]->courses += $temp[$l]->courses;
             $temp[$l]->bookings = $bookings;
             $stats[$zaehler]->bookings += $temp[$l]->bookings;
             $temp[$l]->certificated = $certificated;
             $stats[$zaehler]->certificated += $temp[$l]->certificated;
             $temp[$l]->hits = $hits;
             $stats[$zaehler]->hits += $temp[$l]->hits;
             $temp[$l]->maxpupil = $maxpupil;
             $stats[$zaehler]->maxpupil += $temp[$l]->maxpupil;
             $temp[$l]->year = $Monate[$l];
         }
         $mstats[$zaehler] = $temp;
     }
     $this->stats = $stats;
     $this->mstats = $mstats;
     $this->addToolbar();
     parent::display($tpl);
 }
 /**
  * OLD Booking method for old form
  *
  * @todo move into a nice function for both backend / Frontend / old and new form
  * @return mixed
  */
 public function bookevent()
 {
     $database = JFactory::getDBO();
     $my = JFactory::getUser();
     $id = JFactory::getApplication()->input->getInt('cid', 0);
     $uid = JFactory::getApplication()->input->getInt('uid', 0);
     $catid = JFactory::getApplication()->input->getInt('catid', 0);
     $nrbooked = JFactory::getApplication()->input->getInt('nrbooked', 0);
     $name = JFactory::getApplication()->input->get('name', '', 'string');
     $email = JFactory::getApplication()->input->get('email', '', 'string');
     $dispatcher = JDispatcher::getInstance();
     // Edit own booking
     $booking_id = JFactory::getApplication()->input->getInt('booking_id', 0);
     // AGBs
     $veragb = JFactory::getApplication()->input->get('veragb', 0, 'string');
     $isWaitlist = false;
     $reason = "";
     // Load event (use model function)
     $emodel = JModelLegacy::getInstance('Event', 'MatukioModel');
     $row = $emodel->getItem($id);
     $usrid = $my->id;
     $art = 2;
     if ($uid > 0) {
         $usrid = $uid;
         $art = 4;
     }
     $sqlid = $usrid;
     if ($name != "" and $email != "" or $usrid == 0) {
         $usrid = 0;
         $sqlid = -1;
     }
     // Pruefung ob Buchung erfolgreich durchfuehrbar
     $database->setQuery("SELECT * FROM #__matukio_bookings WHERE semid='{$id}' AND userid='{$sqlid}'");
     $temp = $database->loadObjectList();
     if (!empty($booking_id)) {
         $temp = null;
     }
     $gebucht = MatukioHelperUtilsEvents::calculateBookedPlaces($row);
     $gebucht = $gebucht->booked;
     $allesok = 1;
     $ueber1 = JTEXT::_('COM_MATUKIO_BOOKING_WAS_SUCCESSFULL');
     $pflichtfeld = false;
     $fields = MatukioHelperUtilsEvents::getAdditionalFieldsFrontend($row);
     for ($i = 0; $i < 20; $i++) {
         $test = $fields[0][$i];
         if (!empty($test)) {
             $res = explode("|", $test);
             if (trim($res[1]) == "1") {
                 $value = JFactory::getApplication()->input->get("zusatz" . ($i + 1), '', 'string');
                 if (empty($value)) {
                     $pflichtfeld = true;
                 }
             }
         }
     }
     if ($my->id > 0) {
         $name = $my->name;
         $email = $my->email;
     }
     // }
     if (empty($name) || empty($email)) {
         $allesok = 0;
         $ueber1 = JTEXT::_('COM_MATUKIO_BOOKING_WAS_NOT_SUCCESSFULL');
         $reason = JTEXT::_('COM_MATUKIO_NO_NAME_OR_EMAIL');
     } elseif ($pflichtfeld) {
         $allesok = 0;
         $ueber1 = JTEXT::_('COM_MATUKIO_BOOKING_WAS_NOT_SUCCESSFULL');
         $reason = JTEXT::_('COM_MATUKIO_REQUIRED_ADDITIONAL_FIELD_EMPTY');
     } elseif (count($temp) > 0) {
         $allesok = 0;
         $ueber1 = JTEXT::_('COM_MATUKIO_BOOKING_WAS_NOT_SUCCESSFULL');
         $reason = JTEXT::_('COM_MATUKIO_REGISTERED_FOR_THIS_EVENT');
     } elseif (MatukioHelperUtilsDate::getCurrentDate() > $row->booked) {
         $allesok = 0;
         $ueber1 = JTEXT::_('COM_MATUKIO_BOOKING_WAS_NOT_SUCCESSFULL');
         $reason = JTEXT::_('COM_MATUKIO_EXCEEDED');
     } elseif ($row->maxpupil - $gebucht - $nrbooked < 0 && $row->stopbooking == 1) {
         $allesok = 0;
         $ueber1 = JTEXT::_('COM_MATUKIO_BOOKING_WAS_NOT_SUCCESSFULL');
         $reason = JTEXT::_('COM_MATUKIO_MAX_PARTICIPANT_NUMBER_REACHED');
     } elseif ($row->maxpupil - $gebucht - $nrbooked < 0 && $row->stopbooking == 0) {
         $allesok = 2;
         $ueber1 = JTEXT::_('COM_MATUKIO_ADDED_WAITLIST');
         $reason = JTEXT::_('COM_MATUKIO_YOU_ARE_BOOKED_ON_THE_WAITING_LIST');
         $isWaitlist = true;
     } elseif (MatukioHelperSettings::getSettings('agb_text', '') != "" && $veragb != "1") {
         $allesok = 0;
         $ueber1 = JTEXT::_('COM_MATUKIO_BOOKING_WAS_NOT_SUCCESSFULL');
         $reason = JTEXT::_('COM_MATUKIO_AGB_NOT_ACCEPTED');
     }
     if ($art == 4) {
         $allesok = 1;
         $ueber1 = JTEXT::_('COM_MATUKIO_BOOKING_WAS_SUCCESSFULL');
     }
     $link = JRoute::_(MatukioHelperRoute::getEventRoute($row->id, $catid), false);
     $msg = "";
     $neu = "";
     // Alles in Ordnung
     if ($allesok > 0) {
         // Buchung eintragen
         $neu = JTable::getInstance('bookings', 'Table');
         if (!$neu->bind(JRequest::get('post'))) {
             return JError::raiseError(500, $database->stderr());
         }
         if (!empty($booking_id)) {
             $neu->id = $booking_id;
         }
         $neu->semid = $id;
         $neu->userid = $usrid;
         // Hmm really do that?
         $neu->name = $name;
         $neu->email = $email;
         $neu->bookingdate = MatukioHelperUtilsDate::getCurrentDate();
         $neu->name = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->name);
         $neu->email = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->email);
         $neu->zusatz1 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz1);
         $neu->zusatz2 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz2);
         $neu->zusatz3 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz3);
         $neu->zusatz4 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz4);
         $neu->zusatz5 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz5);
         $neu->zusatz6 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz6);
         $neu->zusatz7 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz7);
         $neu->zusatz8 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz8);
         $neu->zusatz9 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz9);
         $neu->zusatz10 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz10);
         $neu->zusatz11 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz11);
         $neu->zusatz12 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz12);
         $neu->zusatz13 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz13);
         $neu->zusatz14 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz14);
         $neu->zusatz15 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz15);
         $neu->zusatz16 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz16);
         $neu->zusatz17 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz17);
         $neu->zusatz18 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz18);
         $neu->zusatz19 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz19);
         $neu->zusatz20 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz20);
         // Set booking status to active @since 3.1
         $neu->status = MatukioHelperUtilsBooking::$ACTIVE;
         if (!empty($row->fees)) {
             $neu->payment_method = "cash";
             $payment_brutto = $row->fees * $neu->nrbooked;
             $coupon_code = $neu->coupon_code;
             if (!empty($coupon_code)) {
                 $cdate = new DateTime();
                 $db = JFactory::getDBO();
                 $query = $db->getQuery(true);
                 $query->select('*')->from('#__matukio_booking_coupons')->where('code = ' . $db->quote($coupon_code) . ' AND published = 1 AND published_up < ' . $db->quote($cdate->format('Y-m-d H:i:s')) . " AND published_down > " . $db->quote($cdate->format('Y-m-d H:i:s')));
                 $db->setQuery($query);
                 $coupon = $db->loadObject();
                 if (!empty($coupon)) {
                     if ($coupon->procent == 1) {
                         // Get a procent value
                         $payment_brutto = round($payment_brutto * ((100 - $coupon->value) / 100), 2);
                     } else {
                         $payment_brutto = $payment_brutto - $coupon->value;
                     }
                 } else {
                     // Perhaps delete this invalid field, or display an error?! TODO
                 }
             }
             $neu->payment_brutto = $payment_brutto;
         }
         $results = $dispatcher->trigger('onBeforeSaveBooking', $neu, $row);
         // Set status since @3.1
         if ($isWaitlist) {
             // We book to the waitlist, let's set the booking like that then
             $neu->status = MatukioHelperUtilsBooking::$WAITLIST;
         } elseif (empty($row->fees)) {
             // We set the status to active because no payment is done.. so no reason to not confirm them
             $neu->status = MatukioHelperUtilsBooking::$ACTIVE;
         } elseif (MatukioHelperSettings::_("booking_always_active", 0)) {
             // We check if the booking always active setting is set - if yes the booking is always!! active (except waitlist delete etc.)
             $neu->status = MatukioHelperUtilsBooking::$ACTIVE;
         } else {
             // We set the status to pending - this is going to be overwritten by the payment API (if paid etc.)
             $neu->status = MatukioHelperUtilsBooking::$PENDING;
         }
         if (!$neu->check()) {
             JError::raiseError(500, $database->stderr());
             exit;
         }
         if (!$neu->store()) {
             JError::raiseError(500, $database->stderr());
             exit;
         }
         $neu->checkin();
         $ueber1 = JText::_("COM_MATUKIO_BOOKING_WAS_SUCCESSFULL");
         if ($usrid == 0) {
             $usrid = $neu->id * -1;
         }
         if (MatukioHelperSettings::getSettings("oldbooking_redirect_after", "bookingpage") == "bookingpage") {
             $link = JRoute::_(MatukioHelperRoute::getEventRoute($row->id, $catid, 1, $neu->id), false);
         } elseif (MatukioHelperSettings::getSettings("oldbooking_redirect_after", "bookingpage") == "eventpage") {
             $link = JRoute::_(MatukioHelperRoute::getEventRoute($row->id, $catid, 0, $neu->id), false);
         } else {
             // Eventlist overview
             $link = JRoute::_("index.php?option=com_matukio&view=eventlist");
         }
         if ($art == 4) {
             MatukioHelperUtilsEvents::sendBookingConfirmationMail($row, $neu->id, 8);
         } else {
             MatukioHelperUtilsEvents::sendBookingConfirmationMail($row, $neu->id, 1);
         }
     } else {
         $link = JRoute::_(MatukioHelperRoute::getEventRoute($row->id, $catid), false);
     }
     $this->setRedirect($link, $ueber1 . " " . $reason);
 }
 /**
  * Gets the upcoming events
  *
  * @param   object  $events  - The events
  * @param   object  $user    - The user
  *
  * @return  string - The html code
  */
 public static function getUpcomingEventsHTML($events, $user)
 {
     JHTML::_('stylesheet', 'media/com_matukio/css/upcoming.css');
     $html = "";
     if (count($events)) {
         $dispatcher = JDispatcher::getInstance();
         JPluginHelper::importPlugin('content');
         $params = JComponentHelper::getParams('com_matukio');
         foreach ($events as $event) {
             $buchopt = MatukioHelperUtilsEvents::getEventBookableArray(0, $event, $user->id);
             // Link
             $eventid_l = $event->id . ':' . JFilterOutput::stringURLSafe($event->title);
             $catid_l = $event->catid . ':' . JFilterOutput::stringURLSafe(MatukioHelperCategories::getCategoryAlias($event->catid));
             $link = JRoute::_(MatukioHelperRoute::getEventRoute($eventid_l, $catid_l), false);
             // Event image   -- TODO Add / Check for category image
             $linksbild = MatukioHelperUtilsBasic::getComponentImagePath() . "2601.png";
             if ($event->image != "" and MatukioHelperSettings::getSettings('event_image', 1) == 1) {
                 $linksbild = MatukioHelperUtilsBasic::getEventImagePath(1) . $event->image;
             }
             $hot = $event->hot_event ? " " : "";
             $top = $event->top_event ? " mat_top_event" : "";
             // Starting Row
             $html .= '<div class="mat_single_event' . $hot . $top . '">';
             $html .= '	<div class="mat_event_header">';
             $html .= '		<div class="mat_event_header_inner">';
             $html .= '			<div class="mat_event_header_line">';
             $html .= '				<div class="mat_event_image">';
             $html .= '					<img src="' . $linksbild . '" alt="' . $event->title . '" align="absmiddle" />';
             $html .= '				</div>';
             $html .= '				<div class="mat_event_title">';
             $html .= '					<h2><a href="' . $link . '" title="' . $event->title . '">' . $event->title . '</a></h2>';
             $html .= '				</div>';
             $html .= '			</div>';
             $html .= '			<div class="mat_event_location">';
             $begin = JHTML::_('date', $event->begin, MatukioHelperSettings::getSettings('date_format', 'd-m-Y, H:i'));
             $location = $event->place;
             $locobj = null;
             if ($event->place_id > 0) {
                 $locobj = MatukioHelperUtilsEvents::getLocation($event->place_id);
                 $placelink = JRoute::_("index.php?option=com_matukio&view=location&id=" . $locobj->id . ":" . JFilterOutput::stringURLSafe($locobj->title));
                 $location = '<a href="' . $placelink . '">' . $locobj->location . '</a>';
             }
             if (MatukioHelperSettings::getSettings('show_timezone', '1')) {
                 $begin .= " (GMT " . JHTML::_('date', $event->booked, 'P') . ")";
             }
             if ($event->webinar == 1) {
                 $locimg = MatukioHelperUtilsBasic::getComponentImagePath() . "webinar.png";
                 $html .= '<h4><img src="' . $locimg . '" title="' . JText::_("COM_MATUKIO_WEBINAR") . '" style="width: 22px; vertical-align:middle" /> ' . $location . " " . JText::_("COM_MATUKIO_AT") . " " . $begin . '</h4>';
             } else {
                 // TODO add map link
                 $locimg = MatukioHelperUtilsBasic::getComponentImagePath() . "home.png";
                 $html .= '<h4><img src="' . $locimg . '" title="' . JText::_("COM_MATUKIO_FIELDS_CITY") . '" style="width: 22px; vertical-align:middle" /> ' . $location . " " . JText::_("COM_MATUKIO_AT") . " " . $begin . '</h4>';
             }
             $html .= '			</div>';
             $html .= '		</div>';
             $html .= '	</div>';
             $html .= '	<div class="mat_event_description">';
             $html .= $event->shortdesc;
             $html .= '</div>';
             $html .= '	<div class="mat_event_footer">';
             $html .= '		<div class="mat_event_footer_inner">';
             $html .= '			<div class="mat_event_infoline">';
             $catlink = JRoute::_("index.php?option=com_matukio&view=eventlist&art=0&catid=" . $event->catid . ":" . JFilterOutput::stringURLSafe($event->category));
             $html .= '<a href="' . $catlink . '">' . JTEXT::_($event->category) . '</a>';
             // Infoline
             $gebucht = MatukioHelperUtilsEvents::calculateBookedPlaces($event);
             if (MatukioHelperSettings::getSettings('event_showinfoline', 1) == 1) {
                 $html .= " | ";
                 // Veranstaltungsnummer anzeigen
                 if ($event->semnum != "") {
                     $html .= JTEXT::_('COM_MATUKIO_NUMBER') . ": " . $event->semnum . " | ";
                 }
                 $html .= JTEXT::_('COM_MATUKIO_BOOKABLE') . ": " . $buchopt[4];
             }
             // Seminarleiter anzeigen
             if ($event->teacher != "") {
                 $html .= " | " . $event->teacher;
             }
             // Fees
             if ($event->fees > 0) {
                 $html .= " | ";
                 $gebuehr = MatukioHelperUtilsEvents::getFormatedCurrency($event->fees);
                 $currency = MatukioHelperSettings::getSettings('currency_symbol', '$');
                 if ($currency == '€') {
                     $html .= JTEXT::_('COM_MATUKIO_FEES') . ': ' . $gebuehr . " " . $currency;
                 } else {
                     $html .= JTEXT::_('COM_MATUKIO_FEES') . ': ' . $currency . " " . $gebuehr;
                 }
             }
             $html .= '</div>';
             $html .= '			<div class="mat_event_footer_buttons" align="right">';
             // Detail Link
             $html .= " <a title=\"" . $event->title . "\" href=\"" . $link . "\">" . "<span class=\"mat_button\"><img src=\"" . MatukioHelperUtilsBasic::getComponentImagePath() . "0012.png\" border=\"0\" align=\"absmiddle\">&nbsp;" . JTEXT::_('COM_MATUKIO_EVENT_DETAILS') . "</span></a> ";
             // Booking Link
             if (($user->id != 0 || MatukioHelperSettings::getSettings('booking_unregistered', 1) == 1) && MatukioHelperSettings::getSettings('oldbookingform', 0) != 1) {
                 if ($event->nrbooked > 0) {
                     $bookinglink = JRoute::_("index.php?option=com_matukio&view=bookevent&cid=" . $event->id . ":" . JFilterOutput::stringURLSafe($event->title));
                     $html .= " <a title=\"" . JTEXT::_('COM_MATUKIO_BOOK') . "\" href=\"" . $bookinglink . "\"><span class=\"mat_button mat_book\" type=\"button\"><img src=\"" . MatukioHelperUtilsBasic::getComponentImagePath() . "1116.png\" border=\"0\" align=\"absmiddle\">&nbsp;" . JTEXT::_('COM_MATUKIO_BOOK') . "</span></a>";
                 }
             }
             $html .= '				<br />';
             $results = $dispatcher->trigger('onContentAfterButton', array('com_matukio.upcomingevent', &$event, &$params, 0));
             $html .= trim(implode("\n", $results));
             $html .= '			</div>';
             $html .= '		</div>';
             $html .= '	</div>';
             $html .= ' </div>';
         }
     }
     return $html;
 }
 /**
  * NEW Booking method for old and new form
  *
  * @throws  Exception - if db query fails
  * @return  mixed
  */
 public function book()
 {
     $payment_brutto = 0;
     $database = JFactory::getDBO();
     $post = JRequest::get('post');
     $my = JFactory::getUser();
     $input = JFactory::getApplication()->input;
     $event_id = $input->getInt('event_id', 0);
     $uid = $input->getInt('uid', 0);
     $steps = $input->getInt('steps', 3);
     $uuid = $input->get('uuid', 0, 'string');
     $id = $input->getInt('id', 0);
     $booking = null;
     if (!empty($id)) {
         // check if there is really such a booking
         $model = JModelLegacy::getInstance('Booking', 'MatukioModel');
         $booking = $model->getBooking($uuid);
         if (empty($booking)) {
             throw new Exception(JText::_("COM_MATUKIO_NO_BOOKING_FOUND"), 404);
         }
         if ($booking->id != $id) {
             throw new Exception(JText::_("COM_MATUKIO_NO_BOOKING_FOUND"), 404);
         }
     }
     $nrbooked = $input->getInt('nrbooked', 1);
     $catid = $input->getInt('catid', 0);
     $payment_method = $input->get('payment', '', 'string');
     $agb = $input->get('agb', '', 'string');
     $isWaitlist = false;
     $dispatcher = JDispatcher::getInstance();
     if (empty($event_id)) {
         throw new Exception(JText::_("COM_MATUKIO_NO_ID"), 404);
     }
     // Load event (use model function)
     $emodel = JModelLegacy::getInstance('Event', 'MatukioModel');
     $event = $emodel->getItem($event_id);
     $userid = $my->id;
     // Different fees @since 3.0
     $different_fees = $event->different_fees;
     $reason = "";
     $art = 2;
     $temp = null;
     $gebucht = MatukioHelperUtilsEvents::calculateBookedPlaces($event);
     $gebucht = $gebucht->booked;
     $allesok = 1;
     $ueber1 = JTEXT::_('COM_MATUKIO_BOOKING_WAS_SUCCESSFULL');
     $pflichtfeld = false;
     $fields = MatukioHelperUtilsEvents::getAdditionalFieldsFrontend($event);
     // Checking old required fields - backward compatibilty
     for ($i = 0; $i < 20; $i++) {
         $test = $fields[0][$i];
         if (!empty($test)) {
             $res = explode("|", $test);
             if (trim($res[1]) == "1") {
                 $value = $input->get("zusatz" . ($i + 1), '', 'string');
                 if (empty($value)) {
                     $pflichtfeld = true;
                 }
             }
         }
     }
     if (MatukioHelperSettings::getSettings("captcha", 0) == 1) {
         $ccval = $input->get("ccval", '', 'string');
         $captcha = $input->get("captcha", '', 'string');
         if (empty($captcha)) {
             $allesok = 0;
             $ueber1 = JTEXT::_('COM_MATUKIO_BOOKING_WAS_NOT_SUCCESSFULL');
             $reason = JTEXT::_('COM_MATUKIO_CAPTCHA_WRONG');
         } elseif (md5($captcha) != $ccval) {
             $allesok = 0;
             $ueber1 = JTEXT::_('COM_MATUKIO_BOOKING_WAS_NOT_SUCCESSFULL');
             $reason = JTEXT::_('COM_MATUKIO_CAPTCHA_WRONG');
         }
     }
     if (MatukioHelperSettings::getSettings("recaptcha", 0) == 1) {
         require_once JPATH_COMPONENT_ADMINISTRATOR . '/include/recaptcha/recaptchalib.php';
         $key = MatukioHelperSettings::getSettings("recaptcha_private_key", "");
         if (empty($key)) {
             throw new Exception("COM_MATUKIO_YOU_HAVE_TO_SET_A_RECAPTCHA_KEY", 500);
         }
         $resp = recaptcha_check_answer($key, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
         if (!$resp->is_valid) {
             // What happens when the CAPTCHA was entered incorrectly
             $allesok = 0;
             $ueber1 = JTEXT::_('COM_MATUKIO_BOOKING_WAS_NOT_SUCCESSFULL');
             $reason = JTEXT::_('COM_MATUKIO_CAPTCHA_WRONG') . $resp->error;
         }
     }
     $agbtext = MatukioHelperSettings::getSettings("agb_text", "");
     if ($pflichtfeld) {
         $allesok = 0;
         $ueber1 = JTEXT::_('COM_MATUKIO_BOOKING_WAS_NOT_SUCCESSFULL');
         $reason = JTEXT::_('COM_MATUKIO_REQUIRED_ADDITIONAL_FIELD_EMPTY');
     } elseif (count($temp) > 0) {
         $allesok = 0;
         $ueber1 = JTEXT::_('COM_MATUKIO_BOOKING_WAS_NOT_SUCCESSFULL');
         $reason = JTEXT::_('COM_MATUKIO_REGISTERED_FOR_THIS_EVENT');
     } elseif (MatukioHelperUtilsDate::getCurrentDate() > $event->booked) {
         echo "current: " . MatukioHelperUtilsDate::getCurrentDate();
         echo " booking: " . $event->booked;
         $allesok = 0;
         $ueber1 = JTEXT::_('COM_MATUKIO_BOOKING_WAS_NOT_SUCCESSFULL');
         $reason = JTEXT::_('COM_MATUKIO_EXCEEDED');
     } elseif ($event->maxpupil - $gebucht - $nrbooked < 0 && $event->stopbooking == 1) {
         $allesok = 0;
         $ueber1 = JTEXT::_('COM_MATUKIO_BOOKING_WAS_NOT_SUCCESSFULL');
         $reason = JTEXT::_('COM_MATUKIO_MAX_PARTICIPANT_NUMBER_REACHED');
     } elseif (!empty($agbtext)) {
         // Has to be on the end
         if (empty($agb)) {
             $allesok = 0;
             $ueber1 = JTEXT::_('COM_MATUKIO_BOOKING_WAS_NOT_SUCCESSFULL');
             $reason = JTEXT::_('COM_MATUKIO_AGB_NOT_ACCEPTED');
         }
     }
     if ($event->maxpupil - $gebucht - $nrbooked < 0 && $event->stopbooking == 0) {
         $allesok = 2;
         $ueber1 = JTEXT::_('COM_MATUKIO_ADDED_WAITLIST');
         $reason = JTEXT::_('COM_MATUKIO_YOU_ARE_BOOKED_ON_THE_WAITING_LIST');
         if (empty($booking)) {
             $isWaitlist = true;
         } else {
             // Prevent switching old booking to waitlist
             if ($booking->status == MatukioHelperUtilsBooking::$WAITLIST) {
                 $isWaitlist = true;
             } else {
                 $isWaitlist = false;
             }
         }
     }
     if ($art == 4) {
         $allesok = 1;
         $ueber1 = JTEXT::_('COM_MATUKIO_BOOKING_WAS_SUCCESSFULL');
     }
     $results = $dispatcher->trigger('onValidateBooking', $post, $event, $allesok);
     // Alles in Ordnung
     if ($allesok > 0) {
         // Buchung eintragen
         $neu = JTable::getInstance('bookings', 'Table');
         if (!$neu->bind($post)) {
             return JError::raiseError(500, $database->stderr());
         }
         $neu->semid = $event->id;
         $neu->userid = $userid;
         $firstname = $input->get('firstname', '', 'string');
         $lastname = $input->get('lastname', '', 'string');
         $neu->bookingdate = MatukioHelperUtilsDate::getCurrentDate();
         $neu->name = MatukioHelperUtilsBasic::cleanHTMLfromText($firstname . " " . $lastname);
         $neu->email = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->email);
         $neu->zusatz1 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz1);
         $neu->zusatz2 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz2);
         $neu->zusatz3 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz3);
         $neu->zusatz4 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz4);
         $neu->zusatz5 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz5);
         $neu->zusatz6 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz6);
         $neu->zusatz7 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz7);
         $neu->zusatz8 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz8);
         $neu->zusatz9 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz9);
         $neu->zusatz10 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz10);
         $neu->zusatz11 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz11);
         $neu->zusatz12 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz12);
         $neu->zusatz13 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz13);
         $neu->zusatz14 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz14);
         $neu->zusatz15 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz15);
         $neu->zusatz16 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz16);
         $neu->zusatz17 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz17);
         $neu->zusatz18 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz18);
         $neu->zusatz19 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz19);
         $neu->zusatz20 = MatukioHelperUtilsBasic::cleanHTMLfromText($neu->zusatz20);
         $fields = MatukioHelperUtilsBooking::getBookingFields();
         if (!empty($fields)) {
             $newfields = "";
             for ($i = 0; $i < count($fields); $i++) {
                 $field = $fields[$i];
                 $name = $field->field_name;
                 $newfields .= $field->id;
                 $newfields .= "::";
                 $newfields .= $input->get($name, '', 'string');
                 $newfields .= ";";
             }
             $neu->newfields = $newfields;
             if (!empty($event->fees) && $steps > 2) {
                 $neu->payment_method = $payment_method;
                 if ($different_fees == 0) {
                     $payment_brutto = $event->fees * $neu->nrbooked;
                     $coupon_code = $neu->coupon_code;
                     if (!empty($coupon_code)) {
                         $cdate = new DateTime();
                         $db = JFactory::getDBO();
                         $query = $db->getQuery(true);
                         $query->select('*')->from('#__matukio_booking_coupons')->where('code = ' . $db->quote($coupon_code) . ' AND published = 1 AND (published_up < ' . $db->quote($cdate->format('Y-m-d H:i:s')) . ' OR published_up = ' . $db->quote("0000-00-00 00:00:00") . ') ' . 'AND (published_down > ' . $db->quote($cdate->format('Y-m-d H:i:s')) . ' OR published_down = ' . $db->quote("0000-00-00 00:00:00") . ')');
                         $db->setQuery($query);
                         $coupon = $db->loadObject();
                         if (!empty($coupon)) {
                             if ($coupon->procent == 1) {
                                 // Get a procent value
                                 $payment_brutto = round($payment_brutto * ((100 - $coupon->value) / 100), 2);
                             } else {
                                 // Get a real value
                                 $payment_brutto = $payment_brutto - $coupon->value;
                             }
                             // Check how often the coupon is used and if used to often set published to 0 (since 3.0.0)
                             $coupon->hits++;
                             // Check if coupon has to be disabled now
                             if (!empty($coupon->max_hits) && $coupon->hits >= $coupon->max_hits) {
                                 $coupon->published = 0;
                             }
                             $coupontable = JTable::getInstance('coupons', 'Table');
                             if (!$coupontable->bind($coupon)) {
                                 throw new Exception(42, $database->stderr());
                             }
                             if (!$coupontable->check()) {
                                 throw new Exception(42, $database->stderr());
                             }
                             if (!$coupontable->store()) {
                                 throw new Exception(42, $database->stderr());
                             }
                             $coupontable->checkin();
                         } else {
                             // Perhaps delete this invalid field, or display an error?! Should be validated through js normally
                             throw new Exception(JText::_("COM_MATUKIO_INVALID_COUPON_CODE"), 42);
                         }
                     }
                     $neu->payment_brutto = $payment_brutto;
                 } else {
                     // Different fees
                     $payment_brutto = MatukioHelperFees::getPaymentTotal($event);
                     $neu->payment_brutto = $payment_brutto;
                     $difarray = array("places" => $input->get("places", array(), 'Array'), "types" => $input->get("ticket_fees", array(), 'Array'));
                     $neu->different_fees = json_encode($difarray);
                 }
             } elseif (!empty($event->fees)) {
                 if ($different_fees == 0) {
                     // We have disabled payment plugins but a fee
                     // Only calculate total amount
                     $payment_brutto = $event->fees * $neu->nrbooked;
                     $neu->payment_brutto = $payment_brutto;
                 } else {
                     // Different fees
                     $payment_brutto = MatukioHelperFees::getPaymentTotal($event);
                     $neu->payment_brutto = $payment_brutto;
                     $difarray = array("places" => $input->get("places", array(), 'Array'), "types" => $input->get("ticket_fees", array(), 'Array'));
                     $neu->different_fees = json_encode($difarray);
                 }
             }
         } else {
             // Only calculate total amount
             $payment_brutto = $event->fees * $neu->nrbooked;
             $neu->payment_brutto = $event->fees * $neu->nrbooked;
         }
         // Taxes
         if ($neu->payment_brutto > 0) {
             // Lets check if there are any
             if ($event->tax_id == 0) {
                 // No taxes
                 $neu->payment_netto = $neu->payment_brutto;
                 $neu->payment_tax = 0.0;
             } else {
                 $db = JFactory::getDbo();
                 $query = $db->getQuery(true);
                 $query->select("*")->from("#__matukio_taxes")->where("id = " . $db->quote($event->tax_id) . " AND published = 1");
                 $db->setQuery($query);
                 $tax = $db->loadObject();
                 if (empty($tax)) {
                     // Houston we have a problem
                     throw new Exception("Invalid tax value! Please select the correct tax in the event edit form.");
                 } else {
                     // Calculate netto
                     $minfac = 100 / (100 + $tax->value);
                     $neu->payment_netto = $neu->payment_brutto * $minfac;
                     $neu->payment_tax = $neu->payment_brutto - $neu->payment_netto;
                 }
             }
         }
         $results = $dispatcher->trigger('onBeforeSaveBooking', $neu, $event);
         // Set status since @3.1
         if (!empty($booking)) {
             // We don't update the status for old bookings
             $neu->status = $booking->status;
         } elseif ($isWaitlist) {
             // We book to the waitlist, let's set the booking like that then
             $neu->status = MatukioHelperUtilsBooking::$WAITLIST;
         } elseif (MatukioHelperSettings::_("booking_always_inactive", 0)) {
             // We set the status to pending
             $neu->status = MatukioHelperUtilsBooking::$PENDING;
         } elseif (empty($event->fees)) {
             // We set the status to active because no payment is done.. so no reason to not confirm them
             $neu->status = MatukioHelperUtilsBooking::$ACTIVE;
         } elseif ($steps == 2) {
             // We set the status to active because no payment can be done.. so no reason to not confirm them
             $neu->status = MatukioHelperUtilsBooking::$ACTIVE;
         } elseif ($payment_method == "cash") {
             // We check if the booking always active setting is set - if yes the booking is always!! active (except waitlist delete etc.)
             $neu->status = MatukioHelperUtilsBooking::$ACTIVE;
         } elseif (MatukioHelperSettings::_("booking_always_active", 0)) {
             // We check if the booking always active setting is set - if yes the booking is always!! active (except waitlist delete etc.)
             $neu->status = MatukioHelperUtilsBooking::$ACTIVE;
         } else {
             // We set the status to pending - this is going to be overwritten by the payment API (if paid etc.)
             $neu->status = MatukioHelperUtilsBooking::$PENDING;
         }
         if (!$neu->check()) {
             JError::raiseError(500, $database->stderr());
         }
         if (!$neu->store()) {
             JError::raiseError(500, $database->stderr());
         }
         $neu->checkin();
         $results = $dispatcher->trigger('onAfterBookingSave', $neu, $event);
         $ueber1 = JText::_("COM_MATUKIO_BOOKING_WAS_SUCCESSFULL");
         $booking_id = $neu->id;
     }
     if ($payment_brutto > 0 && $steps > 2) {
         // Link to the payment form
         $link = JRoute::_("index.php?option=com_matukio&view=paymentform&uuid=" . $uuid);
         $this->setRedirect($link, $reason);
     } else {
         if ($allesok > 0) {
             // We need to send the confirmation here.. we don't send it yet if the event has payment processing
             MatukioHelperUtilsEvents::sendBookingConfirmationMail($event, $neu->id, 1);
         }
         // Link to the bookingpage
         if (MatukioHelperSettings::getSettings("oldbooking_redirect_after", "bookingpage") == "bookingpage") {
             $link = JRoute::_("index.php?option=com_matukio&view=booking&uuid=" . $neu->uuid);
         } elseif (MatukioHelperSettings::getSettings("oldbooking_redirect_after", "bookingpage") == "eventpage") {
             $link = JRoute::_(MatukioHelperRoute::getEventRoute($event->id, $catid, 0, $booking_id), false);
         } else {
             // Eventlist overview
             $link = JRoute::_("index.php?option=com_matukio&view=eventlist");
         }
         $this->setRedirect($link, $ueber1 . " " . $reason);
     }
 }