// This file is included multiple times, so we've wrapped it in a C-style include guard
if (window.form_was_initialised === undefined) {
    window.form_was_initialised = true;

    function concat() {
        var args = '';
        for (var n = 0; n < arguments.length; n++) {
            args += arguments[n];
        }
        return args;
    }

    /**
     * Thus function takes a value and rounds it to the given number of
     * decimal places. It is used to implement the "round" function in
     * IC expressions.
     *
     * @param {(string|number)} value_to_round
     * @param {number} decimal_places
     * @return {number}
     */
    function round(value_to_round, decimal_places) {
        value_to_round = parseFloat(value_to_round) || 0;
        decimal_places = parseInt(decimal_places) || 0;

        if (decimal_places < 0)
            decimal_places = 0;

        var prec = Math.pow(10, decimal_places);

        // "This looks too complicated"
        // Be quiet, you'll thank me later. Floating point numbers are hard.
        // We don't use toFixed because we want an actual number
        // We use Number.EPSILON to take care of rounding errors
        // from previous calculations
        //
        // "Everything should be made as simple as possible, but no simpler"
        // -- Albert Einstein
        return Math.round((value_to_round + Number.EPSILON) * prec) / prec;
    }

    /**
     * This function should never be called.
     * Expression validation should prevent an invalid function from being called, but if it is
     * we display an error for the benefit of the developer
     *
     * @param {string} function_name name of the invalid function that was called, if known
     */
    function ic_dummy(function_name) {
        if (!function_name)
            console.error("InfoCapture dummy function called. This is probably a bug in the Claromentis application.");
        else
            console.error("Unsupported function \"" + function_name + "\" called. An entry may need to be added in the JSGeneratorVisitor");

        return '';
    }

    function get_field_label(prefix, id, type) {
        var f, e, l;
        if ((type >= document.cla_forms.field_types.TYPE_SHORT_STRING && type <= document.cla_forms.field_types.TYPE_LONG_TEXT) ||
            (type == document.cla_forms.field_types.TYPE_BBCODE_TEXT)) {
            f = document.getElementById(prefix + '_field_' + id);
            if (!f)
                return '';
            return f.value;
        }
        if (type == document.cla_forms.field_types.TYPE_CHECKBOX) {
            f = document.getElementById(prefix + '_field_' + id);
            if (!f)
                return '';
            return (f.checked ? document.cla_forms.lmsg['yes'] : document.cla_forms.lmsg['no']);
        }
        if (type == document.cla_forms.field_types.TYPE_RADIO) {
            for (var i = 0; i < 1000; i++) {
                e = document.getElementById(prefix + '_field_' + id + '_' + i);
                if (!e)
                    break;
                if (e.checked) {
                    l = document.getElementById(prefix + '_field_label_' + id + '_' + i);
                    if (!l)
                        return '';
                    return jQuery(l).text().trim();
                }
            }
            return 'not selected';
        }
        if (type == document.cla_forms.field_types.TYPE_SELECT || type == document.cla_forms.field_types.TYPE_USERLIST) {
            e = document.getElementById(prefix + '_field_' + id);
            if (!e)
                return '';
            if (typeof (e.selectedIndex) != 'undefined')
                return e.options[e.selectedIndex].text;
            return e.options[0].text;
            //from popup
        }
        if (type == document.cla_forms.field_types.TYPE_DATE) {
            var day, month, year;
            e = document.getElementById(prefix + '_field_' + id + '_day');
            if (!e)
                return '';
            day = e.options[e.selectedIndex].value;
            e   = document.getElementById(prefix + '_field_' + id + '_month');
            if (!e)
                return '';
            month = e.options[e.selectedIndex].value;
            e     = document.getElementById(prefix + '_field_' + id + '_year');
            if (!e)
                return '';
            year = e.options[e.selectedIndex].value;
            return moment(year + '-' + month + '-' + day).format(cla_locale.date_format);
        }
        return 'not supported';
    }

    function get_timestamp_date(prefix, id, type) {
        var e, d, day, month, year;
        if (type == document.cla_forms.field_types.TYPE_DATE) {
            e = document.getElementById(prefix + '_field_' + id + '_day');
            if (!e)
                return '';
            day = parseInt(e.options[e.selectedIndex].value);
            e   = document.getElementById(prefix + '_field_' + id + '_month');
            if (!e)
                return '';
            month = parseInt(e.options[e.selectedIndex].value);
            e     = document.getElementById(prefix + '_field_' + id + '_year');
            if (!e)
                return '';
            year = parseInt(e.options[e.selectedIndex].value);
        } else if (type == document.cla_forms.field_types.TYPE_SHORT_STRING) {
            e = document.getElementById(prefix + '_field_' + id);
            if (!e)
                return '';
            d = parse_date_to_object(e.value);
            if (!d)
                return '';
            day   = d.getDate();
            month = d.getMonth() + 1;
            year  = d.getFullYear();
            if (d.getHours() > 0 || d.getMinutes() > 0 || d.getSeconds() > 0) {
                return '';
            }
        } else {
            return '';
        }
        if (day === 0 || month === 0 || year === 0)
            return 0;

        var pad = function (num, len) {
            var pad = '0000';
            return (pad + num).slice(-len);
        };
        return pad(year, 4) + pad(month, 2) + pad(day, 2);
    }

    function get_field_value(prefix, id, type, format) {
        format = format || 0;
        var f, i, e;
        // Be careful! Timestamps for both dates' types are processed without calling this function

        if ((type >= document.cla_forms.field_types.TYPE_SHORT_STRING && type <= document.cla_forms.field_types.TYPE_LONG_TEXT) ||
            (type == document.cla_forms.field_types.TYPE_BBCODE_TEXT) || (type == document.cla_forms.field_types.TYPE_FINANCIAL)) {
            f = document.getElementById(prefix + '_field_' + id);
            if (!f)
                return '';

            if (format === document.cla_forms.string_formats.STRING_FORMAT_NUMERIC)
                return parseInt(f.value) || 0;

            if (format === document.cla_forms.string_formats.STRING_FORMAT_FLOAT)
                return parseFloat(f.value) || 0;

            return f.value;
        }

        if (type == document.cla_forms.field_types.TYPE_CHECKBOX) {
            f = document.getElementById(prefix + '_field_' + id);
            if (!f)
                return '';
            return (f.checked ? 1 : 0);
        }
        if (type == document.cla_forms.field_types.TYPE_RADIO) {
            for (i = 0; i < 1000; i++) {
                e = document.getElementById(prefix + '_field_' + id + '_' + i);
                if (!e)
                    break;
                if (e.checked) {
                    return e.value;
                }
            }
            return '';
        }
        if (type == document.cla_forms.field_types.TYPE_SELECT || type == document.cla_forms.field_types.TYPE_USERLIST) {
            e = document.getElementById(prefix + '_field_' + id);
            if (!e)
                return '';
            if (typeof (e.selectedIndex) != 'undefined')
                return e.options[e.selectedIndex].value;
            return e.options[0].value;
            //from popup
        }
        return '';
    }

    function get_form_values(form) {
        if (typeof (CKEDITOR) === 'object') {
            var instances = CKEDITOR.instances;
            for (var ck in instances) {
                CKEDITOR.instances[ck].updateElement();
            }
        }

        return xajax.getFormValues(form);
    }

    function remove_old_popup_div(id) {
        var el_div = $(document.body).getElements("div#pg_main_div_" + id);
        el_div.each(function (el) {
            if (el.getParent('body'))
                el.remove();
        });
    }

    function xjx_reload(form, type, project_id, field_sym_name) {
        if (!window.fck_ready || !window.dom_ready)
            return false;

        if (type == document.cla_forms.field_types.TYPE_DATE)//Date type
        {
            // _518__field_birth_date_day
            var el_id    = "_" + project_id + "__field_" + field_sym_name;
            var el_day   = jq_$(el_id + "_day");
            var el_month = jq_$(el_id + "_month");
            var el_year  = jq_$(el_id + "_year");
            if (!el_day.prop('selectedIndex') || !el_month.prop('selectedIndex') || !el_year.prop('selectedIndex'))
                return false;
        }

        var scrollTop = $(document).scrollTop();
        $("input[name='last_scroll_position_y']").val(scrollTop);

        // double setTimeout so that it runs after field validation, which is in a setTimeout
        setTimeout(function() {
            setTimeout(function(){
                $('html').trigger({
                    type: "before-form-reload",
                    form: $("#" + form)
                });

                xajax_reload_form(get_form_values(form));
            });
        }, 0);
    }

    function remove_ck_editors() {
        jQuery('.ic_wysiwyg_field').each(function (idx, textarea) {
            if (typeof (CKEDITOR.instances[textarea.id]) != 'undefined')
                CKEDITOR.instances[textarea.id].destroy();
        });
    }

    function remove_dynamic_listeners() {
        jQuery('#issue_form_div .dynamic_field').prop('onchange', null);
        jQuery('#issue_form_div .dynamic_field').prop('onclick', null);
    }

    function checkFck() {
        if (jQuery('.ic_wysiwyg_field').size() == 0)
            window.fck_ready = true;
        else if (typeof (CKEDITOR) !== 'undefined') {
            // CKE instance for Infocapture
            jQuery('.ic_wysiwyg_field:visible').each(function (idx, textarea) {
                CKEDITOR.replace(textarea.id, { "customConfig": "/intranet/common/ckeditor/editor_config.php?application=ic_field" });
            });
            window.fck_ready = true;
        }
    }

    function FCKeditor_OnComplete() {
        window.fck_ready = true;
    }

    function getFormsValuesForXajax(frm) {
        var objForm;

        if (typeof (frm) == "string")
            objForm = jQuery('#' + frm);
        else
            objForm = frm;
        var sXml = "<xjxquery><q>";
        if (objForm && objForm.get(0).nodeName.toLowerCase() == 'form') {
            var formElements = jQuery('#' + frm + ' :input');
            for (var i = 0; i < formElements.length; i++) {
                if (!formElements[i].name)
                    continue;
                if (formElements[i].type && formElements[i].type == 'radio' && formElements[i].checked === false)
                    continue;
                if (formElements[i].disabled && formElements[i].disabled === true)
                    continue;
                var name = formElements[i].name;
                if (name) {
                    if (sXml != '<xjxquery><q>')
                        sXml += '&';
                    if (formElements[i].type == 'select-multiple') {
                        for (var j = 0; j < formElements[i].length; j++) {
                            if (formElements[i].options[j].selected === true)
                                sXml += name + "=" + encodeURIComponent(formElements[i].options[j].value) + "&";
                        }
                    } else if (formElements[i].type == 'checkbox') {
                        sXml += name + "=" + (formElements[i].checked ? "1" : "0");
                    } else {
                        sXml += name + "=" + encodeURIComponent(formElements[i].value);
                    }
                }
            }
        }
        sXml += "</q></xjxquery>";
        return sXml;
    }

    function enable_file_remove_button() {
        // File upload fields have a button to remove the current file if not mandatory
        // There doesn't seem to be a good place to put per-field JS code like this
        jQuery('#issue_form').on('click', '.js-rmv-file', function (e) {
            e.preventDefault();
            jQuery(this).siblings('.js-file_upload').val('');
            return false;
        })
    }

    jQuery(function () {
        checkFck();
        enable_file_remove_button();
        window.dom_ready = true;
    });
}
