<?php

/**
 * View subject detail page or page with edit form.
 * 
 * @version		$Id$
 * @package		ARTIO Booking
 * @subpackage  views 
 * @copyright	Copyright (C) 2010 ARTIO s.r.o.. All rights reserved.
 * @author 		ARTIO s.r.o., http://www.artio.net
 * @license     GNU/GPL http://www.gnu.org/copyleft/gpl.html
 * @link        http://www.artio.net Official website
 */

defined('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.view');

//import needed models
AImporter::model('customer', 'occupancytypes', 'reservationtypes', 'reservations', 'reservationitems', 'prices', 'subject', 'subjects', 'supplements', 'template', 'reservation', 'google');
//import needed JoomLIB helpers
AImporter::helper('booking', 'config', 'document', 'image', 'parameter', 'string');
//import needed objects
AImporter::object('box', 'date', 'day', 'service');
if (IS_ADMIN) {
	BookingHelper::upgradeMootools125();
    //import needed Joomla! libraries
    jimport('joomla.html.pane');
    //import needed assets
    AImporter::js('validator', 'view-subject', 'view-images', 'view-files');
    AImporter::css('view-subject', 'template');
    //setup time picker component
    BookingHelper::importTimePicker();
    ADocument::setScriptJuri();
    ADocument::setCalendarHolder();
    AHtml::importIcons();
} elseif (IS_SITE) {
    //import needed Joomla! libraries
    jimport('joomla.application.pathway');
    //import needed assets
    AImporter::js('calendars', 'supplements', 'view-reservation-submitbutton', 'view-subject-period');
    AImporter::joomlaJS();
    ADocument::setScriptJuri();
}

class BookingViewSubject extends JViewLegacy
{

    /**
     * Global configuration
     * 
     * @var BookingConfig 
     */
    public $config;
    
    /**
     * Prepare to display page.
     * 
     * @param string $tpl name of used template
     */
    function display($tpl = null)
    {
        $mainframe = JFactory::getApplication();
        /* @var $mainframe JApplication */
        $document = JFactory::getDocument();
        /* @var $document JDocument */
        $config = AFactory::getConfig();
        /* @var $config BookingConfig */
        $user = JFactory::getUser();

        if (IS_SITE || $this->getLayout() == 'calendar') {
        	//defines constants
        	define('SESSION_PREFIX', 'booking_site_subject_' . ($id = JRequest::getInt('id')) . '_detail_');
        	define('SESSION_TESTER', 'booking_site_subject_tester');
        }
        
        $id = JRequest::getInt('id', ARequest::getCid());
        
        if (IS_SITE || $this->getLayout() == 'calendar') {
            if (JRequest::getString('pre_from') && JRequest::getString('pre_to')) { // pre-select interval from search result
                $from = JFactory::getDate(JRequest::getString('pre_from'));
                // pre-select first day of selected interval in the session 
                // month layout
                $mainframe->setUserState(('vsdmcy' . $id), $from->format('Y'));
                $mainframe->setUserState(('vsdmcm' . $id), $from->format('n'));
                // week layout
                $mainframe->setUserState(('vsdwcy' . $id), $from->format('Y'));
                $mainframe->setUserState(('vsdwcm' . $id), $from->format('W'));
                // day layout
                $mainframe->setUserState(('vsddcy' . $id), $from->format('Y'));
                $mainframe->setUserState(('vsddcm' . $id), $from->format('n'));
                $mainframe->setUserState(('vsddcd' . $id), $from->format('j'));                
                $to = JFactory::getDate(JRequest::getString('pre_to'));
                // pre-select last day of selected interval in the request 
                JRequest::setVar('year', $to->format('Y'));
                JRequest::setVar('month', $to->format('n'));
                JRequest::setVar('week', $to->format('W'));
                JRequest::setVar('day', $to->format('j'));
                JRequest::setVar('boxIds', array(1));
                JRequest::setVar('operation', CHECK_OP_NEXT);
            }
        }
        
        $modelSubject = new BookingModelSubject();
        $modelSupplements = new BookingModelSupplements();
        
        $modelSubject->setId($id);
        $subject = $modelSubject->getObject();
        /* @var $subject TableSubject */
        
        if (IS_SITE) {
        	$subject->merge();
            if ($subject->parent && $config->parentsBookable == 2) {	
                $mainframe->enqueueMessage(JText::_('SUBITEM_UNBOOKABLE_ALONE'), 'notice');
                return;
            }
        }
        
        if (is_null($subject))
            $mainframe->redirect('index.php', 'Object not found or is unpublished', 'error');
            
    	if (JRequest::getString('page') == 'googlemaps') {
    		$this->assignRef('subject', $subject);
    		echo $this->loadTemplate('googlemaps');	
        	return;
        }
        
        $templateHelper = AFactory::getTemplateHelper();
        $template = $templateHelper->getTemplateById($subject->template);

        /*
        $params = json_decode($template->loadObjectParams($subject->id));
        $params = (array)$params;
        $param = null;
        foreach($params as $k=>$v)
        {
        	$param[(int)$k] = (string)$v;
        }
        $params = $param;

        $f = null;
        if(is_object($template->parser) && $template->parser->fields)
        	$f = $template->parser->fields->fieldset->field;

        $i=0;
        if($f)
        {
	        foreach($f as $k=>$v)
	        {
	        	//TODO xml node - correct indexing
	        	$name = (string)$v['name'];
				$template->parser->fields->fieldset->field[$i] = $params[$name];
				$i++;
	        }
        }
        */
        //var_dump($template->parser->asXML());
        
        $properties = new AParameter($template->loadObjectParams($subject->id), null, $template->parser);
        if ($this->getLayout() == 'form') {
            $this->_displayForm($tpl, $templateHelper, $subject);
            return;
        }
        
        if (IS_SITE) {
            $modelSubjects = new BookingModelSubjects();
            $pathway = JPathway::getInstance('site');
            /* @var $pathway JPathwaySite */
            foreach (($parents = array_reverse($modelSubjects->loadSubjectParentsLine($subject->id))) as $parent)
                $pathway->addItem($parent->title, JRoute::_(ARoute::view(VIEW_SUBJECTS, $parent->id, $parent->alias)));
            $pathway->addItem($subject->title, JRoute::_(ARoute::view(VIEW_SUBJECT, $subject->id, $subject->alias)));
            
            BookingHelper::setSubjectHits($subject->id, $modelSubject);
            
            $this->assignRef('parents', $parents);
        }
        
        if (IS_SITE || $this->getLayout() == 'calendar') {
        	$lists = array('from' => JString::trim(JRequest::getString('from')) , 'to' => JString::trim(JRequest::getString('to')) , 'operation' => JRequest::getInt('operation', CHECK_OP_IN));
        	
        	$this->assignRef('parents', $parents);
        	$this->assignRef('lists', $lists);
        	
        }
        
        $modelTemplate = new BookingModelTemplate();
        
        $templateTable = $modelTemplate->_table;
        $templateTable->load($subject->template);
        $templateTable->display();
        
        $modelOccupancyTypes = new BookingModelOccupancyTypes($subject);
        $occupancyTypes = $modelOccupancyTypes->getData();
        
        $modelReservationTypes = new BookingModelReservationTypes();
        $modelReservationTypes->init(array('subject' => $subject->id));
        $reservationTypes = $modelReservationTypes->getData();
        
        if (IS_SITE || $this->getLayout() == 'calendar') {
            $lists['rids'] = ARequest::getUserStateFromRequest('rids', ($defaultRids = BookingHelper::getIdsFromObjectList($reservationTypes)), 'array');
			$emptyRid = array_search('0', $lists['rids']);
            if ($emptyRid !== false) unset($lists['rids'][$emptyRid]);
            if ($subject->display_only_one_rtype && count($lists['rids']) > 1)
                $lists['rids'] = array(reset($lists['rids']));
            AHtml::setMetaData($subject);
        }
        
        $modelSupplements->init(array('subject' => $subject->id));
        $supplements = $modelSupplements->getData();
        
        //getting logged customer
        $isAdmin = IS_ADMIN;
        $customer = null;
        if(IS_SITE){
	        $modelCustomer = new BookingModelCustomer();
	        $modelCustomer->setIdByUserId();
	        $customer = $modelCustomer->getObject();
			/* @var $customer TableCustomer */	        
	        $isAdmin = $modelCustomer->isAdmin();
        }
        
        $mode = JRequest::getString('mode');
        $changedReservationItemId = JRequest::getInt('changed_reservation_item_id');
        if ($mode == 'change' && $user->authorise('booking.reservation.edit.item', 'com_booking')) {
            $modelReservation = new BookingModelReservation();
            $changeableItems = $modelReservation->getChangeableItems($changedReservationItemId, true);
            $this->assignRef('changeableItems', $changeableItems);
        }
        
        if ($isAdmin) {
        	$this->calendarnummonths = JFactory::getApplication()->getUserStateFromRequest('com_booking.calendarnummonths', 'calendarnummonths', $config->calendarNumMonths, 'int');
        	$this->calendarnumweeks = JFactory::getApplication()->getUserStateFromRequest('com_booking.calendarnumweeks', 'calendarnumweeks', 1, 'int');
        }
        
        $this->assignRef('config', $config);
        $this->assignRef('subject', $subject);
        $this->assignRef('mode', $mode);
        $this->assignRef('changedReservationItemId', $changedReservationItemId);
        $tmpl = JRequest::getString('tmpl');
        $this->assignRef('tmpl', $tmpl);
        $this->assignRef('properties', $properties);
        $this->assignRef('occupancyTypes', $occupancyTypes);
        $this->assignRef('reservationTypes', $reservationTypes);
        $this->assignRef('supplements', $supplements);
        $this->assignRef('customer', $customer);
        $this->assignRef('supplements', $supplements);
        $this->assignRef('templateTable', $templateTable);
        $this->assignRef('template', $template);
        $this->assignRef('isAdmin', $isAdmin);
        
        //get cancel time for object
        /*
        $modelPrices = new BookingModelPrices();
        $modelPrices->init(array('subject' => $subject->id));
        $prices = $modelPrices->getData();
        //var_dump($prices);
        
        $this->assignRef('prices', $prices);
        */
        if($templateid = JRequest::getInt('templateid')) {
	        $db = JFactory::getDbo();
	        $query = 'SELECT `id` FROM `#__booking_subject` WHERE `template` ='.$templateid;
	        $db->setQuery($query);
	        $data = $db->loadObjectList();
	        //var_dump($data);
	        foreach($data as $object) {
	        	$modelSubject = new BookingModelSubject();
	        	$modelSubject->setId($object->id);
	        	$obj = $modelSubject->getObject();
	        	if(!$obj->id)
	        		continue;
	        	$this->day[$obj->id] = BookingHelper::getWeekCalendar($obj, $this->setting, $isAdmin ? $this->calendarnumweeks * 7 : 'week', $isAdmin);
	        	$this->day[$obj->id]->label = $obj->title;
	        }
        }
        
        JFactory::getApplication()->setUserState('com_booking.object.last', JURI::getInstance()->toString());
        
        parent::display($tpl);
    }

    /**
     * Prepare to display page.
     * 
     * @param string $tpl name of used template
     * @param ATemplateHelper $templateHelper
     * @param TableSubject $subject
     */
    function _displayForm($tpl, &$templateHelper, &$subject)
    {
        $db = JFactory::getDBO();
        /* @var $db JDatabaseMySQL */
        $templateHelper->importAssets();
        
        /* Prepare model objects */
        
        $modelOccupancyTypes = new BookingModelOccupancyTypes($subject);
        $modelPrices = new BookingModelPrices();
        $modelReservationTypes = new BookingModelReservationTypes();
        $modelSupplements = new BookingModelSupplements();
        
        $subject->id ? $subject->clean() : $subject->init();
        
        $task = JRequest::getCmd('task');
        
        /* Prepare objects template */
        
        if (($taskAdd = $task == 'add'))
            $subject->template = JRequest::getInt('template');
        
        $subject->newTemplate = $subject->template == 0;
        
        $template = $templateHelper->getTemplateById($subject->template);
        
        $templateTable = $modelPrices->getTable('template');
        /* @var $templateTable TableTemplate */
        $templateTable->load($subject->template);
        $templateTable->display();
        
        $params = $template->loadObjectParams($subject->id);

        $properties = new AParameter($params, null, $template->parser);
        

        /* Prepare page bookmarks */
        
        $tabsParams = array();
        
        if (! $taskAdd)
            $tabsParams['useCookie'] = true;
        
        /* Load objects occupancy types */
        
        $otypes = $modelOccupancyTypes->getData();

        /* Load objects reservation types */
        
        $modelReservationTypes->init(array('subject' => $subject->id));
        $rtypes = $modelReservationTypes->getData();
        
        $emptyRtype = $modelReservationTypes->getMainTable();
        /* @var $emptyRtype TableReservationType */
        $emptyRtype->init();
        
        array_unshift($rtypes, $emptyRtype);
        
        $rtcount = count($rtypes);
        for ($i = 0; $i < $rtcount; $i ++) {
            $rtype = &$rtypes[$i];
            /* @var $rtype TableReservationType */
            $rtype->fullTitle = JText::sprintf($rtype->type == RESERVATION_TYPE_HOURLY ? 'RESERVATION_TYPE_HOURLY_LABEL' : 'RESERVATION_TYPE_DAILY_LABEL', $rtype->title);
        }
        

        /* Load objects prices */
        
        $modelPrices->init(array('subject' => $subject->id));
        $prices = $modelPrices->getData();
        
        $emptyPrice = $modelPrices->getMainTable();
        /* @var $emptyPrice TablePrice */
        $emptyPrice->init();
        
        array_unshift($prices, $emptyPrice);
        

        /* Load objects supplements */
        
        $modelSupplements->init(array('subject' => $subject->id));
        $supplements = $modelSupplements->getData();
        
        $emptySupplement = $modelSupplements->getMainTable();
        /* @var $emptySupplement TableSupplement */
        $emptySupplement->init();
        
        array_unshift($supplements, $emptySupplement);
        

        JFilterOutput::objectHTMLSafe($subject, ENT_QUOTES, array('google_maps_code'));
        
        $params = JComponentHelper::getParams(OPTION);
        /* @var $params JParameter */
        
        AController::setEditorProperties($subject);
        
        $calendars = BookingHelper::loadCalendars();
        
        $config = AFactory::getConfig();
        $templateHelper->importIconsToJS(AImage::getIPath($config->templatesIcons), AImage::getRIPath($config->templatesIcons));
        
        $this->manager = $this->getLayout() == 'manager';
        
        $this->assignRef('config', $config);
        $this->assignRef('subject', $subject);
        $this->assignRef('properties', $properties);
        $this->assignRef('tabsParams', $tabsParams);
        $this->assignRef('otypes', $otypes);
        $this->assignRef('rtypes', $rtypes);
        $this->assignRef('prices', $prices);
        $this->assignRef('supplements', $supplements);
        $this->assignRef('templateHelper', $templateHelper);
        $this->assignRef('template', $template);
        $this->assignRef('templateTable', $templateTable);
        $this->assignRef('params', $params);
        $this->assignRef('calendars', $calendars);
        
        parent::display($tpl);
    }

    protected $volDisItem;
    protected $volDisPrefix;
    protected $volDisSuffix;
    protected $volDisId;

    public function loadTemplateVolumeDiscount($item, $prefix = '', $suffix = '', $id = '', $useVolumePer = true)
    {
        $this->volDisItem = $item;
        $this->volDisPrefix = $prefix;
        $this->volDisSuffix = $suffix;
        $this->volDisId = $id;
        $this->volDisPer = $useVolumePer;
        return $this->loadTemplate('volumediscount');
    }

    /**
     * Get children item list prepared for monthly layout.
     * 
     * @return array
     */
    public function getMonthlyItems() {
        $items = $this->get('children');
        $this->setting = new BookingCalendarSetting();
        $this->days = new stdClass();
        $map = $this->reservationTypes = $this->days->prices = array();
        $defaultYear = $defaultMonth = null;

        if ($this->config->defaultCalendarPageBookable) {
            $model = new BookingModelSubject();
            foreach ($items as $item) { // search a minimal bookable calendar page
                $date = JFactory::getDate($model->getNearestBooking($item->id));
                if ($date->format('Y') < $defaultYear || $defaultYear === null) {
                    $defaultYear = $date->format('Y'); // a minimal bookable year number
                }
                if ($date->format('m') < $defaultMonth || $defaultMonth === null) {
                    $defaultMonth = $date->format('m'); // a minimal bookable month number
                }
            }
        }

        foreach ($items as $item) {
            $item->days = BookingHelper::getMonthlyCalendar($item, $this->setting, 1, $this->isAdmin, ARequest::getUserStateFromRequest('rids', $item->rids, 'array'), $defaultMonth, $defaultYear);
            foreach ($item->days->prices as $rtype) { // compound reservation types by title
                if (!isset($this->days->prices[$rtype->title])) {
                    $this->days->prices[$rtype->title] = $rtype; // shown active rtypes compound by a title
                }
            }
            foreach ($item->days->rtypes as $rtype) { // compound reservation types by title
                if (isset($this->days->prices[$rtype->title])) {
                    // map shown rtype + rtypes asociated by title
                    $map[$this->days->prices[$rtype->title]->id][] = $rtype->id;
                }
                $this->reservationTypes[$rtype->id] = $rtype; // full rtype list
            }
        }
        
        $this->lists['rids'] = ARequest::getUserStateFromRequest('rids', array_keys($this->reservationTypes), 'array');

        ADocument::addDomreadyEvent("            
            Calendars.currentYear = '{$this->setting->currentYear}';
            Calendars.currentMonth = '{$this->setting->currentMonth}';
            Calendars.nextYear = '{$this->setting->nextYear}';
            Calendars.nextMonth = '{$this->setting->nextMonth}';
            Calendars.calendarType = 'monthly';
            Calendars.multiRids = " . json_encode($map) . ";
            Calendars.initMonthMulti();
        ");

        return $items;
    }

    /**
     * Check if show tabs with supplements or prices layout.
     * 
     * @param array $items
     * @return boolean
     */
    public function showMultiTabs(&$items) {
        $showTabs = false;
        foreach ($items as $item) {
            $item->showInTabs = false;
            if ($item->supplements) {
                $showTabs = $item->showInTabs = true;
            }
        }
        return $showTabs;
    }

    /**
     * Get a time selector.
     * 
     * @return array hour and time selector
     */
    public function getTimeSelector() {
        $options = array(JHtml::_('select.option', '', '- '.JText::_('CHECK_IN_HOUR').' -'));
        for ($i = 0; $i < 24; $i++) {
            $options[] = JHtml::_('select.option', $i, str_pad($i, 2, 0, STR_PAD_LEFT));
        }
        $selector[] = JHtml::_('select.genericlist', $options, 'check_in_hour', 'class="input-small" onchange="Calendars.showTotal()"', 'value', 'text', $this->subject->check_in_hour);
        
        $options = array(JHtml::_('select.option', '', '- '.JText::_('CHECK_IN_MINUTE').' -'));
        for ($i = 0; $i < 60; $i+=5) { 
            $options[] = JHtml::_('select.option', $i, str_pad($i, 2, 0, STR_PAD_LEFT));
        } 
        $selector[] = JHtml::_('select.genericlist', $options, 'check_in_time', 'class="input-small" onchange="Calendars.showTotal()"', 'value', 'text', $this->subject->check_in_time);
        
        return $selector;
    }

    public function getPeriodLists() {
        $config = AFactory::getConfig();
        $rTypes = $this->get('rtypes');
        $hourList = $typeList = $lists = $timeFrames = array();

        foreach ($rTypes as $rType) { // build options to select a single time frame
            foreach ($rType->prices as $price) {
                if ($rType->type == RESERVATION_TYPE_DAILY) {
                    if ($this->subject->night_booking_from !== '00:00:00' && $this->subject->night_booking_to !== '00:00:00') {
                        $title = JHTML::_('date', $this->subject->night_booking_from, ATIME_FORMAT) . ' - ' . JHTML::_('date', $this->subject->night_booking_to, ATIME_FORMAT);
                    } else { // time frame per whole day
                        $title = JText::sprintf('H', 24);
                    }
                } else { // time frame in specified time
                    $title = JHTML::_('date', $price->time_up, ATIME_FORMAT) . ' - ' . JHTML::_('date', $price->time_down, ATIME_FORMAT);
                }
                $title .= ' ' . $this->escape($rType->title);
                $timeFrames[] = $this->buildPeriodOption($rType, $price, $title);
            }
        }

        if ($timeFrames) {
            count($timeFrames) === 1 ?: array_unshift($timeFrames, array('value' => '', 'text' => JText::_('SELECT_TIMEFRAME'))); // single option has no -select- option
            $lists[] = JHtml::_('select.genericlist', $timeFrames, 'period_timeframe', array('option.attr' => 'attr', 'list.attr' => array('style' => ($config->multiTimeFrame ? 'display:none' : ''), 'autocomplete' => 'off', 'class' => 'input-medium')));
        }

        if ($config->multiTimeFrame) { // build options to select multi time frame
            foreach ($rTypes as $rType) {
                foreach ($rType->prices as $i => $price) {
                    $typeList[] = $this->buildPeriodOption($rType, $price, $rType->title, $rType->id . '.' . $price->id);
                    if ($rType->type == RESERVATION_TYPE_HOURLY) {
                        $unit = $this->subject->min_limit ? $this->subject->min_limit : $rType->time_unit;
                        $timeUp = JFactory::getDate($price->time_up);
                        $timeDown = JFactory::getDate($price->time_down == '00:00:00' ? '24:00:00' : $price->time_down);
                        $diff = $timeUp->diff($timeDown); // watch end of hours interval
                        while($timeUp <= $timeDown && ($diff->h * 60 + $diff->i) >= $unit) { // build drop-down to select hours
                            $hourList[$price->id][$timeUp->format('H:i:s')] = $timeUp->format(ATIME_FORMAT);
                            $diff = $timeUp->diff($timeDown); // watch end of hours interval
                            $timeUp->modify('+ ' . $unit . 'minutes'); // move to next hour
                        }
                    }
                }
            }

            count($typeList) === 1 ?: array_unshift($typeList, array('value' => '', 'text' => JText::_('SELECT_TIMEFRAME'))); // single option has no -select- option
            $lists[] = JHtml::_('select.genericlist', $typeList, 'period_type', array('list.attr' => array('autocomplete' => 'off', 'class' => 'input-medium'), 'option.attr' => 'attr'));

            foreach ($hourList as $id => $hours) {
                if (count($hours) > 1) {
                    $periodTimeDown = $periodTimeUp = $hours;

                    array_pop($periodTimeUp); // hide last hour
                    count($periodTimeUp) === 1 ?: array_unshift($periodTimeUp, '&ndash;&nbsp;' . JText::_('SELECT_CHECK_IN_TIME') . '&nbsp;&ndash;'); // single option has no -select- option
                    $lists[] = JHtml::_('select.genericlist', $periodTimeUp, 'period_time_up', array('autocomplete' => 'off', 'class' => 'input-large', 'style' => 'display:none'), 'value', 'text', null, 'period_time_up_multi' . $id);

                    array_shift($periodTimeDown); // hide first hour
                    count($periodTimeDown) === 1 ?: array_unshift($periodTimeDown, '&ndash;&nbsp;' . JText::_('SELECT_CHECK_OUT_TIME') . '&nbsp;&ndash;'); // single option has no -select- option
                    $lists[] = JHtml::_('select.genericlist', $periodTimeDown, 'period_time_down', array('autocomplete' => 'off', 'class' => 'input-large', 'style' => 'display:none'), 'value', 'text', null, 'period_time_down_multi' . $id);
                }
            }
        }

        return $lists;
    }

    /**
     * Build an select option of a period time frame with an informations about a reservation type and a price in data parameters for javascript.
     *
     * @param TableReservationType $rType
     * @param TablePrice $price
     * @param string $title
     * @param string $value
     * @return string HTML select option
     */
    protected function buildPeriodOption($rType, $price, $title, $value = null) {
        $params['data-price-id'] = $price->id;
        $params['data-rtype-id'] = $rType->id;
        $params['data-week-days'] = json_encode(array($price->monday, $price->tuesday, $price->wednesday,$price->thursday, $price->friday, $price->saturday, $price->sunday), JSON_NUMERIC_CHECK);
        if ($rType->type == RESERVATION_TYPE_DAILY) {
            $params['data-up'] = $this->subject->night_booking_from;
            $params['data-down'] = $this->subject->night_booking_to;
        } else {
            $params['data-up'] = $price->time_up;
            $params['data-down'] = $price->time_down;
            $params['data-fix'] = $rType->fix;
            if ($this->subject->min_limit > 0 && $rType->time_unit > $this->subject->min_limit) {
                $params['data-fix'] = ($rType->fix ? $rType->fix : 1) * $rType->time_unit / $this->subject->min_limit;
            }
            $params['data-fix-multiply'] = $rType->fix_multiply;
            $params['data-min'] = $rType->min;
            $params['data-max'] = $rType->max;
        }
        return array('text' => $title, 'value' => $value, 'attr' => $params);
    }

    public function getMonthSelector() {
        $options = array(JHtml::_('select.option', '', '- ' . JText::_('SELECT_MONTH') . ' -'));

        $options[] = JHtml::_('select.option', 1,  JText::_('JANUARY'));
        $options[] = JHtml::_('select.option', 2,  JText::_('FEBRUARY'));
        $options[] = JHtml::_('select.option', 3,  JText::_('MARCH'));
        $options[] = JHtml::_('select.option', 4,  JText::_('APRIL'));
        $options[] = JHtml::_('select.option', 5,  JText::_('MAY'));
        $options[] = JHtml::_('select.option', 6,  JText::_('JUNE'));
        $options[] = JHtml::_('select.option', 7,  JText::_('JULY'));
        $options[] = JHtml::_('select.option', 8,  JText::_('AUGUST'));
        $options[] = JHtml::_('select.option', 9,  JText::_('SEPTEMBER'));
        $options[] = JHtml::_('select.option', 10, JText::_('OCTOBER'));
        $options[] = JHtml::_('select.option', 11, JText::_('NOVEMBER'));
        $options[] = JHtml::_('select.option', 12, JText::_('DECEMBER'));

        return JHtml::_('select.genericlist', $options, 'period_month', 'class="input-medium"');
    }

    public function getWeekSelector() {
        $options = array(JHtml::_('select.option', '', '- ' . JText::_('SELECT_WEEK') . ' -'));

        $options[] = JHtml::_('select.option', 1, JText::_('J1ST_WEEK'));
        $options[] = JHtml::_('select.option', 2, JText::_('J2ND_WEEK'));
        $options[] = JHtml::_('select.option', 3, JText::_('J3RD_WEEK'));
        $options[] = JHtml::_('select.option', 4, JText::_('J4TH_WEEK'));

        return JHtml::_('select.genericlist', $options, 'period_week', 'class="input-medium"');
    }

    public function getDaySelector() {
        $options = array(JHtml::_('select.option', '', '- ' . JText::_('SELECT_DAY') . ' -'));

        $options[] = JHtml::_('select.option', 1, JText::_('MONDAY'));
        $options[] = JHtml::_('select.option', 2, JText::_('TUESDAY'));
        $options[] = JHtml::_('select.option', 3, JText::_('WEDNESDAY'));
        $options[] = JHtml::_('select.option', 4, JText::_('THURSDAY'));
        $options[] = JHtml::_('select.option', 5, JText::_('FRIDAY'));
        $options[] = JHtml::_('select.option', 6, JText::_('SATURDAY'));
        $options[] = JHtml::_('select.option', 7, JText::_('SUNDAY'));

        return JHtml::_('select.genericlist', $options, 'period_day', 'class="input-medium"');
    }

    /**
     * The method takes the default quick-jump buttons from the main toolbar.
     * The buttons are used to translate the subject.
     * The method copies and changes the buttons to translate a custom item.
     *
     * @param string $type content-element type
     * @param int $id content-element ID
     * @return string[] buttons HTML
     */
    public function getFalangQuickJump($type, $id) {
        $html = array();
        if ($id && is_file(JPATH_ADMINISTRATOR . "/components/com_falang/contentelements/{$type}.xml")) {
            foreach (JToolbar::getInstance()->getItems() as $btn) {
                if ($btn[0] === 'itrPopup') {
                    // change unique button ID
                    $btn[1] = $type . $id . $btn[10];
                    // change content-element type in the popup URL
                    $btn[3] = str_replace('booking_subject', $type, $btn[3]);
                    // change content-element ID in the popup URL
                    $btn[3] = str_replace("|{$this->subject->id}|", "|$id|", $btn[3]);
                    // hide (un)publish icon over the button
                    $btn[12] = '';
                    $html[] = JToolbar::getInstance()->renderButton($btn);
                }
            }
        }
        return $html;
    }
}

?>