<?php
Yii::app()->clientScript->registerCoreScript('jquery.ui');
Yii::app()->clientScript->registerScriptFile(bu() . '/js/jquery-ui-plugins/jquery-ui-resizable-alsoResizeReverse.js', CClientScript::POS_BEGIN);
?>
<div>
    <script>
        $(function () {
            $("#routing-inbound-grid tbody").sortable();
            $("#routing-inbound-grid .scalableColumn").each(function (i, el) {
                $(el).resizable({
                    alsoResizeReverse: "#" + el.id + "+th"
                });
            });

            $("#routing-inbound-grid tbody").on("sortstop", function (event, ui) {
                $.each($("#routing-inbound-grid tbody tr"), function (i, e) {
                    $(e).find('input.hidenIndex').val(i);
                });
            });
        });
    </script>

    <?php
    $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array(
        'id' => 'routing-inbound-form',
        'enableAjaxValidation' => true,
    ));
    $currentGateway = Gateway::model()->findByPk($_GET['gw_id']);
    ?>

    <script>
        function aftValidate(form, data, hasError) {
            if (!hasError) {
                var formData = new FormData($('#routing-inbound-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) {
                        $("#saveNewRoutingInboundButton").button('reset');
                        $("#newRoutingInboundModal").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);
                $("#saveNewRoutingInboundButton").button('reset');
            }
            return false;
        }

    </script>
    <?php
    $script = "
$('.overWriteDialOutPrefixCheckBox').click(function() {
	var id = $(this).attr('id');
	if($(this).is(':checked')) {
		$('#RoutingInbound_'+id+'_overwriteDialPrefix').show();		
	} else {
		$('#RoutingInbound_'+id+'_overwriteDialPrefix').hide();
		$('#RoutingInbound_'+id+'_overwriteDialPrefix').val('');
	}	
}),
";
    Yii::app()->clientScript->registerScript('overWriteDialOutPrefixCheckBox', $script);

    $script = '
$(".targetDropdown").click(function(){
		var id = $(this).attr("data-id");
		if($(this).val() == "manuell") {
			$(this).hide();
			$("#RoutingInbound_"+id+"_manuellTarget").show();
			$("#RoutingInbound_"+id+"_deleteManuellTarget").show();
			$("#RoutingInbound_"+id+"_manuellTarget").val("");
		}
			
	}
)

$(".icon-remove").click(function() {
		var id =  $(this).attr("data-id");
		$(this).hide();
		$("#RoutingInbound_"+id+"_manuellTarget").hide();
		$("#RoutingInbound_"+id+"_manuellTarget").val("");
		$("#RoutingInbound_"+id+"_target").show();
		$("#RoutingInbound_"+id+"_target").prop("selectedIndex", 0);
	}
)
';
    Yii::app()->clientScript->registerScript('manuellTarget', $script);

    $gatewayDropdown = array('');
    if ($model->renderGatewayDropdown() != NULL) {
        $gatewayDropdown = array(
            'label' => __('ROUTING_INBOUND_NAVBAR_GATEWAY_DROPDOWN_LABLE'),
            'url' => '#',
            'items' => $model->renderGatewayDropdown(),
            'linkOptions' => array(
                'id' => 'addNewRoutingInboundButton',
                'data-target' => '#newRoutingInboundModal',
                'data-translation-id' => 'ROUTING_INBOUND_NAVBAR_GATEWAY_DROPDOWN_LABLE',
            ),
        );
    }
    ?>

    <div class="form">
        <?php
// Container for ErrorMessages :
        echo "<div id='alertFlash'></div>";

        if (!isset($dataProvider)) {
            $dataProvider = $model->search();
        }
        $realCount = $model->search()->getItemCount() - 2;
        $this->widget('ext.PlGrid.PlGridView', array(
            'id' => 'routing-inbound-grid',
            'headerTitle' => 'NAVBAR_TITLE', // optional
            'navBarTitleAppend' => CHtml::encode($currentGateway->name),
            'dataProvider' => $dataProvider,
            '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
            'selectableRows' => 2,
            'enableAddButton' => false,
            'enableSearchButton' => false,
            'navBarHtmlOptions' => array('class' => 'hasImportExportMenu'),
            'customButtons' => array(
                $gatewayDropdown,
            ),
            'columns' => array(
                array(
                    'value' => '"<i class=\"icon-fullscreen\"></i>"',
                    'type' => 'raw'
                ),
                array(
                    'name' => 'active',
                    'type' => 'raw',
                    'value' => array($this, 'renderAktivCell'),
                    'header' => $model->getAttributeLabel('active'),
                    'headerHtmlOptions' => array(
//                            "class"=>"scalableColumn",
                        'data-translation-id' => 'ROUTING_INBOUND_MODEL_ACTIVE'
                    )
                ),
                array(
                    'name' => 'pattern',
                    'type' => 'raw',
                    'value' => array($this, 'renderPatternCell'),
                    'header' => $model->getAttributeLabel('pattern'),
                    'headerHtmlOptions' => array(
                        "class" => "scalableColumn",
                        'data-translation-id' => 'ROUTING_INBOUND_MODEL_PATTERN'
                    )
                ),
                array(
                    'name' => 'score',
                    'type' => 'raw',
                    'header' => $model->getAttributeLabel('score'),
                    "visible" => strlen(cfg("CALL_PROTECTION_API_KEY")) > 0 ? true : false,
                    'headerHtmlOptions' => array(
                        'class' => 'scalableColumn',
                        'data-translation-id' => 'ROUTING_INBOUND_MODEL_SCORE'
                    ),
                    'value' => array($this, 'renderScoreDropdown')
                ),
                array(
                    'name' => 'target',
                    'type' => 'raw',
                    'value' => array($this, 'renderTargetCell'),
                    'header' => $model->getAttributeLabel('target'),
                    'headerHtmlOptions' => array(
                        "class" => "scalableColumn",
                        'data-translation-id' => 'ROUTING_INBOUND_MODEL_TARGET'
                    )
                ),
                array(
                    'name' => 'dateTimeProfile',
                    'type' => 'raw',
                    'header' => $model->getAttributeLabel('dateTimeProfile'),
                    'headerHtmlOptions' => array(
                        "class" => "scalableColumn",
                        'data-translation-id' => 'ROUTING_INBOUND_MODEL_DATE_TIME_PROFILE'
                    ),
                    'value' => array($this, 'renderDateTimeProfile'),
                    'visible' => PhonalisaLicenseManager::systemDateTimeProfileEnabled(),
                ),
                array(
                    'name' => 'overwriteDialPrefix',
                    'type' => 'raw',
                    'value' => array($this, 'renderDialoutPrefixCell'),
                    'header' => $model->getAttributeLabel('overwriteDialPrefix'),
                    'headerHtmlOptions' => array(
                        "class" => "scalableColumn",
                        'data-translation-id' => 'ROUTING_INBOUND_MODEL_OVERWRITE_DIAL_PREFIX'
                    )
                ),
                array(
                    'name' => 'cid_prefix',
                    'type' => 'raw',
                    'value' => array($this, 'renderCidPrefixCell'),
                    'header' => $model->getAttributeLabel('cid_prefix'),
                    'headerHtmlOptions' => array(
                        "class" => "scalableColumn",
                        'data-translation-id' => 'ROUTING_INBOUND_MODEL_CID_PREFIX'
                    )
                ),
                array(
                    'name' => 'desc',
                    'type' => 'raw',
                    'header' => $model->getAttributeLabel('desc'),
                    'value' => array($this, 'renderDescCell'),
                    'headerHtmlOptions' => array(
                        'data-translation-id' => 'ROUTING_INBOUND_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' => 'routingInboundAction', 'style' => 'display:none'));

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

        <script>
            $("#routing-inbound-form").on('click', '.hideableClose', function (el) {
                $parent = $(this).parent();
                $parent.hide();
                $parent.prev().css("display", "inline-block");
                $parent.prev().find('select').val('');
            });

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

            $(document).keypress(function (e) {
                if (e.which === 13) {
                    validateForm();
                    return false;
                }
            });

            function validateForm() {
                var formData = new FormData($('#routing-inbound-form')[0]);
                var url = '<?php echo url("routingInbound/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-inbound-grid').find('.error').each(function (index, element) {
                                $(element).removeClass('error');
                            });
                            $.each(data, function (i, error) {
                                $.each(error, function (index, errorMessage) {
                                    $('#' + index).addClass('error');
                                    $('#alertFlash').find('strong').text(errorMessage);
                                    addErrorClassToCustomPattern(index);
                                    addErrorClassToCustomTarget(index);
                                });
                            });
                            setTimeout(function () {
                                $(".alert").alert('close');
                            }, 6000);
                        } else {
                            var btn = $(this);
                            btn.button('loading'); // call the loading function
                            $("#routingInboundAction").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;
            }

            function checkManualNumber(elem) {
                var targetTypeManual = "<?php echo TargetType::Manual; ?>";
                var targetTypeExtension = "<?php echo PatternType::Manual; ?>";

                if (elem.options[elem.selectedIndex].value === targetTypeManual || elem.options[elem.selectedIndex].value === targetTypeExtension) {
                    $(elem).parent().hide();
                    $(elem).parents().eq(1).find('.targetCustomNumber').css("display", "inline-block");
                } else {
                    $(elem).parents().eq(1).find('.targetCustomNumber').hide();
                }
            }

            function addErrorClassToCustomPattern(index) {
                var customPattern = index.replace('pattern', 'customPattern');
                addErrorClassToCustomFields(index, customPattern);
            }

            function addErrorClassToCustomTarget(index) {
                var customPattern = index.replace('target', 'customNumber');
                var customTargetType = index.replace('target', 'targetType');
                addErrorClassToCustomFields(index, customPattern);
                addErrorClassToCustomFields(index, customTargetType);
            }

            function addErrorClassToCustomFields(index, customPattern) {
                if ($('#' + index).hasClass('error')) {
                    $('#' + customPattern).addClass('error');
                }
            }

        </script>
        <?php
        if (isset($_GET['gw_id'])) {
            if ($model->id == null) {
                $model->id = "new";
            }
            echo CHtml::hiddenField('RoutingInbound[' . $model->id . '][gw_id]', $_GET['gw_id']);
        }// end isset gw_id
        ?>
        <?php
        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) {

//ROUTING_IVR_SELECT_TARGET
            ?>
            <i data-translation-target="ROUTINGINBOUND_MODEL_TARGETS" data-translation-id="ROUTING_IVR_SELECT_TARGET" ></i>
            <i data-translation-target="ROUTINGINBOUND_MODEL_TARGETS" data-translation-id="ROUTINGINBOUND_MODEL_TARGET_USER_FAX" ></i>
            <i data-translation-target="ROUTINGINBOUND_MODEL_TARGETS" data-translation-id="ROUTINGINBOUND_MODEL_TARGET_GROUP_FAX" ></i>
            <i data-translation-target="ROUTINGINBOUND_MODEL_TARGETS" data-translation-id="ROUTINGINBOUND_MODEL_TARGET_OTHER" ></i>	
            <i data-translation-target="ROUTINGINBOUND_MODEL_TARGETS" data-translation-id="ROUTINGINBOUND_MODEL_TARGET_OTHER_CALL_TROUGH" ></i>
            <i data-translation-target="ROUTINGINBOUND_MODEL_TARGETS" data-translation-id="ROUTING_INBOUND_PATTERN_TO_EXTENSION" ></i>

            <i data-translation-target="ROUTING_INBOUND_MODEL_ERROR_HOUR_TARGET" data-translation-id="ROUTING_INBOUND_MODEL_ERROR_HOUR" ></i>	
            <i data-translation-target="ROUTING_INBOUND_MODEL_ERROR_MINUTE_TARGET" data-translation-id="ROUTING_INBOUND_MODEL_ERROR_MINUTE" ></i>

            <i data-translation-id="ROUTINGINBOUND_MODEL_RENDERTARGET_USER" data-translation-target="ROUTINGINBOUND_MODEL_RENDERTARGET"></i>
            <i data-translation-id="ROUTINGINBOUND_MODEL_RENDERTARGET_GROUP" data-translation-target="ROUTINGINBOUND_MODEL_RENDERTARGET"></i>
            <i data-translation-id="ROUTINGINBOUND_MODEL_RENDERTARGET_OTHER" data-translation-target="ROUTINGINBOUND_MODEL_RENDERTARGET"></i>

            <i data-translation-target="ROUTINGINBOUND_MODEL_PATTERNS" data-translation-id="ROUTING_INBOUND_SELECT_PATTERN" ></i>
            <i data-translation-target="ROUTINGINBOUND_MODEL_PATTERNS" data-translation-id="ROUTING_INBOUND_DID" ></i>
            <?php
        }
        ?>
    </div>
</div>


<script>

    var targetTypeAnnouncement = <?php echo TargetType::Announcement ?>;
    var targetTypeCallThrough = <?php echo TargetType::CallThrough ?>;
    var targetTypeCentralDropTarget = <?php echo TargetType::CentralDropTarget ?>;
    var targetTypeExtension = <?php echo TargetType::Extension ?>;
    var targetTypeManual = <?php echo TargetType::Manual ?>;
    var targetTypeUserVoiceMail = <?php echo TargetType::UserVoiceMail ?>;
    var targetTypeEmpty = '<?php echo RoutingInbound::EMPTY_TARGET_TYPE; ?>';

    function updateTargetList(selectedDropdown)
    {
        var targetTypeDropdown = $(selectedDropdown);
        $.ajax({
            url: '<?php echo url("routingInbound/default/ajaxUpdateTargetList"); ?>',
            type: "POST",
            dataType: "json",
            data: {
                type: selectedDropdown.value
            },
            success: function (data) {

                var dataId = targetTypeDropdown.data("id");
                var namePrefix = "RoutingInbound_" + dataId + "_";

                var targetDropdown = $("#" + namePrefix + "target");
                var announcementDropdown = $("#" + namePrefix + "announcement");

                targetDropdown.find('option').remove();
                targetDropdown.find('optgroup').remove();

                $.each(data.availableTargets, function (value, label) {
                    var option = $("<option />").val(value).text(label);
                    targetDropdown.append(option);
                });

                if (targetDropdown.val() === null) {
                    targetDropdown.append($("<option />").val(targetTypeEmpty).text(targetTypeEmpty));
                }

                if (data.targetType === targetTypeManual) {
                    targetTypeDropdown.parent().find(".targetCustomNumber").show();
                    announcementDropdown.parent().hide();
                    targetDropdown.parent().hide();
                } else if (
                        data.targetType === targetTypeCallThrough || 
                        data.targetType === targetTypeCentralDropTarget ||
                        data.targetType === targetTypeExtension||
                        data.targetType === targetTypeEmpty)
                {
                    targetTypeDropdown.parent().find(".targetCustomNumber").hide();
                    announcementDropdown.parent().hide();
                    targetDropdown.parent().hide();
                } else if (data.targetType === targetTypeUserVoiceMail) {
                    targetTypeDropdown.parent().find(".targetCustomNumber").hide();
                    announcementDropdown.parent().show();
                    targetDropdown.parent().show();
                } else if (data.targetType === targetTypeAnnouncement) {
                    targetTypeDropdown.parent().find(".targetCustomNumber").hide();
                    announcementDropdown.parent().show();
                    targetDropdown.parent().hide();
                } else {
                    targetTypeDropdown.parent().find(".targetCustomNumber").hide();
                    announcementDropdown.parent().hide();
                    targetDropdown.parent().show();
                }
            }
        });
    }

    $("[id*='_targetType']").on("change", function () {
        updateTargetList(this);
    });

    $(document).ready(function () {
        $.each($("[id*='_targetType']"), function (index, value) {
            if (
                    $(value).val() === String(targetTypeCentralDropTarget) ||
                    $(value).val() === String(targetTypeCallThrough) ||
                    $(value).val() === String(targetTypeExtension)
                    ) {
                updateTargetList(value);
            }
        });
        $("#alertFlash").prependTo(".grid-view");
    });
</script>