$(document).ready(function () {
    if ($("#nodata").length <= 0) {
        inittable();
        $('body').on('jsp-scroll-x', '#scrollerclone', function() {
            var clonePositionLeft = $('div.jspPane').css('left');
            $('div#tablescroller').css('left', clonePositionLeft);
        });
        $(window).bind("resize", function() {
            setScrollWidth($('#tableh').width() - $('td#fixedblock').width());
            $('#floatingblock').width($('#tableh').width());
            $('div#scrollerclone').data('jsp').scrollTo(0,0);
        });
        if ($.browser.msie) {
            $('#tableh').css('margin-top', '22px');
            $('#floatingblock').find('#fixedblock').width($('#tableh').find('#fixedblock').width());
        }
    }

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

function inittable() {
    $('div#scroller').width($('div#tableh').width() - $('td#fixedblock').width());
    $('div#scrollerclone').width($('div#tableh').width() - $('td#fixedblock').width());
    $('tbody#fixedcols tr').each(function() {
        var rowid = $(this).attr("rowid");
        var maxheight = 0;
        $('td[rowid=' + rowid + ']').each(function() {
            if ($(this).height() > maxheight) maxheight = $(this).height();
        });
        $('td[rowid=' + rowid + ']').each(function() {
            $(this).height(maxheight + 11);
        });
    });
    showHeader();
    var $bar = $('div.jspHorizontalBar');
    $bar.css("position", "relative").css("z-index", "2");
    //плавающие заголовок таблицы и прокрутка
    $('#floatingblock').css('top', '0px');
}

function showHeader() {
    $('#floatingblock').width($('#tableh').width());
    
    $('#scrollerclone').jScrollPane();
    $('div.jspDrag').append('<img class="scroll-icon" src="img/scroll-icon.png"/>');
    if (!$.browser.safari) {
        setScrollWidth($('#tableh').width() - $('td#fixedblock').width());
    }
    $('.jspPane').css('width', '100%');
    $('.jspVerticalBar').remove();
    if ($.browser.safari)
    { $('.jspDrag').width($('.jspDrag').width() - 2); }
}

function setScrollWidth(width) {
    $('div#scrollerclone').width(width);
    $('div#scroller').width(width);
    $('div.jspContainer').width(width);
    $('div#scrollerclone').data('jsp').ReinitScrollerH(width);
    $('.jspPane').css('width', '100%');
}

function expandTaskGroup(link) {
    var $link = $(link);
    $link.parents('table:first').css('width', '100%');
    var $tr = $link.parents('tr[data-group-key]:first');
    var groupKey = $tr.attr('data-group-key');
        
    var $groupTrFixed = $("#fixedblock table").find('tr[data-group-key="' + groupKey + '"]').not(".group-title");
    var $groupTrVariable = $("#variableblock table").find('tr[data-group-key="' + groupKey + '"]').not(".group-title");

    $groupTrFixed.toggle();
    $groupTrVariable.toggle();

    var newHeight = $('#fixedblock').height();

    $('#scrollerclone').animate({
        height: newHeight
    }, 100);

    $('.jspContainer').animate({
        height: newHeight
    }, 100);

    var $img = $(link).find('img');
    if ($img.attr('src') == 'img/tree/minus.gif')
        $img.attr('src', 'img/tree/plus.gif');
    else
        $img.attr('src', 'img/tree/minus.gif');
    return false;
}

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

    var paramsc = $('#columns form').serializeArray();
    var params = new Array();
    params = paramsf.concat(paramsc);
    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();
            setContextSize();
            inittable();
            if (reloadFilters) loadSavedStates();
        });
    }

    return false;
}

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();

        InitReportParams();        
    });
    return false;
}

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

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

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_fromtodayperiod').prop('checked')) {
        var today = $('#today').val();
        $('#enddate').val(today);
        $('#enddate').change();
        $('#startreportdate').val(today);
        $('#startreportdate').change();
    }
}

function InitReportParams() {        
    $('#enddate').prop('disabled', $('#tb_fromtoday').prop('checked'));    
}

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();
    }    

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

        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 ($('#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();
        $('#tb_group_field').change(checkForDate);
        $('#reportfilterholder').show();

        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;
}