//= require imask/dist/imask.js
//= require layout/fields.date.js
//= require layout/fields.time.js
//= require layout/fields.number.js
//= require layout/fields.counter.js
//= require layout/fields.radio.js

var is_native_input_type_supported = function(type)
{
    var key = type + '_input_type_supported';

    if (key in window)
    {
        return window[key];
    }

    var input = document.createElement('input');
    var invalid_value = 'invalid';

    input.setAttribute('type', type);
    input.setAttribute('value', invalid_value);

    window[key] = (input.type === type && input.value != invalid_value);

    return is_native_input_type_supported(type);
};

var getControlValue = function(control)
{
    var value;

    if (control.is(':radio'))
    {
        value = control.closest('.control').find('input:checked').val();
    }
    else if (control.is(':checkbox'))
    {
        value = control.is(':checked');
    }
    else
    {
        value = control.val();
    }

    return value;
};

var getControlInitialValue = function(control)
{
    var value;

    if (control.is(':radio'))
    {
        value = control.closest('.control').find('input[checked]').attr('value');
    }
    else if (control.is('select'))
    {
        var option = control.find('option[selected]');

        // take first available option if no option selected by default
        if (!option.length)
        {
            option = control.find('option:first');
        }

        value = option.attr('value');
    }
    else if (control.is(':checkbox'))
    {
        value = !!control.attr('checked');
    }
    else
    {
        value = control.attr('value');
    }

    return value;
};

var getRemainingCharacterCount = function(input)
{
    var currentLength = input.val().length;
    var maxLength = input.attr('maxlength');

    if (isNaN(maxLength))
    {
        return '';
    }

    var remainingLength = maxLength - currentLength;

    return remainingLength;
};

var entityMap = {
    '&': '&amp;',
    '<': '&lt;',
    '>': '&gt;',
    '"': '&quot;',
    "'": '&#39;',
    '/': '&#x2F;',
    '`': '&#x60;',
    '=': '&#x3D;'
};

var escapeHtml = function(string)
{
    return string.replace(/[&<>"'`=\/]/g, function(s)
    {
        return entityMap[s];
    });
};

(function()
{
    var page = jQuery(document);

    page.on('control:valuecheck', 'input:not([type="radio"]):not([type="checkbox"])', function(event)
    {
        var control = jQuery(event.target);

        control[control.val() ? 'addClass' : 'removeClass']('has-value');
    });

}());
