<?php
// get user for datTimePicker pattern
$user = app()->user->sudoUserInstance;
if (!$user) {
    app()->user->logout();
    app()->user->loginRequired();
}

$source = app()->locale->aMName . '_' . app()->locale->pMName;
$search = array(
    app()->locale->aMName,
    app()->locale->pMName
);
$replace = array('am', 'pm');
$result = str_replace($search, $replace, $source);
$result = explode('_', $result);
?>

<script>
    $.fn.datetimepicker.dates['en'] = {
        days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"],
        meridiem: [
            <?php echo (json_encode($result[0])); ?>,
            <?php echo(json_encode($result[1])); ?>
        ],
        daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
        daysMin:<?php echo(json_encode(array_values(Yii::app()->locale->getWeekDayNames('abbreviated', true)))); ?>,
        months:<?php echo(json_encode(array_values(Yii::app()->locale->getMonthNames('wide', true)))); ?>,
        monthsShort: <?php echo(json_encode(array_values(Yii::app()->locale->getMonthNames('abbreviated', true)))); ?>,
        today: "<?php echo __("CALENDAR_TODAY"); ?>",
        suffix: ["st", "nd", "rd", "th"],
    };
</script>
<?php
$jsonUrl = url('calendarGeneral/default/getJsonEvents');
$tokenName = Yii::app()->request->csrfTokenName;
$token = Yii::app()->request->csrfToken;

$userModel = app()->user->realUserInstance->id;

$cs = cs();
$cs->registerScriptFile(bu() . '/js/fullcalendar/fullcalendar.min.js');
$cs->registerScriptFile(bu() . '/js/jquery-ui-1.8.23.custom.min.js');
?>

<style>
    a.calendarToggle{
        vertical-align: bottom;
    }
    .calendarToggle span{
        width: 15px;
        height: 15px;
        display: inline-block;
        vertical-align: middle;
        box-shadow: inset 0 9px 0 rgba(255,255,255,0.1);
        border: 1px solid #eee;
        margin-right: 3px;
    }
</style>

<?php
$calendarToggles = array();
$activeCalendarIds = array();
if (isset($_COOKIE['PhonalisaActiveCalendars'])) {
    $activeCalendarIds = explode(',', $_COOKIE['PhonalisaActiveCalendars']);
}

foreach ($eventSources as $index => $source) {
    $sourceToggle = array();

    $sourceToggle['label'] = '<span class="calendarToggleColorIndicator" style="background:'
        . CHtml::encode($source['color'])
        . '"></span>'
        . CHtml::encode($source['title']);
    $sourceToggle['active'] = in_array($source['id'], $activeCalendarIds) || count($eventSources) == 1;
    $sourceToggle['url'] = '';

    $sourceToggle['linkOptions'] = array(
        'class' => 'calendarToggle',
        'data-source-index' => $source['id'],
    );


    $calendarToggles[] = $sourceToggle;
}

$this->widget('ext.PlNavbar', array(
    'brand' => __('CALENDAR_NAVBAR_HEADER_TITLE'),
    'htmlOptions' => array(
        'data-translation-target' => 'CALENDAR_NAVBAR_TRANSLATION_TARGET',
    ),
    'collapse' => true, //requires bootstrap-responsive.css
    'items' => array(
        array(
            'class' => 'bootstrap.widgets.TbMenu',
            'items' => $calendarToggles,
            'encodeLabel' => false,
        ),
    ),
));

Yii::app()->clientScript->registerCoreScript('cookie');
?>




<script type='text/javascript'>

    var calendar;

    $(document).ajaxSuccess(function(event, XMLHttpRequest, ajaxOptions) {
        if (XMLHttpRequest.status == 201) {
            var eventObj = jQuery.parseJSON(XMLHttpRequest.responseText);
            calendar.fullCalendar('renderEvent', eventObj);
        }
        else if (XMLHttpRequest.status == 202) {
            var eventObj = jQuery.parseJSON(XMLHttpRequest.responseText);
            calendar.fullCalendar('removeEvents', eventObj.id);
            calendar.fullCalendar('renderEvent', eventObj);
        }
    }).ajaxError(function(event, XMLHttpRequest, ajaxOptions) {
        //alert(XMLHttpRequest.responseText);
    });

    $(document).ready(function() {



        var activeSourceIds = [];

        // delete button
        $("#calendarModal_deleteBtn").click(function(el) {

            if (!confirm('<?php echo __("CALENDAR_EVENT_DELETE_CONFIRM"); ?>')) {
                return;
            }

            // create delete url
            var deleteUrl = $('#calendar-form').attr("action").replace(/update/g, "delete");
            deleteUrl += '&ajax=calendar';

            $.ajax({
                url: deleteUrl,
                type: 'POST',
                data: {
                    YII_CSRF_TOKEN: "<?php echo $token ?>",
                },
            }).success(function(data) {
                calendar.fullCalendar('removeEvents', data);
                $('#calendarModal').modal("hide");
            });
        });

        var eventSources = <?php echo json_encode($eventSources); ?>;

        $(".calendarToggle").click(function(ev, el) {
            var isActive = $(this).parent().is('.active');
            var sourceIndex = $(this).data('source-index');


            if (isActive) {
                if (Object.keys(eventSources).length > 1) {
                    $(this).parent().removeClass('active');

                    calendar.fullCalendar('removeEventSource', eventSources[sourceIndex]);
                    activeSourceIds.splice(activeSourceIds.indexOf(sourceIndex), 1);
                }
            }
            else {
                $(this).parent().addClass('active');
                activeSourceIds.push(sourceIndex);
                calendar.fullCalendar('addEventSource', eventSources[sourceIndex]);
            }

            // store selected calendars in cookie
            $.cookie('PhonalisaActiveCalendars', activeSourceIds.toString());
        });



<?php
$selectedView = 'month';
if (Yii::app()->user->getState('selectedCalendarView')) {
    $selectedView =   Yii::app()->user->getState('selectedCalendarView');
}
$updateUrl = $this->createUrl('update');
$createUrl = $this->createUrl('create');
?>

        calendar = $('#calendar').fullCalendar({
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,agendaWeek,agendaDay'
            },
            timeFormat: {
                // for agendaWeek and agendaDay
                agenda: '<?php echo userPatternForTimeFormat('HH:mm{ - HH:mm}', 'hh:mm tt{ - hh:mm tt}'); ?>',
                // for all other views
                '': '<?php echo userPatternForTimeFormat('HH:mm', 'hh:mm tt'); ?>'
            },
            titleFormat: {
                month: 'MMMM yyyy', // September 2009
                week: "d. [MMM][ yyyy]{ '&#8212;' d. MMM yyyy}", // Sep 7 - 13 2009
                day: 'dddd, d. MMM yyyy'                  // Tuesday, Sep 8, 2009
            },
            axisFormat: '<?php echo userPatternForTimeFormat('HH:mm', 'hh:mm tt'); ?>',
            //axisFormat: 'h:mm tt',
            allDayText: '<?php echo __('CALENDAR_ALL_DAY'); ?>',
            buttonText: {
                prev: '&nbsp;&#9668;&nbsp;', // left triangle
                next: '&nbsp;&#9658;&nbsp;', // right triangle
                //prev: '<i class="icon-arrow-left"></i>',
                //next: '<i class="icon-arrow-right"></i>',
                prevYear: '&nbsp;&lt;&lt;&nbsp;', // <<
                nextYear: '&nbsp;&gt;&gt;&nbsp;', // >>
                today: '<?php echo __('CALENDAR_TODAY'); ?>',
                month: '<?php echo __('CALENDAR_MONTH_VIEW'); ?>',
                week: '<?php echo __('CALENDAR_WEEK_VIEW'); ?>',
                day: '<?php echo __('CALENDAR_DAY_VIEW'); ?>'
            },
            columnFormat: {
                month: 'ddd', // Mon
                week: 'dddd, d.', // Mon 9/7
                day: ''
            },
            monthNames: <?php echo(json_encode(array_values(Yii::app()->locale->getMonthNames('wide', true)))); ?>,
            monthNamesShort: <?php echo(json_encode(array_values(Yii::app()->locale->getMonthNames('wide', true)))); ?>,
            dayNames: <?php echo(json_encode(array_values(Yii::app()->locale->getWeekDayNames('wide', true)))); ?>,
            dayNamesShort: <?php
                echo(
                    json_encode(
                        array_values(
                            Yii::app()->locale->getWeekDayNames('abbreviated', true)
                        )
                    )
                );
            ?>,
            defaultView: !($.cookie('PhonalisaSelectedCalendarView')) ?
                            undefined :
                            $.cookie('PhonalisaSelectedCalendarView'),
            selectable: <?php echo $addNewEventEnabled ?>,
            selectHelper: true,
            eventClick: function(calEvent, jsEvent, view) {
                $.get("<?php echo $updateUrl; ?>", {id: calEvent.id}, function(data) {
                    $('#calendarModal .modal-header h4').html(calEvent.title);
                    $('#calendarModal_deleteBtn').show();

                    if (!isEditable(calEvent)) {
                        $('#calendarModal_deleteBtn').hide();
                        $('#calendar-grid_Modal_saveBtn').hide();
                    }
                    else {
                        $('#calendarModal_deleteBtn').show();
                        $('#calendar-grid_Modal_saveBtn').show();
                    }

                    $('#calendarModal .modal-body').html(data);
                    $('#calendarModal').modal('show');
                    if (isEditable(calEvent)) {
                        $('#CalendarEvent_start').attr('data-date', $('#CalendarEvent_start').val());
                        $('#CalendarEvent_end').attr('data-date', $('#CalendarEvent_end').val());
                        initDTP();
                    }

                });
            },
            eventRender: function(event, element) {
                $('.fc-event-title', element).html(event.title);
                // add locked icon to uneditable events
                if (!isEditable(event)) {
                    element.find(">:first-child").prepend('&nbsp;<i class="icon-lock"></i>');
                }

            },
            select: function(start, end, allDay) {
                addNewEvent(start, end, allDay);
                /*
                 var title = prompt('Event Title:');
                 if (title) {
                 calendar.fullCalendar('renderEvent',
                 {
                 title: title,
                 start: start,
                 end: end,
                 allDay: allDay
                 },
                 true // make the event "stick"
                 );
                 }
                 calendar.fullCalendar('unselect');
                 */
            },
            //events: "<?php echo $jsonUrl; ?>",
            firstDay: 1,
            eventDrop: function(event, dayDelta, minuteDelta, allDay, revertFunc, jsEvent, ui, view) {
                var eventCopy = jQuery.extend(true, {}, event);
                eventCopy.start = convertDateTime(event.start);
                eventCopy.end = convertDateTime(event.end);

                $.ajax({
                    url: "<?php echo url('calendarGeneral/default/update') ?>&id=" + event.id,
                    type: 'POST',
                    //async:   false,
                    data: {
                        CalendarEvent: eventCopy,
                        jsonDelta: dayDelta,
                        YII_CSRF_TOKEN: "<?php echo $token ?>"
                    },
                })
                        .success(function() {

                        })
                        .error(function() {
                            revertFunc();
                        });

                //revertFunc()



            },
            eventResize: function(event, dayDelta, minuteDelta, revertFunc, jsEvent, ui, view) {
                var eventCopy = jQuery.extend(true, {}, event);
                eventCopy.start = convertDateTime(event.start);
                eventCopy.end = convertDateTime(event.end);

                $.ajax({
                    url: "<?php echo url('calendarGeneral/default/update') ?>&id=" + event.id,
                    type: 'POST',
                    data: {
                        CalendarEvent: eventCopy,
                        YII_CSRF_TOKEN: "<?php echo $token ?>"
                    },
                })
                        .success(function() {

                        })
                        .error(function() {
                            revertFunc();
                        });
            },
            loading: function(bool) {
                if (bool)
                    $('#loading').show();
                else
                    $('#loading').hide();
            },
            viewDisplay: function(view) {
                $.cookie('PhonalisaSelectedCalendarView', view.name);
                var h;
                if (view.name == "month") {
                    h = NaN;
                }
                else {
                    h = 2500;  // high enough to avoid scrollbars
                }

                $('#calendar').fullCalendar('option', 'contentHeight', h);
            }
        });


        $(".calendarToggle").each(function(index) {
            var isActive = $(this).parent().is('.active');
            if (isActive) {
                var sourceIndex = $(this).data('source-index');
                activeSourceIds.push(sourceIndex);
                calendar.fullCalendar('addEventSource', eventSources[sourceIndex]);
            }

        });

        //$.each(eventSources, function(index, source) {
        //calendar.fullCalendar('addEventSource', source);
        //});


    });


    function isEditable(event) {
        var isEditable;
        if (event.source != undefined) {
            isEditable = event.source.editable;
        }
        else if (event.editable != undefined) {
            isEditable = event.editable;
        }
        else {
            isEditable = false;
        }
        return isEditable;
    }


    function addNewEvent(start, end, allDay) {
        if (allDay) {
            // increment date if full day
            var tempDate = new Date(end);
            end = new Date(tempDate.getTime() + 86400000);
        }

        $('#calendarModal .modal-header h4').html('<?php echo __('CALENDAR_EVENT_CREATE_NEW_EVENT') ?>');
        $('#calendarModal_deleteBtn').hide();
        $('#calendar-grid_Modal_saveBtn').show();
        $.ajax({
            url: '<?php echo $createUrl; ?>',
        })
                .success(function(data) {
                    $('#calendarModal .modal-body').html(data);
                    $('#calendarModal').modal('show');
                    $('#CalendarEvent_start').val(convertDateTime(start));
                    $('#CalendarEvent_allDay').prop('checked', allDay);
                    $('#CalendarEvent_end').val(convertDateTime(end));

                    $('#CalendarEvent_start').attr('data-date', convertDateTime(start));
                    $('#CalendarEvent_end').attr('data-date', convertDateTime(end));
                    initDTP();
                });
    }

    function initDTP() {

        var pattern = '<?php echo DTPUserDatePattern(true) ?>';
        var showMeridian = false;

        if ('<?php echo $user->timeFormat; ?>' == '12') {
            showMeridian = true;
        }

        //init Start DateTimepicker :

        var timestampDiff = 86400000;
        $('#CalendarEvent_start').parent().parent().datetimepicker({
            format: pattern,
            autoclose: true,
            forceParse: false,
            showMeridian: showMeridian,
            pickerPosition: "bottom-left",
        }).on('show', function() {

            var parsedData = parseGermanDateToDTPFormat($('#CalendarEvent_start').val());
            var startTimestamp = parsedData.getTime();

            parsedData = parseGermanDateToDTPFormat($('#CalendarEvent_end').val());
            var endTimestamp = parsedData.getTime();

            timestampDiff = endTimestamp - startTimestamp;

            $('#CalendarEvent_end').parent().parent().datetimepicker('setStartDate', null);

        }).on('hide', function() {

            var parsedData = parseGermanDateToDTPFormat($('#CalendarEvent_start').val());
            var newEndDate = new Date(parsedData.getTime() + timestampDiff);

            $('#CalendarEvent_end').parent().parent().datetimepicker('setDate', newEndDate);
        });

        $('#CalendarEvent_end').parent().parent().datetimepicker({
            format: pattern,
            autoclose: true,
            forceParse: false,
            showMeridian: showMeridian,
            pickerPosition: "bottom-left",
        }).on('show', function() {

            $(this).datetimepicker('setStartDate', parseGermanDateToDTPFormat($('#CalendarEvent_start').val()));
        });
    }

    function parseGermanDateToDTPFormat(date) {
        var pattern = '<?php echo phpUserDatePattern() ?>';
        var delimiter = pattern.substr(1, 1);

        if (delimiter == '.') {
            var dateParts = date.split(delimiter);
            var YearTime = dateParts[2].split(' ');
            date = YearTime[0] + '-' + dateParts[1] + '-' + dateParts[0] + ' ' + YearTime[1]
            if (YearTime.length > 2) {
                date += ' ' + YearTime[2];
            }
        }

        return new Date(date);
    }

    /*
     '<?php echo userPatternForTimeFormat('HH:mm{ - HH:mm}', 'hh:mm tt{ - hh:mm tt}'); ?>'
     */

    function convertDateTime(dateTime) {
        var plDateFormat = '<?php echo userPatternForDateFormat(); ?>';
        var plTimeFormat = '<?php echo userPatternForTimeFormat('HH:mm', 'hh:mm tt'); ?>';
        return $.fullCalendar.formatDate(dateTime, plDateFormat + ' ' + plTimeFormat);
    }



</script>


<?php
Yii::app()->clientScript->registerScript(
    'calendarModalScripts',
    "$('#calendarModal').on('keyup', this, function(e){
        if(e.keyCode == 13 && $(this).is(':visible')){
             $('#calendar-grid_Modal_saveBtn').click();
        }
    });

    $('#calendarModal').on('shown', function () {
	   $('#calendarModal').find('input[type=text],textarea,select').filter(':visible:first').focus();
	   $('.modal-backdrop').unbind('click');
    });
    ",
    CClientScript::POS_READY
);
?>




<div id="checkBox-div">
<?php
/*
  echo CHtml::checkBox('test','',array())
 */
?>
</div>
<div id="calendar-grid">
    <style type='text/css'>


        #loading {
            position: absolute;
            top: 5px;
            right: 5px;
        }

        #calendar {
            width: auto;
            margin: 0 auto;
        }
    </style>



    <div id="loading" style="display:none">loading...</div>
    <div id="calendar"></div>






    <style>

    </style>
</div>
<?php
/*
  $model = new CalendarEvent;
  $form=$this->beginWidget('bootstrap.widgets.TbActiveForm', array(
  'id'=>'routing-inbound-form',
  'enableAjaxValidation'=>false,
  ));

  echo "New Event:";
  echo $form->textFieldRow($model,'title');
  echo $form->textFieldRow($model,'start');
  echo $form->textFieldRow($model,'end');
  echo $form->textFieldRow($model,'duration');
  echo $form->textFieldRow($model,'members');
  echo $form->textFieldRow($model,'url');
  echo "<br>";
  echo CHtml::submitButton('save');

  $this->endWidget();
 */
?>




<?php
$this->beginWidget('bootstrap.widgets.TbModal', array('id' => 'calendarModal'));
?>

<div class="modal-header">
    <a class="close" data-dismiss="modal">&times;</a>
    <h4>Modal header</h4>
</div>

<div class="modal-body">
<?php ?>
</div>

<div class="modal-footer">
<?php
$saveBtnId = 'calendar-grid_Modal_saveBtn';

$this->widget('bootstrap.widgets.TbButton', array(
    'type' => 'danger',
    'icon' => 'trash',
    //'label'=>__('GLOBAL_DELETE_BUTTON'),
    'url' => '',
    'htmlOptions' => array(
        'class' => 'pull-left',
        'id' => 'calendarModal_deleteBtn',
        'data-translation-id' => 'CALENDAR_EVENT_DELETE_CONFIRM',
    ),
));


$this->widget('bootstrap.widgets.TbButton', array(
    'buttonType' => 'link',
    //'type'=>'danger',
    'icon' => 'icon-question',
    'url' => Yii::app()->controller->getHelpUrl(null, true),
    'encodeLabel' => false,
    'htmlOptions' => array(
        //'id'=>$deleteBtnId,
        'data-translation-id' => 'GLOBAL_HELP_BTN',
        'title' => __('GLOBAL_HELP_BTN'),
        'target' => "_blank",
        'class' => 'pull-left'
    ),
));

$this->widget('bootstrap.widgets.TbButton', array(
    'buttonType' => 'button',
    'type' => 'primary',
    'label' => __('GLOBAL_SAVE_BUTTON'),
    'loadingText' => __('GLOBAL_LOADING_TEXT'),
    'htmlOptions' => array('id' => $saveBtnId, 'class' => 'modalSaveBtn'),
));


Yii::app()->clientScript->registerScript(
    'asd',
    "$('#" . $saveBtnId . "').click(function() {
        var btn = $(this);
        btn.button('loading');
        $('#calendar-grid_hiddenSaveBtn').click();
    });"
);

$this->widget(
    'bootstrap.widgets.TbButton',
    array(
        'label' => __('GLOBAL_CANCEL_BUTTON'),
        'url' => '#',
        'htmlOptions' => array('data-dismiss' => 'modal'),
    )
);
?>
</div>
    <?php
    if (Yii::app()->user->translateMode) {
        echo '<i '
            . 'data-translation-target="CALENDAR_NAVBAR_TRANSLATION_TARGET" '
            . 'data-translation-id="CALENDAR_NAVBAR_HEADER_TITLE"'
            . '>'
            . '</i>';
        echo '<i '
            . 'data-translation-target="CALENDAR_NAVBAR_TRANSLATION_TARGET" '
            . 'data-translation-id="CALENDAR_TODAY"'
            . '>'
            . '</i>';
        echo '<i '
            . 'data-translation-target="CALENDAR_NAVBAR_TRANSLATION_TARGET" '
            . 'data-translation-id="CALENDAR_MONTH_VIEW"'
            . '>'
            . '</i>';
        echo '<i '
            . 'data-translation-target="CALENDAR_NAVBAR_TRANSLATION_TARGET" '
            . 'data-translation-id="CALENDAR_WEEK_VIEW"'
            . '>'
            . '</i>';
        echo '<i '
            . 'data-translation-target="CALENDAR_NAVBAR_TRANSLATION_TARGET" '
            . 'data-translation-id="CALENDAR_DAY_VIEW"'
            . '>'
            . '</i>';
    }
    ?>
<?php $this->endWidget();
