window.afterInitTable = function () {
    InitResizableGrid('table.resizable-grid', window.getHeightTableHolder(150));
};

$(document).ready(function () {

    $('body').on('click', "#tb_report_type1, #tb_report_type2", InitReportParams);

    $('body').on('change', '#tb_period_type', InitReportParams);

    $('body').on('change', '#tb_fromtoday', ToggleFromToday);

    $('body').on('change', '#tb_fromtodayperiod', ToggleFromTodayPeriod);

    var showparameterform = $('#showparameterform').val();

    if (showparameterform === 'True') {
        loadReportSettings();
    }

    $('#postform').submit(function () {
        window.open('', 'formpopup', 'width=1300,height=800,resizeable,scrollbars');
        this.target = 'formpopup';
    });

});

function ToggleFromToday() {
    $('#tb_fromtodayperiod').prop('checked', $('#tb_fromtoday').prop('checked'));
    $('#startreportdate').prop('disabled', $('#tb_fromtoday').prop('checked'));
    $('#enddate').prop('disabled', $('#tb_fromtoday').prop('checked'));
    if ($('#tb_fromtoday').prop('checked')) {
        var today = $('#today').val();
        $('#enddate').val(today);
        $('#enddate').change();
        $('#startreportdate').val(today);
        $('#startreportdate').change();
    }
}

function ToggleFromTodayPeriod() {
    $('#tb_fromtoday').prop('checked', $('#tb_fromtodayperiod').prop('checked'));
    $('#startreportdate').prop('disabled', $('#tb_fromtodayperiod').prop('checked'));
    $('#enddate').prop('disabled', $('#tb_fromtodayperiod').prop('checked'));
    if ($('#tb_fromtoday').prop('checked')) {
        var today = $('#today').val();
        $('#enddate').val(today);
        $('#enddate').change();
        $('#startreportdate').val(today);
        $('#startreportdate').change();
    }
}

function ajax_download(url, adata, bdata, input_namea, input_nameb) {
    var $iframe,
        iframe_doc,
        iframe_html;

    if (($iframe = $('#download_iframe')).length === 0) {
        $iframe = $("<iframe id='download_iframe'" +
                    " style='display: none' src='about:blank'></iframe>"
                   ).appendTo("body");
    }

    iframe_doc = $iframe[0].contentWindow || $iframe[0].contentDocument;
    if (iframe_doc.document) {
        iframe_doc = iframe_doc.document;
    }

    iframe_html = "<html><head></head><body><form method='POST' action='" +
                  url + "'>" +
                  "<input type=hidden name='" + input_namea + "' value='" +
                  JSON.stringify(adata) + "'/><input type=hidden name='" + input_nameb + "' value='" +
                  JSON.stringify(bdata) + "'/></form>" +
                  "</body></html>";

    iframe_doc.open();
    iframe_doc.write(iframe_html);
    $(iframe_doc).find('form').submit();
}

function InitReportParams() {
    var isType1 = $('#tb_report_type1').is(':checked');
    var isType2 = $('#tb_report_type2').is(':checked');
    var $periodselect = $('#tb_period_type');
    var period = $periodselect.val();
    var $reportType1 = $('#tb_report_type1');

    if (period === 'Period') {
        $('span.period').show();
        $('span.notanyperiod').hide();
        $reportType1.attr('disabled', 'disabled');
        $('#tb_report_type2').attr('checked', true);
    } else {
        var $periodlabel = $('label.period_name');
        var key = '#ReportPeriod_' + period;
        $periodlabel.text($(key).val());
        $('span.period').hide();
        $('span.notanyperiod').show();
        $reportType1.removeAttr('disabled');
    }

    $('#startreportdate').prop('disabled', $('#tb_fromtoday').prop('checked'));
    $('#enddate').prop('disabled', $('#tb_fromtoday').prop('checked'));

    if (isType1) {
        $('select#tb_columns').hide();
        $('select#tb_columns').attr('disabled', 'disabled');
        $('#multiple-indicator input').removeAttr('disabled');
        $('#multiple-indicator').show();
    }
    if (isType2) {

        if (period != 'Period') {
            $('select#tb_columns').show();
            $('select#tb_columns').removeAttr('disabled');
            $('#multiple-indicator').hide();
            $('#multiple-indicator input').attr('disabled', 'disabled');
        } else {
            $('select#tb_columns').hide();
            $('select#tb_columns').attr('disabled', 'disabled');
            $('#multiple-indicator input').removeAttr('disabled');
            $('#multiple-indicator').show();
        }
    }
}

function loadReportSettings() {
    $('#filtercontrol').remove();

    if ($('#reportfilterholder #filter').length > 0) {
        $('#reportfilterholder #filter').remove();
    }
    if ($('#reportfilterholder #columns').length > 0) {
        $('#reportfilterholder #columns').remove();
    }

    if ($('#reportfilterholder #groups').length > 0) {
        $('#reportfilterholder #groups').remove();
    }

    if (tableController() == 'taskreport.ivp/') {
        var urlg = base + tableController() + 'LoadGroup';
        $('#rgroupholder').load(urlg, {
            timestamp: new Date().toString(),
            action: tableAction()
        }, initGroup);
    }

    var urlc = base + tableController() + 'LoadColumns';
    $('#rcolumnsholder').load(urlc,
        {
            timestamp: new Date().toDateString(),
            customPath: true,
            action: tableAction()
        }, function () {
            initColumns();
            InitHint();
            $('#tb_group_field').change(checkForDate);
            $('#reportfilterholder').show();

            //Чистим выпадающие списки
            $('#columncontainer select option[value=""]').remove();
            InitReportParams();

            if ($.fn.calendar) {
                $('#reportfilterholder input.date').change(function () {
                    var $this = $(this);
                    var date = $.parseDate($this.val());
                    if (!date) {
                        $this.attr("date", '');
                        return;
                    }
                    if (date.getHours() == 0 && date.getMinutes() == 0)
                        $this.attr("date", date.print('%Y-%m-%d'));
                    else
                        $this.attr("date", date.print('%Y-%m-%d %H:%M'));
                });
            }

            var url = base + tableController() + 'LoadFilter';
            $('#commonFilter').load(url, {
                timestamp: new Date().toString(),
                action: tableAction()
            }, function () {
                initFilter();
                if ($('#filter form').size()) {
                    $('#filter form').validate({ ignore: '.ignore' });
                }

                if ($('#isSetFilter').length > 0) {
                    $('#isSetCustomFilter').empty();
                    $('#isSetCustomFilter').append(FilterResources.IsFilterSet);
                } else {
                    $('#isSetCustomFilter').empty();
                    $('#isSetCustomFilter').append(FilterResources.IsFilterNotSet);
                }
            });
        });
    return false;
}

function editReportSettings(stateId, isCommonFilter) {
    $('#filtercontrol').remove();

    if ($('#reportfilterholder #filter').length > 0) {
        $('#reportfilterholder #filter').remove();
    }
    if ($('#reportfilterholder #columns').length > 0) {
        $('#reportfilterholder #columns').remove();
    }

    if ($('#reportfilterholder #groups').length > 0) {
        $('#reportfilterholder #groups').remove();
    }
        
    var urlc = base + tableController() + 'EditColumns';
    $('#rcolumnsholder').load(urlc,
        {
            timestamp: new Date().toDateString(),
            customPath: true,
            stateid: stateId
        }, function () {
            initColumns();
            InitHint();
            $('#tb_group_field').change(checkForDate);
            $('#reportfilterholder').show();

            //Чистим выпадающие списки
            $('#columncontainer select option[value=""]').remove();
            InitReportParams();

            if ($.fn.calendar) {
                $('#reportfilterholder input.date').change(function () {
                    var $this = $(this);
                    var date = $.parseDate($this.val());
                    if (!date) {
                        $this.attr("date", '');
                        return;
                    }
                    if (date.getHours() == 0 && date.getMinutes() == 0)
                        $this.attr("date", date.print('%Y-%m-%d'));
                    else
                        $this.attr("date", date.print('%Y-%m-%d %H:%M'));
                });
            }

            var url = base + tableController() + 'EditFilter';
            $('#commonFilter').load(url, { timestamp: new Date().toString(), stateid: stateId, fill: true }, function () {
                initFilter(true);
                if ($('#filter form').size()) {
                    $('#filter form').validate({ ignore: '.ignore' });
                }

                if (isCommonFilter != 'undefined' && isCommonFilter)
                    $('#filter form').append('<input class="hidden" id="commonfilter" name="commonfilter">');

                if ($('#isSetFilter').length > 0) {
                    $('#isSetCustomFilter').empty();
                    $('#isSetCustomFilter').append(FilterResources.IsFilterSet);
                } else {
                    $('#isSetCustomFilter').empty();
                    $('#isSetCustomFilter').append(FilterResources.IsFilterNotSet);
                }
            });
        });
    return false;
}

function InitHint() {
    var $links = $('#multiple-indicator a');
    $links.each(function () {
        var $link = $(this);
        var $parent = $link.parent();
        if ($parent.prop("tagName").toUpperCase() === 'LABEL') {
            $link.insertAfter($parent);
        }
    });
}

function loadCustomReportFilter() {
    $("#mainFilter").hide();

    if ($('#filter').length > 0) { $("#commonFilter").show(); return false; }
    var url = base + tableController() + 'LoadFilter';
    $('#commonFilter').load(url, {
        timestamp: new Date().toString(),
        action: tableAction()
    }, function () {
        initFilter();
        if ($('#filter form').size()) {
            $('#filter form').validate({ ignore: '.ignore' });
        }

        $("#commonFilter").show();
    });
    return false;
}

function applyCommonFilter() {
    $("#isSetCustomFilter").text(ReportResources.IsSetCustomFilter);

    $('#commonFilter').hide();
    $("#mainFilter").show();
}


function applyCustomReportFilter(isExcel) {
    var paramsf = $('#rcolumnsholder form [isdate!=1]').serializeArray(true);
    var dates = [];
    $('#rcolumnsholder form input[date]').each(function () {
        var date = { name: $(this).attr('name'), value: $(this).attr('date') };
        dates[dates.length] = date;
    });
    paramsf = $.merge(paramsf, dates);

    var paramsg = $('#groups form').serializeArray();
    var params = new Array();
    params = paramsf.concat(paramsg);
    var orderby = '';
    $('select.orderby option:selected').each(function (i, el) { if (el.value) orderby += ((orderby.length > 0) ? ',' : '') + el.value; });

    params[params.length] = { name: 'tb_orderby', value: orderby };
    params[params.length] = { name: 'tb_stateid', value: '' };
    params[params.length] = { name: 'timestamp', value: new Date().toString() };
    params[params.length] = { name: 'nolayout', value: true };
    params[params.length] = { name: 'rebuild', value: true };
    params[params.length] = { name: 'generateReport', value: true };

    if ($('#savefrompopup').is(':checked')) {
        params[params.length] = { name: 'savefrompopup', value: true };
        params[params.length] = { name: 'sfpfiltername', value: $('#sfpfiltername').val() };
        params[params.length] = { name: 'sfpfilterwascommon', value: $('#sfpfilterwascommon').val() };
    }

    $('div.multipleselectpopup').hide();
    $('#reportfilterholder').hide(); $('ul.filterlist li.selected').removeClass('selected');
    $('#showfilter').addClass('enabled');
    enableSaveAndClear();

    var url = tableUrl();

    if (isExcel != undefined && isExcel) {
        url = tableController() + 'excel';
        $.download(url, params);
    } else {
        var reloadFilters = $("#savefrompopup").is(":checked");
        $(tableRootDiv).load(url, params, function () {
            initTable();
            if ($("#filter-sticker").length)
                setContextSize();
            if (reloadFilters) loadSavedStates();
        });
    }    

    return false;
}

function getReportDetalization(obj) {
    var parent = $(obj).parent();
    var input = $(parent).find(".ids");

    var ids = "";
    if ($(input).attr('path') != undefined) {
        var objs = $(".ids[path^='" + $(input).attr('path') + "']");
        var col = $(input).attr('i');

        $(objs).each(function (i, el) {
            if ($(el).attr('i') == col)
                ids += $(el).val() + ",";
        });

    } else {
        ids += $(input).val();
    }

    var form = $('#postform').empty();
    form.append('<input type="hidden" name="reset" value="true"/>');
    form.append('<input type="hidden" name="tb_taskIds" value="' + ids + '"/>');
    form.append('<input type="hidden" name="tb_serviceid" value="0"/>');

    form.submit();

    return false;
}
