//= require jquery-ui/ui/version.js
//= require jquery-ui/ui/widgets/datepicker.js
//= require jquery-ui/ui/i18n/datepicker-lv.js
//= require jquery-ui/ui/i18n/datepicker-ru.js
//= require jquery-ui/ui/i18n/datepicker-et.js
//= require jquery-ui/ui/i18n/datepicker-en-GB.js
//= require jquery-ui/ui/i18n/datepicker-lt.js

// include english version last because inclusion automatically sets that locale as default

jQuery(function()
{
    'use strict';
    var page = jQuery(document);

    var parse_date_string_to_date_object = function ( date_string )
    {
        var parts;
        var date = '';
        if ( date_string.match( /^\d{4}(-\d{2}){2}$/ ) )
        {
            parts = date_string.split( '-' );
            date = new Date( parts[ 0 ], parts[ 1 ] - 1, parts[ 2 ] );
        }
        else if ( date_string.match(/^(\d{1,2})\.(\d{1,2})\.(\d{4})$/) )
        {
            var parts = date_string.split( '.' );
            date = new Date( parts[ 2 ], parts[ 1 ] - 1, parts[ 0 ] );
        }

        return date;
    };

    var close_datepickers = function()
    {
        var inputs = page.find('input.hasDatepicker');

        inputs.each(function(index)
        {
            jQuery(this).datepicker('hide');
        });
    };

    // add extra space before or after the datepicker
    // to leave space for the box pointer
    var old_offset_function = jQuery.datepicker._checkOffset;
    jQuery.datepicker._checkOffset = function(inst, offset, isFixed)
    {
        var box = jQuery(inst.dpDiv);
        var original_offset = old_offset_function.call(this, inst, offset, isFixed);
        var input_offset = jQuery(inst.input).offset();

        var adjusted_offset = original_offset;
        var offset_adjustment = 12;

        if (input_offset.top > original_offset.top)
        {
            adjusted_offset.top -= offset_adjustment;
        }
        else
        {
            adjusted_offset.top += offset_adjustment;
        }

        return adjusted_offset;
    };

    page.on('contentloaded', function(event)
    {
        var block = jQuery(event.target);

        block.find('.field.date-range').each(function(i, field)
        {
            var from = jQuery(field).find("input").first();
            var to = jQuery(field).find("input").last();

            from.on('change', function()
            {
                to.attr('min', this.value).trigger('rangechange');
            });

            to.on('change', function()
            {
                from.attr('max', this.value).trigger('rangechange');
            });
        });

        var layout = page.data('layout');
        var large_layout = layout.match(/^(medium|full)$/);
        var is_touch_device = jQuery('html').is('.touch-device');

        if (is_touch_device && !large_layout && is_native_input_type_supported('date'))
        {
            return;
        }

        var locale = jQuery('html').attr('lang');

        var regional_options = {};

        // use british english where first day is monday
        if (/^en$/.test(locale))
        {
            locale = 'en-GB';
        }
        // classic estonian case
        if (/ee$/.test(locale))
        {
            locale = 'et';
        }
        if (/lt$/.test(locale))
        {
            locale = 'lt';
        }

        if (locale && (locale in jQuery.datepicker.regional))
        {
            var regional_options = jQuery.extend( true, {}, jQuery.datepicker.regional[ locale ] );
        }
        regional_options.altFormat = 'yy-mm-dd';

        var dateSeparator = regional_options.dateFormat.replace(/[a-z]/gi, '').charAt(0);
        var pattern = 'd{' + dateSeparator + '}`m{' + dateSeparator + '}`Y';

        if (locale === 'lt') {
            pattern = 'Y-m-d';
        }

        var maskDefaults = {
            mask: Date,  // enable date mask

            pattern: pattern,

            // define date -> str conversion
            format: function (date) {
                var day = ('' + date.getDate()).padStart(2, '0');
                var month = ('' + (date.getMonth() + 1)).padStart(2, '0');
                var year = date.getFullYear();

                return [day, month, year].join(dateSeparator);
            },

            // define str -> date conversion
            parse: function (str) {
                var strSplit = str.split(dateSeparator);
                var day   = strSplit[0];
                var month = strSplit[1];
                var year  = strSplit[2];

                return new Date(year, month - 1, day);
            }
        };

        block.find('input[type="date"]').each(function()
        {
            var system_input = jQuery(this);

            var parse_from_string = parse_date_string_to_date_object;

            var options = jQuery.extend( true, {}, regional_options );
            var maskOptions = jQuery.extend( true, {}, maskDefaults );

            system_input.attr({
                type: 'text',
                autocomplete: 'off'
            });

            var user_input      = system_input.clone();
            var system_input_id = system_input.attr('id');
            var user_input_id;
            if (system_input_id)
            {
                user_input_id  = system_input_id + '-user-input';
                user_input.attr('id', user_input_id);
            };

            user_input.removeAttr('name').val('');

            user_input.insertAfter( system_input );

            if (system_input_id)
            {
                var field_label = user_input.closest('.field').find('label');

                if (!field_label.data('updated'))
                {
                    field_label.attr('for', user_input_id);
                    field_label.data('updated', true);
                }
            }

            if ( system_input.attr( 'max' ) )
            {
                var maxDate = parse_from_string( system_input.attr( 'max' ) );

                options[ 'maxDate' ] = maxDate;
                maskOptions['max'] = maxDate;
            }

            if ( system_input.attr( 'min' ) )
            {
                var minDate = parse_from_string( system_input.attr( 'min' ) );

                options[ 'minDate' ] = minDate;
                maskOptions['min'] = minDate;
            }

            if ( system_input.attr( 'default-calendar-date' ) )
            {
                var defaultDate = parse_from_string( system_input.attr( 'default-calendar-date' ) );
                options[ 'defaultDate' ] = defaultDate;
            }

            system_input.hide();

            options.showOn = 'button';
            options.showOtherMonths = true;
            options.changeMonth = true;
            options.changeYear = true;
            options.yearRange = '1900:+10';
            options.altField = system_input;
            options.onSelect = function()
            {
                system_input.trigger('change');
            };

            user_input.datepicker(options);

            var update_from_system_input = function()
            {
                user_input.datepicker(
                    'setDate',
                    parse_from_string(
                        system_input.val().trim()
                    )
                );
            };

            var update_range_from_system_input = function()
            {
                if (system_input.attr('min'))
                {
                    user_input.datepicker(
                        'option',
                        'minDate',
                        parse_from_string(system_input.attr('min'))
                    );
                }

                if (system_input.attr('max'))
                {
                    user_input.datepicker(
                        'option',
                        'maxDate',
                        parse_from_string(system_input.attr('max'))
                    );
                }
            }

            update_from_system_input();

            // validate value when entered manually
            user_input.on('change', function()
            {
                user_input.datepicker('setDate', user_input.datepicker('getDate'));
            });

            // load current value from system field
            system_input.on('change', function()
            {
                update_from_system_input();
            });

            system_input.on('rangechange', function()
            {
                update_range_from_system_input();
            });

            var field = system_input.closest('.field');
            field.on('disabledtoggle', function(e, disabled)
            {
                if (typeof disabled == 'undefined')
                {
                    disabled = field.is('.disabled');
                }
                disabled = !!disabled;
                if (disabled)
                {
                    user_input.datepicker('hide');
                }
            });


            // set input mask

            user_input.attr({
                placeholder: 'dd' + dateSeparator + 'mm' + dateSeparator + 'yyyy',
            });

            new IMask(user_input[0], maskOptions);
        });

    });

    page.on('resizeend', function(event)
    {
        close_datepickers();
    });

});
