<?php
$htmlOptions = array('data-translation-id' => 'THIRDPARTYCREDENTIAL_MODEL_CALENDAR_CHECKBOX');
if (!PhonalisaLicenseManager::adminCalendarEnabled()) {
    $htmlOptions = array('style' => 'display:none', 'disabled' => 'disabled');
}

$form = $this->beginWidget('ext.PlGrid.PlActiveForm', array(
    'id' => 'iCloud-table-form',
    'gridId' => 'third-party-credentials-grid',
    'action' => $model->isNewRecord ? array('create') : array()
        ));
echo $form->checkBoxRow($model, 'addressBookCheckBox', array('data-translation-id' => 'THIRDPARTYCREDENTIAL_MODEL_ADDRESSBOOK_CHECKBOX'));
echo $form->dropDownListRow($model, 'addressBookId', $availableAddressBooks, array('data-translation-id' => 'THIRDPARTYCREDENTIAL_MODEL_ADDRESSBOOK_ID'));
echo $form->checkBoxRow($model, 'calendarCheckBox', $htmlOptions);
echo $form->textFieldRow($model, 'title', array('data-translation-id' => 'THIRDPARTYCREDENTIAL_MODEL_TITLE', 'readonly' => true));
echo $form->textFieldRow($model, 'username', array('data-translation-id' => 'THIRDPARTYCREDENTIAL_MODEL_USERNAME', 'readonly' => true));
echo $form->passwordFieldRow($model, 'password', array('data-translation-id' => 'THIRDPARTYCREDENTIAL_MODEL_PASSWORD', 'readonly' => true));
echo $form->textFieldRow($model, 'serverURI', array('data-translation-id' => 'THIRDPARTYCREDENTIAL_MODEL_SERVERURI', 'readonly' => true));
echo $form->textFieldRow($model, 'addressBookURI', array('readonly' => true));
echo $form->textFieldRow($model, 'provider', array('readonly' => true));
echo $form->textFieldRow($model, 'syncCalendars', array('readonly' => true));
echo $form->textFieldRow($model, 'validate', array('readonly' => true));

echo $form->errorSummary($model);

$this->endWidget();

$iCloudCalendarList = CHtml::activeDropDownList($model, 'iCloudCalendars', $availableICloudCalendars, array('name' => 'iCloudCalendarDropDown', 'class' => 'span2'));
$calendarList = CHtml::activeDropDownList($model, 'calendarId', $availableCalendars, array('name' => 'calendarDropDown', 'class' => 'span2'));

$this->widget('ext.PlGrid.PlGridView', array(
    'id' => 'iCloud-table-grid',
    'dataProvider' => $model->modalSearch($model->id),
    'enableHistory' => false,
    'type' => 'striped bordered condensed',
    'itemsCssClass' => 'plTable items',
    'enableSorting' => false,
    'modalSize' => 'large',
    'showNavbar' => false,
    'summaryText' => false,
    'rowCssClassExpression' => '!$data->id?"hideRow":""',
    'columns' => array(
        array(
            'name' => 'iCloudCalendars',
            'header' => __('THIRDPARTYCREDENTIAL_MODEL_ICLOUD_CALENDAR_ID'),
            'headerHtmlOptions' => array('data-translation-target' => 'THIRDPARTYCREDENTIAL_MODEL_ICLOUD_CALENDAR_ID'),
            'footer' => $iCloudCalendarList,
        ),
        array(
            'name' => 'calendarId',
            'header' => __('THIRDPARTYCREDENTIAL_MODEL_CALENDAR_ID'),
            'headerHtmlOptions' => array('data-translation-target' => 'THIRDPARTYCREDENTIAL_MODEL_CALENDAR_ID'),
            'footer' => $calendarList,
        ),
        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();
                                removeCalendar(this);
                                return false;
                        }',
                ),
            ),
            'footer' => '<div style="cursor: pointer;" class="icon-plus addCalendarSync"  
            					data-toggle="tooltip" title="' . __("THIRDPARTYCREDENTIAL_MODEL_ADD_CALENDAR") . '"
            					data-translation-id="THIRDPARTYCREDENTIAL_MODEL_ADD_CALENDAR">
            		</div>',
        ),
    ))
);
?>

<style>
    .hideRow{
        display:none;
    }

    .addCalendarSync{
        background-color: #fff;
    }
</style>

<script>
    $("#third-party-credentials-grid_Modal_saveBtn").button("reset");
    $('#ThirdPartyCredential_serverURI').val($('#ThirdPartyCredential_addressBookURI').val());
    hideICloudData();
    checkAddressBookCheckBox();
    checkCalendarCheckBox();
    getSameCalendarName();
    removeLabelIfFieldNotUsed();

    var firstCalendar = $('#iCloud-table-grid tbody tr').first();
    var calendarIndex = $('#iCloud-table-grid tbody').find('.icon-trash').length;
    var calendarArray = new Array();

    $('#ThirdPartyCredential_addressBookCheckBox').change(function () {
        checkAddressBookCheckBox();
    });

    $('#ThirdPartyCredential_calendarCheckBox').change(function () {
        checkCalendarCheckBox();
    });

    $('#iCloudCalendarDropDown').change(function () {
        getSameCalendarName();
    });

    $('.addCalendarSync').click(function () {
        addItem();
    });

    $('#iCloud-table-form').submit(function () {
        if (document.getElementById('ThirdPartyCredential_addressBookCheckBox').checked) {
            validate(calendarArray);
        } else if (document.getElementById('ThirdPartyCredential_calendarCheckBox').checked && typeof calendarArray !== 'undefined' && calendarArray.length > 0) {
            validate(calendarArray);
        }
    });

    function hideICloudData() {
        $('#ThirdPartyCredential_serverURI').closest(".control-group").hide();
        $('#ThirdPartyCredential_title').closest(".control-group").hide();
        $('#ThirdPartyCredential_username').closest(".control-group").hide();
        $('#ThirdPartyCredential_password').closest(".control-group").hide();
        $('#ThirdPartyCredential_provider').closest(".control-group").hide();
        $('#ThirdPartyCredential_addressBookURI').closest(".control-group").hide();
        $('#ThirdPartyCredential_syncCalendars').closest(".control-group").hide();
        $('#ThirdPartyCredential_validate').closest(".control-group").hide();
    }

    function checkAddressBookCheckBox() {
        if (document.getElementById('ThirdPartyCredential_addressBookCheckBox').checked) {
            $('#ThirdPartyCredential_addressBookId').closest(".control-group").show();
            $("#ThirdPartyCredential_addressBookId").removeAttr('disabled');
        } else {
            $('#ThirdPartyCredential_addressBookId').closest(".control-group").hide();
            $('#ThirdPartyCredential_addressBookId').attr('disabled', 'disabled');
            $('#ThirdPartyCredential_addressBookId').val('');
        }
    }

    function checkCalendarCheckBox() {
        if (document.getElementById('ThirdPartyCredential_calendarCheckBox').checked) {
            $('#iCloud-table-grid').show();
            $('#third-party-credentials-grid_Modal').addClass('modal-large');
        } else {
            $('#iCloud-table-grid').hide();
            $('#third-party-credentials-grid_Modal').removeClass('modal-large');
        }
    }

    function getSameCalendarName() {
        $('#calendarDropDown option').each(function () {
            if (this.text === $('#iCloudCalendarDropDown :selected').text()) {
                $("#calendarDropDown").val(this.value);
                return false;
            }
        });
    }

    function addItem() {
        calendarIndex = calendarIndex + 1;

        var label = $('#calendarDropDown').find(':selected').text();
        var calendarId = $('#calendarDropDown').find(':selected').val();
        var iCloudLabel = $('#iCloudCalendarDropDown').find(':selected').text();
        var iCloudCalendarId = $('#iCloudCalendarDropDown').find(':selected').val();

        checkCalendarCheckBox();

        $('#iCloudCalendarDropDown').find(':selected').remove();
        $('#calendarDropDown').find(':selected').remove();
        var result = firstCalendar.clone();

        $(result).find('input').each(function (i, el) {
            el.name = el.name.replace('0', calendarIndex);
            el.id = el.id.replace('0', calendarIndex);
        });

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

        var calendarObject = {};

        $(result).find('td:first-child')
                .html(
                        '<div>' + iCloudLabel + '</div><input type="hidden" name="ThirdPartyCredential[' + calendarIndex + '][iCloudCalendars]" value="' + iCloudCalendarId + '" ></input>'
                        );
        $(result).find('td:first-child').next()
                .html(
                        '<div>' + label + '</div><input type="hidden" name="ThirdPartyCredential[' + calendarIndex + '][calendarId]" value="' + calendarId + '" ></input>'
                        );
        calendarObject[iCloudCalendarId] = calendarId;
        calendarArray.push(calendarObject);
        $(result).removeClass('hideRow');
        $('#iCloud-table-grid > table').append(result.clone().addClass('new-item-animated'));
        if (!document.getElementById('calendarDropDown').options[document.getElementById('calendarDropDown').options.selectedIndex] ||
                !document.getElementById('iCloudCalendarDropDown').options[document.getElementById('iCloudCalendarDropDown').options.selectedIndex]) {
            $('#iCloud-table-grid tfoot').hide();
        }
        getSameCalendarName();
    }

    function removeCalendar(el) {
        var optionICloudText = $(el).parent().parent().find("td:first-child div").html();
        var optioniCloudValue = $(el).parent().parent().find("td:first-child :hidden").val();
        var optionPhonalisaText = $(el).parent().parent().find("td:first-child").next().find("div").html();
        var optionPhonalisaValue = $(el).parent().parent().find("td:first-child").next().find(":hidden").val();

        calendarArray.splice($.inArray(optioniCloudValue, calendarArray), 1);

        $("#iCloudCalendarDropDown").append($('<option />').text(optionICloudText).val(optioniCloudValue));
        $("#calendarDropDown").append($('<option />').text(optionPhonalisaText).val(optionPhonalisaValue));
        $(el).parent().parent().remove();
        $('#iCloud-table-grid tfoot ').show();

        getSameCalendarName();
    }

    function deleteArrayEntry(array, item) {
        array = jQuery.grep(array, function (value) {
            return value !== item;
        });

        return array;
    }

    function validate(calendarArray) {
        if (document.getElementById('ThirdPartyCredential_calendarCheckBox').checked) {
            string = JSON.stringify(calendarArray);
            if (typeof string === 'undefined' || !string || string === '') {
                return false;
            }
            $('#ThirdPartyCredential_syncCalendars').val(string);
        }

        $('#ThirdPartyCredential_validate').val('true');

        $("#third-party-credentials-grid_Modal_saveBtn").button("loading");
        location.reload();
        return true;
    }

    function removeLabelIfFieldNotUsed() {
        if (!$('#ThirdPartyCredential_calendarCheckBox').is(':visible')) {
            $('#ThirdPartyCredential_calendarCheckBox').parent().hide();
            $('#ThirdPartyCredential_addressBookCheckBox').prop('checked', 'checked');
            $('#ThirdPartyCredential_addressBookCheckBox').prop('disabled', 'disabled');
            checkAddressBookCheckBox();
        }
    }
</script>