/* Check a value wheather is empty */
function isEmptyValue(val)
{
    return val === null || val === undefined || (typeof val === 'string' && !val.trim().length);
}

/* Validate method settings data */
function validateFormData(data, $form)
{
    var hasError = false;
    $form.find('.helper-text').remove();
    $.each(methodSettings, function(name, setting)
    {
        if($form.find('tr[data-name="' + name + '"]').is(':hidden')) return;

        var $control = $('#' + name);
        if(!$control.length) return;

        $($control).closest('td').find('.help-text').remove();

        var isList  = setting.type === 'list';
        var value   = $control.val();
        if(isList && $control.is('.checkbox-list,.checkbox-group'))
        {
            value = $control.find('input:checked').map(function(){return this.value}).get();
        }

        var isEnum = setting.type === 'enum';
        if(isEnum && $control.is('.radio-list,.radio-group'))
        {
            value = $control.find('input:checked').map(function(){return this.value}).get()[0];
        }

        var isEmpty = isList ? (!value || !value.length) : isEmptyValue(value);
        var $label = $('#' + name + 'Label');
        if(setting.required && isEmpty)
        {
            if($label.length) $label.remove();
            $label = '<div id="' + name + 'Label" class="text-danger help-text">' + validMsg.required.replace('%s', setting.label) + '</div>';
            $control.closest('td').append($label);
            hasError = true;
            return false;
        }

        if(!isEmpty && setting.type === 'number')
        {
            if(!/^(-?\d+)(\.\d+)?$/.test(value))
            {
                if($label.length) $label.remove();
                $label = '<div id="' + name + 'Label" class="text-danger help-text">' + validMsg.numberType.replace('%s', setting.label) + '</div>';
                $control.closest('td').append($label);
                hasError = true;
                return false;
            }

            if((!isNaN(setting.min) && parseFloat(value) <= setting.min) || (!isNaN(setting.max) && parseFloat(value) >= setting.max))
            {
                if($label.length) $label.remove();
                var error = validMsg.numberRange.replace(/%s/, setting.label);
                if(!isNaN(setting.min) && !isNaN(setting.max))
                {
                    error = error.replace(/%s/, setting.min + ' < ').replace(/%s/, ' < ' + setting.max);
                }
                else if(!isNaN(setting.min))
                {
                    error = error.replace(/%s/, '').replace(/%s/, ' ≥ ' + setting.min);
                }
                else
                {
                    error = error.replace(/%s/, '').replace(/%s/, ' ≤ ' + setting.max);
                }
                $label = '<div id="' + name + 'Label" class="text-danger help-text">' + (setting.error || error) + '</div>';
                $control.closest('td').append($label);
                hasError = true;
                return false;
            }

            if(setting.gt)
            {
                var gtValue = $('#' + setting.gt).val();
                var s1      = setting.label;
                var s2      = methodSettings[setting.gt].label;
                if(parseInt(value) < parseInt(gtValue))
                {
                    if($label.length) $label.remove();
                    $label = '<div id="' + name + 'Label" class="text-danger help-text">' + validMsg.gtError.replace('%s1', s1).replace('%s2', s2) + '</div>';
                    $control.closest('td').append($label);
                    hasError = true;
                    return false;
                }
            }
        }

        if(!isEmpty && setting.type == 'list' && setting.listType == 'number')
        {
            var values = value.split(',');
            for(var i = 0; i < values.length; i++)
            {
                var numStr = values[i].trim();
                if(!/^(-?\d+)(\.\d+)?$/.test(numStr))
                {
                    if($label.length) $label.remove();
                    $label = '<div id="' + name + 'Label" class="text-danger help-text">' + setting.error || validMsg.numberType.replace('%s', setting.label) + '</div>';
                    $control.closest('td').append($label);
                    hasError = true;
                    return false;
                }

                if(setting.pattern && !new RegExp(eval(setting.pattern)).test(numStr))
                {
                    if($label.length) $label.remove();
                    $label = '<div id="' + name + 'Label" class="text-danger help-text">' + setting.error || validMsg.numberType.replace('%s', setting.label) + '</div>';
                    $control.closest('td').append($label);
                    hasError = true;
                    return false;
                }
            }
        }
        else if(!isEmpty)
        {
            if(setting.pattern && !new RegExp(eval(setting.pattern)).test(value))
            {
                if($label.length) $label.remove();
                $label = '<div id="' + name + 'Label" class="text-danger help-text">' + setting.error || validMsg.numberType.replace('%s', setting.label) + '</div>';
                $control.closest('td').append($label);
                hasError = true;
                return false;
            }
        }
    });
    if(hasError) return false;
}

/** Check method settings condition */
function checkSettingsConditions($form)
{
    if(!window.methodSettings) return;

    $form = $form || $('#dataform');
    var formData = {};
    $form.serializeArray().forEach(function(item)
    {
        var oldValue = formData[item.name];
        if(Array.isArray(oldValue))     oldValue.push(item.value);
        else if(oldValue !== undefined) formData[item.name] = [oldValue, item.value];
        else formData[item.name] = item.value;
    });

    $.each(methodSettings, function(name, setting)
    {
        var conditions = setting.conditions;
        if(!conditions) return;
        if(!Array.isArray(conditions)) conditions = [conditions];
        var isMatch = false;
        for(var i = 0; i < conditions.length; ++i)
        {
            var condition      = conditions[i];
            var conditionMatch = true;
            $.each(condition, function(name, value)
            {
                var currentValue = formData[name];
                if(currentValue !== value && JSON.stringify(currentValue) !== JSON.stringify(value))
                {
                    conditionMatch = false;
                    return false;
                }
            });
            if(conditionMatch)
            {
                isMatch = true;
                break;
            }
        }
        $form.find('tr[data-name="' + name +  '"]').toggle(isMatch);
    });
}

$(function()
{
    if(window.methodSettings)
    {
        var $form = $('#dataform');
        if(window.validMsg && $form.length && !$form.data('zui.ajaxform'))
        {
            $form.ajaxForm({beforeSubmit: validateFormData});
            $form.on('change', function(event)
            {
                $(event.target).closest('td').find('.help-text').remove();
                checkSettingsConditions($form);
            });
        }
        checkSettingsConditions($form);
    }

  var bodyHeight = $(window.parent).height();
  var modalMaxHeight = bodyHeight - 200;

  $('#dataform .table-settings').css('max-height', modalMaxHeight + 'px');


    $(document).on('click', "#collapse", function (event)
    {
        if($(".more-label").find('i').hasClass('icon-expand'))
        {
            $(".more-label").find('i').removeClass('icon-expand');
            $(".more-label").find('i').addClass('icon-collapse');
            $('#collapseMore').css('display', '');
        }
        else
        {
            $(".more-label").find('i').removeClass('icon-collapse');
            $(".more-label").find('i').addClass('icon-expand');
            $('#collapseMore').css('display', 'none');
        }
    });
});
