<?php
$modelTiers = new Tiers;
$modelTiers->static_member = true;
$listData = $modelTiers->getQueueDropDownData($model->id);
$sortrdLisrtData = array();

foreach ($listData as $id => $value) {
    $help = $value;
    $helpValue = strtolower($help);
    $sortrdLisrtData [$id] = $value;
}
asort($sortrdLisrtData);
foreach ($sortrdLisrtData as $id => $value) {
    if (strlen($value) > 16) {
        $value = substr($value, 0, 13);
        $value = $value . '...';
        $listData[$id] = $value;
    }
    $sortrdLisrtData[$id] = $listData[$id];
}

$html = CHtml::activeDropDownList($modelTiers, 'queueId', $sortrdLisrtData, array('name' => 'queuesDropdown', 'class' => 'span2'));
$this->widget('bootstrap.widgets.TbGridView', array(
    'id' => 'queues-grid',
    'dataProvider' => $modelTiers->search($model->id),
    'enableHistory' => false,
    'type' => 'striped bordered condensed', //change color from columns in 'white' and 'grey' responsively
    'itemsCssClass' => 'plTable items', //change design of the table, removed search bar
    'enableSorting' => true,
    'summaryText' => false,
    'rowCssClassExpression' => '!$data->id?"hideRow":""',
    'columns' => array(
        array(
            'name' => 'queueId',
            'header' => $modelTiers->getAttributeLabel('queue'),
            'headerHtmlOptions' => array('data-translation-id' => 'TIERS_MODEL_QUEUE'),
            'value' => array($this, 'renderQueueInput'),
            'footer' => $html,
        ),
        array(
            'name' => 'static_member',
            'type' => 'raw',
            'header' => $modelTiers->getAttributeLabel('static_member'),
            'headerHtmlOptions' => array('data-translation-id' => 'TIERS_MODEL_STATIC_MEMBER'),
            'value' => array($this, 'renderQueueInput'),
            'footer' => $this->renderPartial('queueInput', array('tier' => $modelTiers, 'row' => 'footer', 'data' => $modelTiers, 'column' => 'static_member'), true),
        ),
        array(
            'name' => 'level',
            'type' => 'raw',
            'header' => $modelTiers->getAttributeLabel('level'),
            'headerHtmlOptions' => array('data-translation-id' => 'TIERS_MODEL_LEVEL'),
            'value' => array($this, 'renderQueueInput'),
            'footer' => $this->renderPartial('queueInput', array('tier' => $modelTiers, 'row' => 'footer', 'data' => $modelTiers, 'column' => 'level'), true),
            'visible' => $this->getQueueAttributeVisibility()
        ),
        array(
            'name' => 'position',
            'type' => 'raw',
            'header' => $modelTiers->getAttributeLabel('position'),
            'headerHtmlOptions' => array('data-translation-id' => 'TIERS_MODEL_POSITION'),
            'value' => array($this, 'renderQueueInput'),
            'footer' => $this->renderPartial('queueInput', array('tier' => $modelTiers, 'row' => 'footer', 'data' => $modelTiers, 'column' => 'position'), true),
            'visible' => $this->getQueueAttributeVisibility()
        ),
        array(
            'name' => 'timeout',
            'type' => 'raw',
            'header' => $modelTiers->getAttributeLabel('timeout'),
            'headerHtmlOptions' => array('data-translation-id' => 'TIERS_MODEL_TIMEOUT', 'style' => 'width:110px;'),
            'value' => array($this, 'renderQueueInput'),
            'footer' => $this->renderPartial('queueInput', array('tier' => $modelTiers, 'row' => 'footer', 'data' => $modelTiers, 'column' => 'timeout'), true),
        ),
        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' => "",
                    'visible' => 'true', //FIXME
                    'click' => 'js:function(){ 
                                        $(this).parent().find(".tooltip-inner").remove();
                                        $(this).parent().find(".tooltip-arrow").remove();
                                        removeQueue(this);
                                        $("#queues-grid tfoot").show();
                                        return false;
                        }',
                ),
            ),
            'footer' => '<div style="cursor: pointer;" class="icon-plus addQueueRow"  
        							data-toggle="tooltip" title="' . __("TIERS_FORM_ADD_QUEUE_TOOLTIP") . '"
        							data-translation-id="TIERS_FORM_ADD_QUEUE_TOOLTIP">
        			</div>',
        ),
    ),
        )
);
?>
<style>
    .hideRow{
        display:none;
    }

    .addQueueRow{
        background-color: #fff;
    }
</style>
<script>
    if (!document.getElementById('queuesDropdown').options[document.getElementById('queuesDropdown').options.selectedIndex]) {
        $('#queues-grid tfoot').hide();
    }
    var firstWeekRule = $('#queues-grid tbody tr').first();
    var queueIndex = $('#queues-grid tbody').find('.icon-trash').length;
    $('.addQueueRow').click(function () {
        queueIndex = queueIndex + 1;

        var label = $('#queuesDropdown').find(':selected').text();
        var userId = $('#queuesDropdown').find(':selected').val();
        var defaultStaticMemberValue = $('#Tiers_footer_static_member').is(':checked');
        var defaultPositionValue = $('#Tiers_footer_position').val();
        var defaultLevelValue = $('#Tiers_footer_level').val();
        var defaultTimeoutValue = $('#Tiers_footer_timeout').val();

        $('#Tiers_footer_static_member').attr('checked', defaultStaticMemberValue);
        $('#Tiers_footer_level').val(defaultLevelValue);
        $('#Tiers_footer_position').val(defaultPositionValue);
        $('#Tiers_footer_timeout').val(defaultTimeoutValue);

        $('#queuesDropdown').find(':selected').remove();

        var result = firstWeekRule.clone();
        $(result).find('input').each(function (i, el) {
            el.name = el.name.replace('0', queueIndex);
            el.id = el.id.replace('0', queueIndex);
        });
        $(result).find('select').each(function (i, el) {
            el.name = el.name.replace('0', queueIndex);
            el.id = el.id.replace('0', queueIndex);
            $(el).find('option[selected]').removeAttr('selected');
        });

        $(result).find('td:first-child')
                .html(
                        '<div>' + label + '</div><input type="hidden" name="Tiers[' + queueIndex + '][queueId]" value="' + userId + '" ></input>' +
                        '<input type="hidden" name="Tiers[' + queueIndex + '][dataId]" value="" ></input>'
                        );
        $(result).find('td:first-child').next().find('input').attr('checked', defaultStaticMemberValue);

        if (typeof defaultPositionValue !== "undefined" && typeof defaultLevelValue !== "undefined") {
            $(result).find('td:first-child').next().next().find('select').find('option[value=' + defaultLevelValue + ']').attr('selected', true);
            $(result).find('td:first-child').next().next().next().find('input').val(defaultPositionValue);
            $(result).find('td:first-child').next().next().next().next().find('input').val(defaultTimeoutValue);
        } else {
            $(result).find('td:first-child').next().next().find('input').val(defaultTimeoutValue);
        }


        $(result).removeClass('hideRow');
        $('#queues-grid > table').append(result.clone().addClass('new-item-animated'));
        
        
        $('#queues-grid tbody tr:last-child').find("input:visible, select:visible").each(function(i,e) {
            var defaultId = e.id.replace(queueIndex, "footer");
            contextHelper.addlisteningElement("#"+e.id, defaultId.toUpperCase() + "_CONTEXT_HELP");
        });
        
        

        if (!document.getElementById('queuesDropdown').options[document.getElementById('queuesDropdown').options.selectedIndex]) {
            $('#queues-grid tfoot').hide();
        }
    });

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

        var label = $(el).parent().parent().find("td:first-child div").text();
        var userId = $(el).parent().parent().find("td:first-child :hidden").val();
        var addDropdownValue = "1";
        for (var k = 0; k < dropdownValues.length; k++) {
            if (userId == dropdownValues[k]) {
                addDropdownValue = "0";
            }
        }

        if (addDropdownValue == "1") {
            if (userId) {
                $("<option/>").val(userId).text(label).appendTo("#queuesDropdown");
            }
        }

        $(el).parent().parent().remove();
        $('#queues-grid tfoot').show();
    }
</script>