<?php
// Register script files
cs()->registerScriptFile(Yii::app()->baseUrl . '/js/rangeSlider/jquery-ui-1.8.16.custom.min.js', CClientScript::POS_HEAD);
cs()->registerScriptFile(Yii::app()->baseUrl . '/js/rangeSlider/jQAllRangeSliders-withRuler-min.js', CClientScript::POS_HEAD);
cs()->registerCssFile(Yii::app()->baseUrl . '/js/rangeSlider/css/Phonalisa.css');
cs()->registerScriptFile(Yii::app()->baseUrl . '/js/plDynamicGrid/plDynamicGrid.js', CClientScript::POS_HEAD);


if (Yii::app()->user->translateMode) {
    echo '<i data-translation-target="RING_DELAY_CONFIRM_LEAVE_WITHOUT_CHANGES" data-translation-id="RING_DELAY_CONFIRM_LEAVE_WITHOUT_CHANGES">RING_DELAY_CONFIRM_LEAVE_WITHOUT_CHANGES: ';
    echo __('RING_DELAY_CONFIRM_LEAVE_WITHOUT_CHANGES') . '</i><br><br>';
}


$this->widget('ext.PlNavbar', array(
    'brand' => Yii::t(
            'messages', 'RING_DELAY_FOR_CALL_GROUP', array(
        '{group}' => CHtml::encode($model->name),
        '{extension}' => CHtml::encode($model->extension ? ' < ' . $model->extension . ' > ' : $model->extension )
            )
    ),
    'htmlOptions' => array(
        'data-translation-id' => 'RING_DELAY_FOR_CALL_GROUP',
    ),
    'items' => array(
        array(
            'class' => 'bootstrap.widgets.TbMenu',
            'items' => array(
                '---',
                array(
                    'label' => __('GLOBAL_BACK'),
                    'url' => url('routingCallGroup'),
                    'icon' => 'arrow-left',
                ),
            ),
            'htmlOptions' => array(
                'data-translation-id' => 'GLOBAL_BACK',
            ),
        ),
    ),
));

echo CHtml::beginForm();

$this->widget('bootstrap.widgets.TbGridView', array(
    'id' => 'call-group-member-grid',
    'itemsCssClass' => 'table plTable items',
    'type' => 'striped bordered condensed',
    'dataProvider' => $userDataProvider,
    'summaryText' => false,
    'enableSorting' => false,
    'rowCssClassExpression' => '!$data->id?"hideRow":""',
    'columns' => array(
        array(
            'name' => 'extension',
            'header' => '&nbsp;<i class="icon-fixed-width icon-phone"></i>',
            'headerHtmlOptions' => array('data-translation-id' => 'ROUTING_CALL_GROUP_MODEL_EXTENSION', 'style' => 'width:30px;'),
        ),
        array(
            'name' => 'name',
            'value' => array($this, 'renderUserColumn'),
            'header' => $userModel->getAttributeLabel('name'),
            'headerHtmlOptions' => array('data-translation-id' => 'USERS_MODEL_NAME', 'style' => 'width:150px;'),
            'footer' => $model->renderMemberDropdown(),
        ),
        array(
            'name' => 'firstname',
            'header' => $userModel->getAttributeLabel('firstname'),
            'headerHtmlOptions' => array('data-translation-id' => 'USERS_MODEL_FIRSTNAME', 'style' => 'width:150px;'),
        ),
        array(
            'name' => 'lastname',
            'header' => $userModel->getAttributeLabel('lastname'),
            'headerHtmlOptions' => array('data-translation-id' => 'USERS_MODEL_LASTNAME', 'style' => 'width:150px;'),
        ),
        array(
            'value' => array($this, 'renderStaticMember'),
            'type' => 'raw',
            'header' => __('TIERS_MODEL_STATIC_MEMBER'),
            'headerHtmlOptions' => array('data-translation-id' => 'TIERS_MODEL_STATIC_MEMBER', 'style' => 'width:150px;'),
        ),
        array(
            'value' => array($this, 'renderRingTimeSlider'),
            'htmlOptions' => array('class' => 'sliderCell'),
            'footer' => '<span class="addMember" style="float: right; padding-top: 5px;">' . __('USERGROUP_FORM_ADD_MEMBERS') . '</div>',
            'footerHtmlOptions' => array(
                'style' => 'cursor: pointer;',
                'data-translation-id' => 'USERGROUP_FORM_ADD_MEMBERS',
            )
        ),
        array(
            'class' => 'bootstrap.widgets.TbButtonColumn',
            'htmlOptions' => array(
                'class' => 'buttonColumnIcons',
                'style' => 'width:55px;cursor: pointer;',
                'title' => __("GRID_DELETE_TOOLTIP"),
                'data-translation-id' => "GRID_DELETE_TOOLTIP"
            ),
            'template' => '{delete}',
            'buttons' => array(
                'delete' => array(
                    'url' => '',
                    'label' => "",
                    'click' => 'js:function(){  
                                    $(this).parent().find(".tooltip-inner").remove();
                                    $(this).parent().find(".tooltip-arrow").remove();
                                    removeMember(this);
                                    return false;
                        }',
                ),
            ),
            'footer' => '<span class="icon-plus addMember" style="cursor: pointer;"
                    id="addMember2"
                    data-toggle="tooltip" title="' . __("USERGROUP_FORM_ADD_MEMBERS") . '"
                    data-translation-id="USERGROUP_FORM_ADD_MEMBERS">
                    </span>',
        ),
    ),
));

$this->widget('bootstrap.widgets.TbButton', array(
    'label' => __('GLOBAL_SAVE_BUTTON'),
    'buttonType' => 'submit',
    'type' => 'primary',
    'htmlOptions' => array(
        'onClick' => 'sliderValuesChanged = false'
    )
));

echo CHtml::endForm();
?>

<style>
    .hideRow{
        display:none;
    }
</style>
<script>
    if (!document.getElementById('memberDropdown').options[document.getElementById('memberDropdown').options.selectedIndex]) {
        $('#call-group-member-grid tfoot ').hide();
    }
    var index = $('#call-group-member-grid tbody').find('.icon-trash').length;
    var sliderValuesChanged = false;

    var defaultMaxHoldTime = <?php echo $model->getMaxHoldTime(); ?>;
    var defaultMaxSlider = <?php echo $model->getDefaultMaxSliderTime(); ?>;

    $(".ringTimeSlider").each(function (i, e) {
        initSlider($(e).parent());
    });
    setTimeSlotToUserValueChanges();

    new plDynamicGrid(
            '#call-group-member-grid',
            "removeMember",
            '.addMember',
            "new-item-animated",
            function (element, index) {

                var selectedDropDownValues = parseSelectedDropdownValue();
                var tr = $(element).parent().parent();
                if ($(element).hasClass('userId')) {

                    fillUserDataCells(tr, selectedDropDownValues);
                    if (!document.getElementById('memberDropdown').options[document.getElementById('memberDropdown').options.selectedIndex]) {
                        $('#call-group-member-grid tfoot ').hide();
                    }
                    $(element).parent().parent().removeClass('hideRow');
                    $("#call-group-member-grid tbody tr:last-child").find(".sliderCell .ringTimeSlider").find('*').remove();

                } else if (element.id.indexOf("start") >= 0) {
                    setNewElementId(element, selectedDropDownValues);
                    setNewElementName(element, selectedDropDownValues);
                    element.value = 0;

                } else if (element.id.indexOf("end") >= 0) {

                    setNewElementId(element, selectedDropDownValues);
                    setNewElementName(element, selectedDropDownValues);
                    element.value = defaultMaxSlider;

                    initSlider($(tr));
                    removeSelectedUserDropdownOption();
                    sliderValuesChanged = true;
                    resizeSliderRange();
                    setTimeSlotToUserValueChanges();
                } else if (element.id.indexOf("static_member") >= 0) {
                    element.value = 1;
                }
            }
    );
    $('.hideRow').remove();

    function removeSelectedUserDropdownOption()
    {
        var dropdown = $('#memberDropdown');
        dropdown.find(':selected').remove();
        if (dropdown.find("option").length === 0) {
            dropdown.closest("tfoot").hide();
        }
    }

    function fillUserDataCells(tr, selectedDropDownValues)
    {
        var currentTd = tr.find("td:first-child");
        currentTd.text(selectedDropDownValues.extension);
        currentTd = currentTd.next();
        currentTd.find("div").text(selectedDropDownValues.username);
        currentTd.find("input").val(selectedDropDownValues.userId).attr('label', selectedDropDownValues.label);
        currentTd = currentTd.next();
        currentTd.text(selectedDropDownValues.firstname);
        currentTd = currentTd.next();
        currentTd.text(selectedDropDownValues.lastname);

    }

    function parseSelectedDropdownValue()
    {
        var value = $('#memberDropdown').find(':selected').val();
        var values = value.split("_");

        var result = {
            label: $('#memberDropdown').find(':selected').text(),
            extension: values[0],
            userId: values[1],
            username: values[2],
            firstname: values[3],
            lastname: values[4]
        };
        return result;
    }

    function setNewElementId(element, dropdownValues)
    {
        var newId = "";
        if (element.id.indexOf("start") >= 0) {
            newId += "TimeSlotsUser_" + dropdownValues.userId + "_start";
        } else if (element.id.indexOf("end") >= 0) {
            newId += "TimeSlotsUser_" + dropdownValues.userId + "_end";
        }
        element.id = newId;
    }

    function setNewElementName(element, dropdownValues)
    {
        var newName = "";
        if (element.id.indexOf("start") >= 0) {
            newName += "TimeSlotsUser[" + dropdownValues.userId + "][start]";
        } else if (element.id.indexOf("end") >= 0) {
            newName += "TimeSlotsUser[" + dropdownValues.userId + "][end]";
        }
        element.name = newName;
    }

    function initSlider(selector) {
        var slider = selector.find('.ringTimeSlider');
        slider.rangeSlider({
            valueLabels: "change",
            durationIn: 500,
            durationOut: 2000,
            arrows: false,
            step: 1,
            bounds: {min: 0, max: defaultMaxHoldTime},
            defaultValues: {min: slider.prev().val(), max: slider.next().val()},
            formatter: function (val) {
                var value = Math.round(val * 5) / 5,
                        decimal = value - Math.round(val);
                var result = decimal === 0 ? value.toString() : value.toString();
                return result + ' sec.';
            },
            scales: [
                // Primary scale
                {
                    first: function (val) {
                        return val;
                    },
                    next: function (val) {
                        return val + 10;
                    },
                    stop: function (val) {
                        return false;
                    },
                    label: function (val) {
                        return val;
                    },
                    format: function (tickContainer, tickStart, tickEnd) {
                        tickContainer.addClass("myCustomClass");
                    }
                },
                // Secondary scale
                {
                    first: function (val) {
                        return val;
                    },
                    next: function (val) {
                        if (val % 10 === 9) {
                            return val + 2;
                        }
                        return val + 1;
                    },
                    stop: function (val) {
                        return false;
                    },
                    label: function () {
                        return '';
                    }
                }]
        });
    }

    function setTimeSlotToUserValueChanges() {
        $("#content .ringTimeSlider").bind("userValuesChanged", function (e, data) {
            sliderValuesChanged = true;
            $(this).prev().val(data.values.min);
            $(this).next().val(data.values.max);
        });
    }

    function resizeSliderRange() {
        setTimeout(function () {
            $("#content .ringTimeSlider").each(function () {
                $(this).rangeSlider('resize');
            });
        }, 350);
    }

    setTimeout(function () {
        // Change options after slider creation
        $("#content .ringTimeSlider").rangeSlider("option", "valueLabels", 'change');
    }, 2000);

    function removeMember(el) {
        var dropdownValues = new Array();
        $('#memberDropdown').find('option').each(function (i, e) {
            dropdownValues.push(e.value);
        });

        var label = $(el).first().parent().parent().find("td:first-child").next().find("input").attr('label');
        var extension = $(el).first().parent().parent().find("td:first-child").text();
        var userId = $(el).first().parent().parent().find("td:first-child").next().find("input").val();
        var username = $(el).first().parent().parent().find("td:first-child").next().text();
        var firstname = $(el).first().parent().parent().find("td:first-child").next().next().text();
        var lastname = $(el).first().parent().parent().find("td:first-child").next().next().next().text();

        var newUserValue = extension + "_" + userId + "_" + username + "_" + firstname + "_" + lastname;

        var addDropdownValue = "1";
        for (var k = 0; k < dropdownValues.length; k++) {
            if (newUserValue === dropdownValues[k]) {
                addDropdownValue = "0";
            }
        }

        if (addDropdownValue === "1") {
            if (newUserValue) {
                $("<option/>").val(newUserValue).text(label).appendTo("#memberDropdown");
            }
        }
        resizeSliderRange();
        sliderValuesChanged = true;
        $('#call-group-member-grid tfoot ').show();
        index = index - 1;
        $(el).parent().parent().remove();
    }

    $(window).bind('beforeunload', function () {
        if (sliderValuesChanged) {
            return '<?php echo __("RING_DELAY_CONFIRM_LEAVE_WITHOUT_CHANGES"); ?>';
        }
    });

    $('#userMonitorToggleLink').click(function () {
        resizeSliderRange();
    });
</script>
