<script src="/js/require.js"></script>
<script>
require.config({
  paths: {
    "luxon": "/js/libs/rrule/luxon",
    "rrule": "/js/libs/rrule/rrule",
  },
});
var RRule;
require(['rrule'], function (rrule) {
  RRule = rrule;
});
function toText(data, type, full, opt) {
  var rrule_text = '';
  var dtstart, dtend, freq;
  var dtstart_obj;
  var dtend_obj;
  var rrule_re = RegExp('[^a-z]RRULE:','i');
  if (data && rrule_re.test(data)) {
    var r = RRule.rrulestr(data);
    if (r.isFullyConvertibleToText()) {
      rrule_text = r.toText();
    }
    freq = r.options.freq;
  }
  if (full.start){
    dtstart = full.start;
  }
  if (full.end){
    dtend = full.end;
  }
  var rrule_date_text = '';
  if (dtstart) {
    var rrule_dtend_text = '';
    if (dtend) {
        var dtend_obj = new Date(dtend);
        var dtend_date = fomatDate(dtend_obj.getFullYear(), dtend_obj.getMonth() + 1, dtend_obj.getDate(), '-');
        var dtend_time = fomatDate(dtend_obj.getHours(), dtend_obj.getMinutes(), dtend_obj.getSeconds(),':');
        rrule_dtend_text = ' [%c.loc("to")%] ' + (needDate(freq) ?  dtend_date + ' ': '') + dtend_time;
    }
    var dtstart_obj = new Date(dtstart);
    var dtstart_date = fomatDate(dtstart_obj.getFullYear(), dtstart_obj.getMonth() + 1, dtstart_obj.getDate(), '-');
    var dtstart_time = fomatDate(dtstart_obj.getHours(), dtstart_obj.getMinutes(), dtstart_obj.getSeconds(),':');

    var rrule_dtstart_text = ( rrule_dtend_text == '' ? ' [%c.loc("at")%] ' : ' [%c.loc("from")%] ') + (needDate(freq) ? dtstart_date + ' ' : '') + dtstart_time;

    rrule_date_text = rrule_dtstart_text + rrule_dtend_text;
  }
  rrule_text += rrule_date_text;
  return rrule_text;
}

function needDate(freq) {
    //3 - daily
    if (freq == 3 ) {
        return 0;
    }
    return 1;
}
function fomatDate (d1,d2,d3,delimiter) {
  var addZero = function(d){
    return d < 10 ? '0' + d : d;
  }
  return [addZero(d1),addZero(d2),addZero(d3)].join(delimiter);
}
</script>
<script>
function dynamicFields(){
  //remember about after error and edit form cases

  if ($('#repeat\\.freq').val() != 'no') {
    $('.ngcp-recurrent-control').show();
  } else {
    $('.ngcp-recurrent-control').hide();
  }
  //we need to hide again everything that we showed according to rrule on
  toggleRepeatStopControl();
  toggleLabeledFields();
}

function toggleEndControl (id) {
  var id_jquery = id;
  id_jquery = id_jquery.replace(/\./g,'\\.');
  var id_label_jquery = id_jquery + '\\.label';
  var id_control_jquery = id_jquery + '\\.label\\.control';
  var endSwitch = $('#' + id_jquery);
  var endSwitchLabel = $('#' + id_label_jquery);
  var endSwitchControl = $('#' + id_control_jquery);
  var endSwitchLabelText;
  var endSwitchControlText;
  if (endSwitch.val() == '0') {
    $('.ngcp-end-control').hide();
    endSwitchLabel.show();
    endSwitchLabelText = endSwitchLabel.data('toggle-off');
    endSwitchControlText = endSwitchControl.data('toggle-off');
  } else {
    $('.ngcp-end-control').show();
    endSwitchLabel.hide();
    endSwitchLabelText = endSwitchLabel.data('toggle-on');
    endSwitchControlText = endSwitchControl.data('toggle-on');
  }
  endSwitchLabel.html(endSwitchLabelText);
  endSwitchControl.html(endSwitchControlText);
}

function toggleEndField(){
  var endSwitch = $('#end\\.switch');
  var val = ((endSwitch.val() == '0') ? '1' : '0');
  endSwitch.val(val);
  toggleEndControl('end.switch');
}

function toggleRepeatStopControl () {
  var stop_control_on = $('#repeat_stop\\.switch').val();
  $("[class*='ngcp-repeatstop-']").hide();
  $('.ngcp-repeatstop-'+stop_control_on).show();
}

function frequencySuffix(){
  //remember about after error and edit form cases
  var intervalField = $('#repeat\\.interval');
  var suffix_regexp = /s$/;
  if (intervalField.val() > 1) {
    $("#repeat\\.freq option").each(function() {
      if (!suffix_regexp.test($(this).text())) {
        $(this).text($(this).text() + 's');
      }
    });
  } else {
    $("#repeat\\.freq option").each(function() {
      if (suffix_regexp.test($(this).text())) {
        $(this).text($(this).text().replace(suffix_regexp, ''));
      }
    });
  }
}

function toggleLabeledFields() {
  $(".ngcp-label-field-switch").each(function() {
    var field_name_jquery = $(this).data('field');
    field_name_jquery = field_name_jquery.replace(/\./g,'\\.');
    var hiddenSwitch = $('#' + 'label_switch\\.' + field_name_jquery );
    var showControl = false;
    var fieldSingleNameSelector = "[name='" + field_name_jquery + "']";
    var fieldMultiNameSelector = "[name^='" + field_name_jquery + '\\.' + "']";
    //byday, byday.weekdays
    $(fieldSingleNameSelector).add($(fieldMultiNameSelector)).each(function () {
      if( $(this).is(':checkbox') || $(this).is(':radio') ){
        if ( $(this).is(':checked')) {
          showControl = true;
        }
      } else if($(this).val() != '' ){
        showControl = true;
      }
    });
    var fieldLayer = $(this).closest( 'label' ).next( 'div.controls' );
    var fieldInvertControl = $( '#invert_field\\.' + field_name_jquery );
    var fieldClearControl = $( '#clear_field\\.' + field_name_jquery );
    var fieldAuxControls = fieldInvertControl.add(fieldClearControl);
    var fieldCheckboxes = $('input:checkbox' + fieldSingleNameSelector).add($('input:checkbox' + fieldMultiNameSelector));
    var fieldInputs = $('input' + fieldSingleNameSelector).add($('input' + fieldMultiNameSelector));
    var showFunc = function (button) {
      fieldLayer.show();
      if (fieldCheckboxes.length) {
        fieldInvertControl.show();
      } else {
        fieldInvertControl.hide();
      }
      fieldClearControl.show();
      hiddenSwitch.val(1);
      button.removeClass('btn-tertiary');
      button.addClass('btn-primary');
    };
    var hideFunc = function (button) {
      fieldLayer.hide();
      fieldAuxControls.hide();
      hiddenSwitch.val(0);
      button.removeClass('btn-primary');
      button.addClass('btn-tertiary');
    };
    if (showControl) {
    //by default controls are visible, but we use this point as initialization place even if they are visible
      showFunc($(this));
    } else if (!showControl && fieldLayer.is(":visible")) {
      hideFunc($(this));
    }
    $(this).off('click').click(function (event) {
      if (fieldLayer.is(":hidden")) {
        showFunc($(this));
      } else if (fieldLayer.is(":visible")) {
        hideFunc($(this));
      }
    });
    fieldInvertControl.off('click').click(function (event) {
      fieldInputs.prop('checked', function () { return (!this.checked); } );
    });
    fieldClearControl.off('click').click(function (event) {
      fieldInputs.prop('checked', false );
      fieldInputs.prop('value', '' );
    });
  });
}

$( document ).ready(function() {
    frequencySuffix();
    dynamicFields();
    toggleEndControl('end.switch');
});
</script>
<style>
.ngcp-60-checkboxes label.checkbox,.ngcp-32-checkboxes label.checkbox, .ngcp-7-checkboxes label.checkbox, .ngcp-6-checkboxes label.checkbox, .ngcp-inline-control, .ngcp-inline-control .control-label, .ngcp-inline-control .controls, .ngcp-inline-control input{
    display: inline-block;
    *display: inline;
}
.ngcp-60-checkboxes label.checkbox {
    width: 25px;
}
.ngcp-32-checkboxes label.checkbox {
    width: 20px;
}
.ngcp-7-checkboxes label.checkbox {
    width: 35px;
}
.ngcp-6-checkboxes label.checkbox {
    width: 70px;
}
.ngcp-inline-control .control-label, .ngcp-inline-control .controls{
    margin-left: 5px;
    padding-left: 5px;
    text-align: left;
}
.ngcp-inline-control .control-label{
    width: 30px;
}

</style>
[% site_config.title = c.loc('Time set "[_1]" - Events', timeset.name) -%]

[%
    helper.name = c.loc('Time Set Event');
    helper.identifier = 'event';
    helper.messages = messages;
    helper.dt_columns = event_dt_columns;
    helper.length_change = 1;

    helper.close_target = close_target;
    helper.create_flag = create_flag;
    helper.edit_flag = edit_flag;
    helper.form_object = form;
    helper.ajax_uri = c.uri_for_action( "/timeset/event_ajax", [c.req.captures.0] );
    helper.custom_renderers => {
      ical => 'function ( data, type, full, opt ) { return toText(data, type, full, opt); }'
    };

    UNLESS c.user.read_only;
        helper.dt_buttons = [
            { name = c.loc('Edit'), uri = "/timeset/'+full.time_set_id+'/event/'+full.id+'/edit", class = 'btn-small btn-primary', icon = 'icon-edit' },
            { name = c.loc('Delete'), uri = "/timeset/'+full.time_set_id+'/event/'+full.id+'/delete", class = 'btn-small btn-secondary', icon = 'icon-trash' },
        ];
        helper.top_buttons = [
            { name = c.loc('Time Sets'), uri = c.uri_for('/timeset/'), icon = 'icon-list' },
            { name = c.loc('Create Event'), uri = c.uri_for_action('/timeset/event_create', [c.req.captures.0] ), icon = 'icon-star' },
            { name = c.loc('Upload iCalendar events'), uri = c.uri_for_action('/timeset/event_upload',[c.req.captures.0]), icon = 'icon-star' },
            { name = c.loc('Download iCalendar'), uri = c.uri_for_action('/timeset/download', [c.req.captures.0]), icon = 'icon-th-list'},
        ];
    ELSE;
        helper.top_buttons = [
            { name = c.loc('Time Sets'), uri = c.uri_for('/timeset/'), icon = 'icon-list' },
        ];
    END;

    PROCESS 'helpers/datatables.tt';
-%]
[% # vim: set tabstop=4 syntax=html expandtab: -%]
