<?php

/**
 * Smarty plugin.
 */

/**
 * Smarty {insert_calendar} plugin.
 *
 * Type:     function<br>
 * Name:     url<br>
 * Purpose:  insert calendar to field
 *
 * @param array                    $params   parameters
 * @param Smarty_Internal_Template $template template object
 *
 * @return string
 */
function smarty_function_insert_calendar($params, $template)
{
    $selector = null;
    $format = 'date';
    $figureFormat = true;
    $czechformat = '';
    $used = false;

    extract($params);

    if (empty($selector)) {
        throw new InvalidArgumentException('insert_calendar: \'selector\' parameter empty');
    }

    echo openCalenderButton($selector, $format, $figureFormat, $czechformat, $used);
}

// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
function openCalenderButton($selector, $dateFormat, $figureFormat = true, $czechformat = null, $param_used = false)
{
    global $cfg;

    static $used = false;

    $used = $used || $param_used;

    /*$format = "dd-mm-yy";
    $timeFormat = "";

    if ($dateFormat == 'datetime')
       $timeFormat = "hh:mm:ss";
    */

    // if (!empty($czechformat)){
    $format = calendarDateFormat();
    $timeFormat = '';
    if ($dateFormat == 'datetime') {
        $timeFormat = calendarTimeFormat();
    }
    // }

    $ret = "<script>
      $(function(){
         openCalenderIFrame('{$selector}', '{$format}', '{$timeFormat}');
      });
   </script>";

    if (!$used) {
        $used = true;
        $ret .= '<script src="./static/js/jquery.datetimepicker.js"></script>';
        $ret .= '<script src="./static/js/jquery-ui.datepicker-cs.js"></script>';
    }

    return $ret;
}

function calendarDateFormat()
{
    $dbcfg = Settings::getDefault();

    switch ($dbcfg['date_format']) {
        case '%e.%c.%y':
            return 'd.m.y';
            break;
        case '%d.%m.%Y':
            return 'dd.mm.yy';
            break;
        case '%d/%m/%Y':
            return 'dd/mm/yy';
            break;
        case '%d/%m/%y':
            return 'dd/mm/y';
            break;
        case '%e.%c.%Y':
        default:
            return 'd.m.yy';
            break;
    }
}

function calendarTimeFormat()
{
    $dbcfg = Settings::getDefault();

    switch ($dbcfg['time_format']) {
        case '%k:%i:%s':
            return 'h:mm:ss';
            break;
        case '%H:%i':
            return 'hh:mm';
            break;
        case '%k:%i':
            return 'h:mm';
            break;
        case '%H:%i:%s':
        default:
            return 'hh:mm:ss';
            break;
    }
}
