;(function ($) {
    var isJalali = !!(window.anbarak && anbarak.is_jalali);

    function getTimestampField($input) {
        var fieldName = $input.data('timestamp-field') || ($input.attr('name') ? $input.attr('name') + '-ts' : '');
        var $form = $input.closest('form');
        var $field = fieldName && $form.length
            ? $form.find('input').filter(function () { return this.name === fieldName; })
            : $();

        if (!$field.length && fieldName) {
            $field = $('<input>', {
                type: 'hidden',
                name: fieldName,
                class: 'date-picker-timestamp'
            }).insertAfter($input.closest('.anbarak-input').length ? $input.closest('.anbarak-input') : $input);
        }

        return $field;
    }

    function getOptions($input, withTime) {
        var $timestampField = getTimestampField($input);
        var options = {
            format: withTime ? 'YYYY/MM/DD HH:mm:ss' : 'YYYY/MM/DD',
            observer: true,
            altField: $timestampField,
            altFormat: 'unix',
            toolbox: {
                calendarSwitch: {
                    enabled: false
                }
            },
            timePicker: {
                enabled: withTime,
                second: {
                    enabled: withTime
                },
                meridian: {
                    enabled: false
                }
            },
            onSelect: function (timestamp) {
                $timestampField.val(timestamp);
                $input.trigger('anbarak:date-picked', [timestamp]);
            },
            onSet: function (timestamp) {
                $timestampField.val(timestamp);
                $input.trigger('anbarak:date-picked', [timestamp]);
            }
        };

        if (isJalali) {
            options.initialValueType = 'persian';
        } else {
            options.initialValueType = 'gregorian';
            options.calendarType = 'gregorian';
            options.persianDigit = false;
        }

        if (!$input.val() && $timestampField.val()) {
            options.initialValueType = 'unix';
            $input.attr('value', $timestampField.val());
        }

        return options;
    }

    function initDatePickers(context) {
        var $context = context ? $(context) : $(document);

        $context.find('input.date-picker, input.datetime-picker').addBack('input.date-picker, input.datetime-picker').each(function () {
            var $input = $(this);
            if ($input.data('anbarak-datepicker')) return;

            var picker = $input.pDatepicker(getOptions($input, $input.hasClass('datetime-picker')));
            $input.data('pdp', picker);
            $input.data('anbarak-datepicker', true);
        });
    }

    function setDatePickerValue($input, timestampMs) {
        if (!$input || !$input.length || timestampMs === null || typeof timestampMs === 'undefined' || timestampMs === '') return;

        initDatePickers($input);

        var picker = $input.data('pdp');
        if (picker && picker.setDate) {
            picker.setDate(timestampMs);
        }

        getTimestampField($input).val(timestampMs);
    }

    window.anbarakInitDatePickers = initDatePickers;
    window.anbarakSetDatePickerValue = setDatePickerValue;

    $(function () {
        initDatePickers(document);
    });
})(jQuery);
