<?php
Yii::app()->clientScript->registerCoreScript('jquery.ui');
Yii::app()->clientScript->registerScriptFile(bu() . '/js/jquery-ui-plugins/jquery-ui-resizable-alsoResizeReverse.js', CClientScript::POS_BEGIN);

$form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
    'id' => 'routing-outbound-form',
    'enableAjaxValidation' => true,
        ));
?>

<script>

    $(function () {
        $("#routing-outbound-grid .scalableColumn").each(function (i, el) {
            $(el).resizable({
                alsoResizeReverse: "#" + el.id + "+th"
            });
        });
        $("#routing-outbound-form tbody").sortable();
        $("#routing-outbound-form tbody").on("sortstop", function (event, ui) {
            $.each($("#routing-outbound-form tbody tr"), function (i, e) {
                $(e).find('input.hidenIndex').val(i);
            });
        });
    });

    function aftValidate(form, data, hasError) {
        if (!hasError) {
            var formData = new FormData($('#routing-outbound-form')[0]);
            $.ajax({
                url: form.attr('action'), //server script to process data
                type: 'POST',
                xhr: function () {  // custom xhr
                    myXhr = $.ajaxSettings.xhr();
                    if (myXhr.upload) { // check if upload property exists
                        console.log(myXhr);
                        myXhr.upload.addEventListener('progress', progressHandlingFunction, false); // for handling the progress of the upload
                    }
                    return myXhr;
                },
                //Ajax events
                beforeSend: function () {
                },
                success: function (data) {
                    $("#saveNewRoutingOutboundButton").button('reset');
                    $("#newRoutingOutboundModal").modal('hide');
                    refreshGrid();
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.log('this is error');
                    console.log(jqXHR);
                    console.log(textStatus);
                    console.log(errorThrown);
                },
                //error: errorHandler,
                // Form data
                data: formData,
                //Options to tell JQuery not to process data or worry about content-type
                cache: false,
                contentType: false,
                processData: false
            });
        } else {
            console.log(hasError);
            console.log(form);
            console.log(data);
            $("#saveNewRoutingOutboundButton").button('reset');
        }
        return false;
    }

</script>
<?php
$script = '
$(".toggleOverwriteCallerId").click(function() {
    var id = $(this).attr("data-id");
    if($(this).is(":checked")) {
	$("#RoutingOutbound_"+id+"_overwriteCallerId").show();
	//$("#RoutingOutbound_"+id+"_overwriteCallerId").val()=old;
    } else {
	$("#RoutingOutbound_"+id+"_overwriteCallerId").hide();
	$("#RoutingOutbound_"+id+"_overwriteCallerId").val("");		
    }
})';

Yii::app()->clientScript->registerScript('toggleOverwriteCallerId', $script);
?>
<div class="form">
    <?php
    echo "<div id='alertFlash'></div>";
    if (!isset($dataProvider)) {
        $dataProvider = $model->search();
    }
    $realCount = $model->count();
    $this->widget('ext.PlGrid.PlGridView', array(
        'id' => 'routing-outbound-grid',
        'headerTitle' => 'NAVBAR_TITLE', // optional
        'dataProvider' => $dataProvider,
        'selectableRows' => 1,
        'summaryText' => false,
        'type' => 'striped bordered condensed', //change color from columns in 'white' and 'grey' responsively
        'itemsCssClass' => 'plTable', //change design of the table, removed search bar
        'hideHeaderButtons' => true,
        'navBarHtmlOptions' => array('class' => 'hasImportExportMenu'),
//        'customButtons' => array(
//            'label' => __("GLOBAL_IMPORT_EXPORT_ITEMS"),
//            'icon' => 'wrench',
//            'url' => '',
//            'position' => 'right',
//            "items" => array(
//                array(
//                    "label" => __("GLOBAL_CSV_EXPORT"),
//                    "url" => url('routingOutbound/default/export'),
//                    'linkOptions' => array(
//                        'data-translation-id' => 'GLOBAL_CSV_EXPORT'
//                    ),
//                ),
//                array(
//                    "label" => __("GLOBAL_CSV_IMPORT"),
//                    'linkOptions' => array(
//                        'data-translation-id' => 'GLOBAL_CSV_IMPORT'
//                    ),
//                    "url" => url('addressbookImportExport/default/index', array(
//                        'params' => array(
//                            'model' => get_class($model),
//                            'returnUrl' => url('routingOutbound/default/index'),
//                        )
//                            )
//                    )
//                ),
//            ),
//            'linkOptions' => array(
//                'data-translation-id' => 'GLOBAL_IMPORT_EXPORT_ITEMS'
//            )
//        ),
        'columns' => array(
            array(
                'value' => '"<i class=\"icon-fullscreen\"></i>"',
                'type' => 'raw'
            ),
            array(
                'name' => 'active',
                'type' => 'raw',
                'header' => $model->getAttributeLabel('active'),
                'headerHtmlOptions' => array('data-translation-id' => 'ROUTING_OUTBOUND_MODEL_ACTIVE'),
                'value' => array($this, 'renderActiveCell'),
            ),
            array(
                'name' => 'usergroup',
                'type' => 'raw',
                'value' => array($this, 'renderUserGroupCell'),
                'header' => $model->getAttributeLabel('usergroup'),
                'headerHtmlOptions' => array(
                    "class" => "scalableColumn",
                    'data-translation-id' => 'ROUTING_OUTBOUND_MODEL_USERGROUP'
                )
            ),
            array(
                'name' => 'pattern',
                'type' => 'raw',
                'value' => array($this, 'renderPatternCell'),
                'header' => $model->getAttributeLabel('pattern'),
                'headerHtmlOptions' => array(
                    "class" => "scalableColumn",
                    'data-translation-id' => 'ROUTING_OUTBOUND_MODEL_PATTERN'
                )
            ),
            array(
                'name' => 'gw_id',
                'type' => 'raw',
                'value' => array($this, 'renderGatewayCell'),
                'header' => $model->getAttributeLabel('gw_id'),
                'headerHtmlOptions' => array(
                    "class" => "scalableColumn",
                    'data-translation-id' => 'ROUTING_OUTBOUND_MODEL_GW_ID'
                )
            ),
            array(
                'name' => 'dateTimeProfile',
                'value' => array($this, 'renderDateTimeProfile'),
                'header' => $model->getAttributeLabel('dateTimeProfile'),
                'headerHtmlOptions' => array(
                    "class" => "scalableColumn",
                    'data-translation-id' => 'ROUTING_OUTBOUND_MODEL_DATE_TIME_PROFILE'
                ),
                'visible' => PhonalisaLicenseManager::systemDateTimeProfileEnabled(),
            ),
            array(
                'name' => 'overwriteCallerId',
                'type' => 'raw',
                'value' => array($this, 'renderOverwriteCallerIdCell'),
                'header' => $model->getAttributeLabel('overwriteCallerId'),
                'headerHtmlOptions' => array(
                    "class" => "scalableColumn",
                    'data-translation-id' => 'ROUTING_OUTBOUND_MODEL_OVERWRITE_CALLER_ID'
                )
            ),
            array(
                'name' => 'lcrPrefix',
                'header' => $model->getAttributeLabel('lcrPrefix'),
                'value' => array($this, 'renderLcrPrefix'),
                'headerHtmlOptions' => array(
                    "class" => "scalableColumn",
                    'data-translation-id' => 'ROUTING_OUTBOUND_MODEL_LCR_PREFIX'
                )
            ),
            array(
                'name' => 'desc',
                'header' => $model->getAttributeLabel('desc'),
                'value' => array($this, 'renderDescCell'),
                'headerHtmlOptions' => array(
                    'data-translation-id' => 'ROUTING_OUTBOUND_MODEL_DESC'
                )
            ),
            array(
                // 'name'=>'sort',
                'type' => 'raw',
                'htmlOptions' => array('style' => 'display:none'),
                'headerHtmlOptions' => array('style' => 'display:none'),
                'value' => array($this, 'renderhiddenSortCell')
            ),
            array(
                'class' => 'bootstrap.widgets.TbButtonColumn',
                'htmlOptions' => array('class' => 'buttonColumnIcons'),
                'template' => '{delete}',
                'buttons' => array(
                    'delete' => array('visible' => '$data->pattern != null'),
                ),
            ),
        ),
    ));
    echo CHtml::submitButton('save', array('id' => 'routingOutboundAction', 'style' => 'display:none'));

    $this->widget('bootstrap.widgets.TbButton', array(
        'buttonType' => 'button',
        'type' => 'primary',
        'label' => __('GLOBAL_SAVE_BUTTON'),
        'loadingText' => 'loading...',
        'htmlOptions' => array(
            'id' => 'saveRoutingOutboundButton',
            'data-translation-id' => 'GLOBAL_SAVE_BUTTON',
        ),
    ));
    ?>
    <script>

        $('#saveRoutingOutboundButton').click(function () {
            validateForm();
            return false;
        });

        function validateForm() {
            var formData = new FormData($('#routing-outbound-form')[0]);
            var url = '<?php echo url("routingOutbound/default/ajaxValidate"); ?>'; //FIXME 
            var isValid = false;
            $.ajax({
                url: url,
                type: 'POST',
                dataType: 'json',
                //Ajax events
                beforeSend: function () {
                },
                success: function (data) {
                    if (data) {
                        var alertBlockTemplate = '<div class="alert alert-error alert-block fade in"><strong></strong><a class="close" data-dismiss="alert" href="#">&times;</a></div>';
                        $('#alertFlash').html(alertBlockTemplate);
                        $('#routing-outbound-grid').find('.error').each(function (inx, element) {
                            $(element).removeClass('error');
                        });
                        $.each(data, function (i, error) {
                            $.each(error, function (index, errorMessage) {
                                $('#' + index).addClass('error');
                                $('#alertFlash').find('strong').text(errorMessage);

                            });
                        });
                        setTimeout(function () {
                            $(".alert").alert('close');
                        }, 6000);
                    } else {
                        var btn = $(this);
                        btn.button('loading'); // call the loading function
                        $("#routingOutboundAction").click();
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.log('this is error');
                    console.log(jqXHR);
                    console.log(textStatus);
                    console.log(errorThrown);
                },
                //error: errorHandler,
                // Form data
                data: formData,
                //Options to tell JQuery not to process data or worry about content-type
                cache: false,
                contentType: false,
                processData: false
            });
            return isValid;
        }

    </script>
    <?php
    if (isset($_GET['gw_id'])) {
        echo CHtml::hiddenField('RoutingOutbound[' . $model->id . '][gw_id]', $_GET['gw_id']);
    }// end isset gw_id

    if (isset($error) && count($error) > 1) {
        $count = count($error) - 1;
        foreach ($error as $err) {
            if ($err != $error[$count]) {
                echo $err;
            }
        }
    }
    $this->endWidget();
    if (Yii::app()->user->translateMode) {
        ?>
        <i data-translation-target="ROUTING_OUTBOUND_MODEL_ERROR_HOUR_TARGET" data-translation-id="ROUTING_OUTBOUND_MODEL_ERROR_HOUR" ></i>

        <i data-translation-id="ROUTING_OUTBOUND_MODEL_ERROR_HOUR" ></i>	

        <i data-translation-target="ROUTING_OUTBOUND_MODEL_ERROR_MINUTE_TARGET" data-translation-id="ROUTING_OUTBOUND_MODEL_ERROR_MINUTE" ></i>
        <i data-translation-id="ROUTINGOUTBOUND_MODEL_RENDERTARGET_SELECT_TARGET" data-translation-target="ROUTINGOUTBOUND_MODEL_USERGROUP_TARGET"></i>
        <i data-translation-id="ROUTINGOUTBOUND_MODEL_RENDERTARGET_USER" data-translation-target="ROUTINGOUTBOUND_MODEL_USERGROUP_TARGET"></i>
        <i data-translation-id="ROUTINGOUTBOUND_MODEL_RENDERTARGET_GROUP" data-translation-target="ROUTINGOUTBOUND_MODEL_USERGROUP_TARGET"></i>

        <i data-translation-id="ROUTING_OUTBOUND_SELECT_GATEWAY_ACTIVE_GATEWAY" data-translation-target="ROUTING_OUTBOUND_SELECT_GATEWAY_TARGET"></i>
        <i data-translation-id="ROUTING_OUTBOUND_SELECT_GATEWAY_DISABLED_GATEWAY" data-translation-target="ROUTING_OUTBOUND_SELECT_GATEWAY_TARGET"></i>

        <?php
    }
    ?>
</div>
