function validateConditionData(datas, $form)
{
    var hasError   = false;
    var checkEmpty = ['value', 'then', 'otherwise'];
    var varLimit   = {'min': -99999, 'max': 99999};

    datas.forEach(function(data)
    {
        var input = $('input[name="' + data.name + '"]');
        input.parent().parent().find('.help-text').remove();

        var label = $('#' + data.name + 'Label');
        if(label.length) label.remove();

        var labelName = data.name;
        if(data.name.indexOf('val') !== -1) labelName = 'value';


        /* Validate required */
        var shouldCheck = false;
        checkEmpty.forEach(function(field) { if(labelName == field) shouldCheck = true; });

        if(shouldCheck && isEmptyValue(data.value))
        {
            hasError  = true;
            var name  = conditionCheck[labelName];
            var label = '<div id="' + labelName + 'Label" class="text-danger help-text">' + validMsg.required.replace('%s', name) + '</div>';
            /* Then and otherwise should use parent.parent. */
            labelName == 'value' ? input.parent().append(label) : input.parent().parent().append(label);
            return false;
        }

        /* Validate rule if has no error. */
        if(!hasError)
        {
            if(labelName == 'value')
            {
                if(isNaN(data.value))
                {
                    hasError  = true;
                    var name  = conditionCheck[labelName];
                    var label = '<div id="' + labelName + '" class="text-danger help-text">' + validMsg.number.replace('%s', name) + '</div>';
                    input.parent().append(label);
                    return false;
                }

                if(Number(data.value) < Number(varLimit.min) || Number(data.value) > Number(varLimit.max))
                {
                    hasError   = true;
                    var name   = conditionCheck[labelName];
                    limitError = validMsg.limit.replace('%s', varLimit.min).replace('%s', name).replace('%s', varLimit.max);
                    var label  = '<div id="' + labelName + 'Label" class="text-danger help-text">' + limitError + '<div>';
                    input.parent().append(label);
                    return false;
                }
            }
            else if(labelName == 'then' || labelName == 'otherwise')
            {
                parent.getFormData();
                var formData = parent.formData;
                var execStr  = '';
                var vars     = [];

                formData.hypo.forEach(function(item) { vars.push('var ' + item.variable + ' = 1;'); });
                formData.forecast.forEach(function(item) { vars.push('var ' + item.variable + ' = 1;'); });
                if(formData.decisionStus == 'true') formData.decision.forEach(function(item) { vars.push('var ' + item.variable + ' = 1;'); });

                try
                {
                    eval(vars.join('') + parent.replaceFunc(data.value));
                }
                catch(e)
                {
                    hasError  = true;
                    var name  = conditionCheck[labelName];
                    var label = '<div id="' + labelName + '" class="text-danger help-text">' + validMsg.formula.replace('%s', name) + '</div>';
                    input.parent().parent().append(label);
                    return false;
                }

            }
        }
    });

    if(hasError) return false;
}

function addCondition(obj)
{
    var tml = $("#conditionTpl").html();

    var data = {};
    data.i = rowIndex + 1;

    var html   = $($.zui.formatString(tml, data));
    var picker = html.find('.picker');
    picker.picker();

    var objID     = $(obj).attr('data-id');
    var hypo      = $('#hypoList' + objID).val();
    var condition = $('#condition' + objID).val();
    var val       = $('input[id^="val[' + objID + ']"]').val() == undefined ? '' : $('input[id^="val[' + objID + ']"]').val();
    html.find('#hypoList' + data.i).data('zui.picker').setValue(hypo);
    html.find('#condition' + data.i).data('zui.picker').setValue(condition);
    html.find('input[id^="val"]').attr('value', val);

    $(obj).closest('tr').after(html);
    rowIndex++;
}

function deleteCondition(obj)
{
    if($(obj).hasClass('disable')) return;
    $(obj).closest('tr').remove();
}

$(function()
{
    $('.picker').picker();

    var $form = $('#condition');
    if(window.validMsg && $form.length)
    {
        $form.ajaxForm({beforeSubmit: validateConditionData});
        $form.on('change', function(event)
        {
            $(event.target).parent().find('.help-text').remove();
        });
    }
});
