var gaugesstack = [];
var gaugesselector = $('#gauges').val();
var params = [];

$(function () {
    if (Number($('#defpersswitch').val()) == 1) {
        $("#personalgaugesettings").click();
    } else {
        $("#defaultgaugesettings").click();
    }

    filterToggle();

    toggleDefaultPersonal();
    toggleFilterControls();

    $("#gaugeselector").bind('change', function () {
        setupGauge($("#gaugeselector").val());
    });

    $("#defaultgaugeselector").bind('change', function () {
        setupGauge($("#defaultgaugeselector").val());
    });

    $(".settingsswitch").change(function () {
        reinitDefaultPersonal();
    });

    $('#gaugesetup').validate({
        errorPlacement: function (error, element) {
            error.appendTo($('#errorplace'));
        },
        rules: {
            setupgaugeticks: {
                digits: true,
                max: 40
            },
            setupgaugetargetvalue: {
                required: true,
                number: true
            },
            setupgaugesuffix: {
                maxlength: 5
            },
            setupgaugegreenrangestart: {
                required: true,
                number: true
            },
            setupgaugegreenrangeend: {
                required: true,
                number: true
            },
            setupgaugeyellowrangestart: {
                required: true,
                number: true
            },
            setupgaugeyelloerangeend: {
                required: true,
                number: true
            },
            setupgaugeredrangestart: {
                required: true,
                number: true
            },
            setupgaugeredrangeend: {
                required: true,
                number: true
            }
        }
    });

    //$('#filter').load('gauge.ivp/loadfilter', function () { initGaugeFilter(); });
});

function toggleDefaultPersonal() {
    $(defpersswitch).val(Number($("input[name='gst']:checked").val()));

    if (Number($(defpersswitch).val()) > 0) {
        $("#gaugeselector").removeClass("hidden");
        $("#defaultgaugeselector").addClass("hidden");
    } else {
        $("#defaultgaugeselector").removeClass("hidden");
        $("#gaugeselector").addClass("hidden");
    }

    if (Number($('#defpersswitch').val()) == 1) {

        settingsForbidden(false);

        if (Number($("#personalscount").val()) > 0) {
            $("#showsettings").show();
            $("#createpersonals").hide();
            $("#deletegauge").removeClass("hidden");
        } else {
            $("#showsettings").hide();
            $("#createpersonals").show();
            $("#deletegauge").addClass("hidden");
        }
    } else {
        $("#createpersonals").hide();
        if (Number($("#primegauges").val()) == 1) {
            $("#showsettings").show();
            settingsForbidden(false);
        } else {
            settingsForbidden(true);
        }
        if (Number($('#personalscount').val() > 0)) {
            $("#deletegauge").removeClass("hidden");
        } else {
            $("#deletegauge").addClass("hidden");
        }
    }

    if (Number($("#defpersswitch").val()) == 1 | Number($("#primegauges").val()) == 1) {
        settingsForbidden(false);
    } else {
        settingsForbidden(true);
    }
}

function settingsForbidden(condition) {
    $("#setupgaugeticks").prop("disabled", condition);
    $("#setupgaugetargetvalue").prop("disabled", condition);
    $("#setupgaugemaxvalue").prop("disabled", condition);
    $("#setupgaugesuffix").prop("disabled", condition);
    $("#setupgaugegreenrangestart").prop("disabled", condition);
    $("#setupgaugegreenrangeend").prop("disabled", condition);
    $("#setupgaugeyellowrangestart").prop("disabled", condition);
    $("#setupgaugeyellowrangeend").prop("disabled", condition);
    $("#setupgaugeredrangestart").prop("disabled", condition);
    $("#setupgaugeredrangeend").prop("disabled", condition);
    $("#savegaugesettings").prop("disabled", condition);
    if (condition) {
        $("#nopermissiondefaultgauges").removeClass("hidden");
    } else {
        $("#nopermissiondefaultgauges").addClass("hidden");
    }

}

function reinitDefaultPersonal() {
    toggleDefaultPersonal();

    initializeGauges();
}

function toggleGaugesVisibility() {
    if ($('#gaugesvisible').val() == 0) {
        initializeGauges();
        $('#gaugeswrapper').removeClass("hidden");
        $('#gaugesvisible').val(1);
        $('#gaugesswitch').addClass("hidden");
    } else {
        $('#gaugeswrapper').addClass("hidden");
        $('#gaugesvisible').val(0);
        $('#gaugesswitch').removeClass("hidden");
    }
    return false;
}

function setupGauge(gid) {
    var defpersswitch = Number($("#defpersswitch").val());
    if (gid > 0) {
        $.getJSON(base + "gauge.ivp/setupgauge", { gid: gid, defpersswitch: defpersswitch }, function (data) {
            $('#setupgaugename').val(data.Data.Name);
            $('#setupgaugeaction').val(data.Data.Action);
            $('#setupgaugeticks').val(data.Data.Ticks);
            $('#setupgaugetargetvalue').val(data.Data.TargetValue);
            $('#setupgaugemaxvalue').val(data.Data.MaxValue);
            $('#setupgaugesuffix').val(data.Data.Suffix);
            $('#setupgaugegreenrangestart').val(data.Data.GreenRangeStart);
            $('#setupgaugegreenrangeend').val(data.Data.GreenRangeEnd);
            $('#setupgaugeyellowrangestart').val(data.Data.YellowRangeStart);
            $('#setupgaugeyellowrangeend').val(data.Data.YellowRangeEnd);
            $('#setupgaugeredrangestart').val(data.Data.RedRangeStart);
            $('#setupgaugeredrangeend').val(data.Data.RedRangeEnd);
            if (data.Data.ShowOnDashBoard) {
                $('#setupgaugeshowondashboard').attr('checked', true);
            } else {
                $('#setupgaugeshowondashboard').attr('checked', false);
            }
            $('#setupgaugeshoworder').attr('checked', data.Data.ShowOrder);
        });
    } else {
        cleanGaugeSettings();
    }
}

function cleanGaugeSettings() {
    $('#gaugeselector').val(0);
    $('#defaultgaugeselector').val(0);
    $('#setupgaugename').val("");
    $('#setupgaugeaction').val("");
    $('#setupgaugeticks').val("");
    $('#setupgaugetargetvalue').val("");
    $('#setupgaugemaxvalue').val("");
    $('#setupgaugesuffix').val("");
    $('#setupgaugegreenrangestart').val("");
    $('#setupgaugegreenrangeend').val("");
    $('#setupgaugeyellowrangestart').val("");
    $('#setupgaugeyellowrangeend').val("");
    $('#setupgaugeredrangestart').val("");
    $('#setupgaugeredrangeend').val("");
    $('#setupgaugeshowondashboard').attr('checked', false);
    $('#setupgaugeshoworder').attr('checked', false);
}

function createPersonalGauges() {
    $.post(base + "gauge.ivp/createpersonalgauges");
    $("#personalscount").val(1);
    toggleDefaultPersonal();
    updateSelector();
}

function setupGaugeAJAXForm() {

    $('#commonFilter').hide();
    $('#settingsbody').show();
    $('#settingscontrols').show();
    $('#savegaugesettings').show();
    $('#abandongaugesettings').show();

    var $dialogContainer = $('#gaugesetup');
    var $detachedChildren = $dialogContainer.children().detach();

    $dialogContainer.dialog({ width: 360, position: { my: "left top", at: "left bottom", of: $("#gauge_setup") }, resizable: false, open: function () { $detachedChildren.appendTo($dialogContainer); } });
}

function closeGaugeAJAXForm() {
    cleanGaugeSettings();
    $('#commonFilter').hide();
    $('#settingsbody').show();
    $('#gaugesetup').dialog("close");
    return false;
}

function closeGaugeFilterForm() {
    $('#commonFilter').hide();
    $('#gaugesetup').dialog({ width: 360 });
    $('#settingsbody').show();
    $('#settingscontrols').show();
    $('#savegaugesettings').show();
    $('#abandongaugesettings').show();
    return false;
}

function deleteFilter() {
    $.post(base + "gauge.ivp/deletefilter");
    $(".checklist input:checked").click();
    $(".flttype").val(0);
    $(".fltdate").val(null);
    $(".fltdate").datepicker("setDate", null);
    $(".numeric").val(null);
    $(".flttext").val(null);
    $(".manualfilter").val(null);
    $('#isfilterset').val(0);
    toggleFilterControls();
}

function showGaugeFilterForm() {
    $('#settingsbody').hide();
    $('#gaugesetup').dialog({ width: 740 });
    $('#commonFilter').show();
    $('#settingscontrols').hide();
    $('#savegaugesettings').hide();
    $('#abandongaugesettings').hide();
    $('#filter').load('gauge.ivp/loadfilter', function () { initGaugeFilter(); });

    return false;
}

function initializeGauges() {
    var viewreports = Number($("#viewreports").val());
    if (viewreports == 1) {
        gaugesstack = [];
        var defpersswitch = Number($("#defpersswitch").val());
        var personalscount = Number($("#personalscount").val());

        var nopersshowglob = defpersswitch == 1 && personalscount == 0 ? 1 : 0;

        $.getJSON(base + 'gauge.ivp/getgaugesjson', { defpersswitch: defpersswitch, nopersshowglob: nopersshowglob }, function (data) {
            for (var i = 0; i < data.Data.length; i++) {
                var newGauge = new jGauge();
                newGauge.id = 'gauge_' + (i + 1);
                newGauge.action = data.Data[i].Action;
                newGauge.imagePath = 'img/gauge/jgauge_face_taco.png';
                newGauge.needle.imagePath = 'img/gauge/jgauge_needle_taco.png';
                newGauge.needletarget.imagePath = 'img/gauge/jgauge_needle_default.png';
                newGauge.segmentStart = -225;
                newGauge.segmentEnd = 45;
                newGauge.width = 170;
                newGauge.height = 170;
                newGauge.ticks.count = data.Data[i].Ticks;
                newGauge.ticks.start = 0;
                newGauge.ticks.end = data.Data[i].MaxValue;
                newGauge.label.suffix = data.Data[i].Suffix;
                newGauge.setGreenRange(data.Data[i].GreenRangeStart, data.Data[i].GreenRangeEnd);
                newGauge.setYellowRange(data.Data[i].YellowRangeStart, data.Data[i].YellowRangeEnd);
                newGauge.setRedRange(data.Data[i].RedRangeStart, data.Data[i].RedRangeEnd);
                newGauge.needle.xOffset = 0;
                newGauge.needle.yOffset = 0;
                newGauge.label.yOffset = 55;
                newGauge.label.color = '#fff';
                newGauge.label.precision = 2;
                newGauge.init();
                newGauge.setValue(0);
                setGaugeValue(data.Data[i].Action, $('#periodstart').val(), $('#periodend').val(), newGauge, data.Data[i].Suffix, $('#browseall').val(), $('#browsewithrights').val(), $('#uid').val());
                newGauge.setValueTarget(data.Data[i].TargetValue);
                $('#' + newGauge.id + "_target").text(Number(data.Data[i].TargetValue).toFixed(2) + data.Data[i].Suffix);
                gaugesstack.push(newGauge);
            }
        });
    }
}

function saveGaugeSettings() {
    var defpersswitch = Number($("#defpersswitch").val());
    var id = defpersswitch == 1 ? $('#gaugeselector').val() : $('#defaultgaugeselector').val();

    if (id > 0) {
        var name = $('#setupgaugename').val();
        var action = $('#setupgaugeaction').val();
        var ticks = $('#setupgaugeticks').val();
        var targetvalue = $('#setupgaugetargetvalue').val();
        var maxvalue = $('#setupgaugemaxvalue').val();
        var suffix = $('#setupgaugesuffix').val();
        var greenrangestart = $('#setupgaugegreenrangestart').val();
        var greenrangeend = $('#setupgaugegreenrangeend').val();
        var yellowrangestart = $('#setupgaugeyellowrangestart').val();
        var yellowrangeend = $('#setupgaugeyellowrangeend').val();
        var redrangestart = $('#setupgaugeredrangestart').val();
        var redrangeend = $('#setupgaugeredrangeend').val();
        var showorder = $('#setupgaugeshoworder').val();

        $.post(base + "gauge.ivp/savegaugesettings", { name: name, action: action, id: id, ticks: ticks, targetvalue: targetvalue, maxvalue: maxvalue, suffix: suffix, greenrangestart: greenrangestart, greenrangeend: greenrangeend, yellowrangestart: yellowrangestart, yellowrangeend: yellowrangeend, redrangestart: redrangestart, redrangeend: redrangeend, showorder: showorder, defpersswitch: defpersswitch }, initializeGauges);
    }
    $('#gaugesetup').dialog("close");

    updateSelector();

    cleanGaugeSettings();



    return false;
}

function updateSelector() {
    var defpersswitch = Number($("#defpersswitch").val());

    $.getJSON(base + 'gauge.ivp/getgaugesjson', { defpersswitch: defpersswitch, selector: 1 }, function (data) {

        var newOptions = {};
        newOptions[""] = 0;
        for (var i = 0; i < data.Data.length; i++) {
            newOptions[data.Data[i].Name] = data.Data[i].Id;
        };

        var $el = defpersswitch == 1 ? $("#gaugeselector") : $("#defaultgaugeselector");
        $el.empty(); // remove old options
        $.each(newOptions, function (key, value) {
            $el.append($("<option></option>")
                .attr("value", value).text(key));
        });
    });
}

function applyGaugeFilter() {
    var params = $('#commonFilter .formbody [name][isdate!=1]').serializeArray();
    var dates = [];
    $('#commonFilter .formbody input[date]').each(function () {
        var date = { name: $(this).attr('name'), value: $(this).attr('date') };
        dates[dates.length] = date;
    });

    params = $.merge(params, dates);

    $.post(base + 'gauge.ivp/savefilter', params);

    $('#isfilterset').val(1);
    toggleFilterControls();
    $('#commonFilter').hide();
    $('#gaugesetup').dialog({ width: 360 });
    $('#settingsbody').show();
    $('#settingscontrols').show();
    $('#savegaugesettings').show();
    $('#abandongaugesettings').show();
    return false;
}

function toggleFilterControls() {
    if (Number($('#isfilterset').val()) == 1) {
        $("#filterisset").removeClass("hidden");
        $("#filterisnotset").addClass("hidden");
    } else {
        $("#filterisset").addClass("hidden");
        $("#filterisnotset").removeClass("hidden");
    }

}

function setGaugeValue(action, periodstart, periodend, newGauge, suffix, browseall, browsewithrights, uid) {
    paramsa = $('#commonFilter .formbody select').serializeArray();
    paramsb = $('#commonFilter .formbody input').serializeArray();
    params = paramsa.concat(paramsb);

    params.push({ name: 'periodstart', value: periodstart });
    params.push({ name: 'periodend', value: periodend });

    $.post(base + 'gauge.ivp/' + action, params, function (valuedata) {
        newGauge.setValue(valuedata.Data);
        $('#' + newGauge.id + "_actual").text(Number(valuedata.Data).toFixed(2) + suffix);
    }, 'json');

    var today = new Date();
    var ytdstart = new Date(Number(today.getFullYear()), 0, 1).toDateString();
    var ytdend = new Date(Number(today.getFullYear()), Number(today.getMonth()), today.getDate()).toDateString();

    params.pop();
    params.pop();

    params.push({ name: 'periodstart', value: ytdstart });
    params.push({ name: 'periodend', value: ytdend });

    $.post(base + 'gauge.ivp/' + action, params, function (valuedata) {
        $('#' + newGauge.id + "_ytd").text(Number(valuedata.Data).toFixed(2) + suffix);
    }, 'json');

    var monthstart = new Date(Number(today.getFullYear()), Number(today.getMonth()), 1).toDateString();
    var mtdend = new Date(Number(today.getFullYear()), Number(today.getMonth()), today.getDate()).toDateString();

    params.pop();
    params.pop();
    params.push({ name: 'periodstart', value: monthstart });
    params.push({ name: 'periodend', value: mtdend });
    $.post(base + 'gauge.ivp/' + action, params, function (valuedata) {
        $('#' + newGauge.id + "_mtd").text(Number(valuedata.Data).toFixed(2) + suffix);
    }, 'json');

    return false;
}

function deletePersonalGauges() {
    $.post(base + "gauge.ivp/deletepersonalgauges");
    $("#personalscount").val(0);
    cleanGaugeSettings();
    $("#defaultgaugesettings").click();
}

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

    $(".k-header-column-menu-wrap").hide();
    $(".k-resize-handle").hide();
};

function initGaugeFilter() {
    if ($('#filter').length > 0) {
        if ($.fn.calendar) {
            $('#filter input.date, #filter input.dateTime').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'));
            });
        }
        //Фильтр. Скрыть/показать поля для даты при изменении "равно" на "между"
        //Фильтр. Скрыть/показать поля для выбора при изменении условия с/на "задано","не задано"
        $('#filter .fttdate').change(function () {
            switch (this.value) {
                case "1":
                    $(this).parents('table').find('.fltdate').show();
                    $(this).parents('table').find('.date2').hide();
                    break;
                case "2":
                case "3":
                    $(this).parents('table').find('.fltdate').show();
                    $(this).parents('table').find('.date2').show();
                    break;
                case "4":
                case "5":
                    $(this).parents('table').find('.fltdate').hide();
                    $(this).parents('table').find('.date2').hide();
            }
        });
        //Фильтр. Скрыть/показать поля для чисел при изменении "равно" на "между"
        //Фильтр. Скрыть/показать поля для выбора при изменении условия с/на "задано","не задано"
        $('#filter .fttnumeric').change(function (el) {
            $(this).parents('table').find('.numeric').show();
            if (this.value == 5) $(this).parents('table').find('.numeric2').show(); else $(this).parents('table').find('.numeric2').hide();
            if (this.value == 4) { $('.numeric3', this.parentNode).show(); $(this).parents('table').find('.numeric').css('width', 150); } else { $(this).parents('table').find('.numeric3').hide(); $(this).parents('table').find('.numeric').css('width', 50); }
            if (this.value == 6 || this.value == 7) $(this).parents('table').find('.numeric').hide();
        });

        //Установка значений по умолчанию
        $('#filter .flttext').change(function () { var ftt = '#ftt' + this.id.substr(3); if ($(ftt).val() == 0 && this.value.length > 0) $(ftt).val(1); });
        $('#filter .numeric').change(function () { var ftt = '#ftt' + this.id.substr(4); if ($(ftt).val() == 0 && this.value.length > 0) $(ftt).val(1); });
        //В зависимости от количества опций, выбрать "Входит в" или "Содержит любое из"
        $('#filter .fltselect').change(function () { var ftt = '#ftt' + this.id.substr(3); if ($(ftt).val() == 0 && this.selectedIndex >= 0) $(ftt).val(($('option', ftt).length > 5) ? 3 : 1); });
        $('#filter .flttree').change(function () { var ftt = '#ftt' + this.id.substr(3); if ($(ftt).val() == 0 && this.selectedIndex >= 0) $(ftt).val(3); });
        $('#filter .fltdate').change(function () { var ftt = '#ftt' + this.id.substr(4); if ($(ftt).val() == 0 && this.value.length > 0) $(ftt).val(1); });
        $('#filter .fltsmalltree').change(function () { var ftt = '#ftt' + this.id.substr(3); if ($(ftt).val() == 0 && this.selectedIndex >= 0) $(ftt).val(1); });

        //Заменим выпадающие списки на спец. контрол
        if ($.multipleSelect) $.multipleSelect.initByClassName('.multipleselect', { maxwidth: '300px', init: true });

        //Фильтр. Скрыть/показать поля для выбора при изменении условия с/на "задано","не задано"
        $('#filter .fttselect').change(function () {
            if (this.value == 3 || this.value == 4) $(this).parents('tr').find('.tdvalue div').hide(); else $(this).parents('tr').find('.tdvalue div').show();
        });
        $('#filter .fttrelation').change(function () {
            if (this.value == 7 || this.value == 8) $(this).parents('tr').find('.tdvalue div').hide(); else $(this).parents('tr').find('.tdvalue div').show();
        });
        $('#filter .ftttext').change(function () {
            if (this.value == 7 || this.value == 8) $(this).parents('tr').find('.flttext').hide(); else $(this).parents('tr').find('.flttext').show();
        });
        $('#filter .ftttree').change(function () {
            var self = this;
            var flt = $('#flt' + self.id.substr(3));
            var ms = flt.data('multipleselect');
            if (self.value == 0) {
                flt.attr('multiple', true);
                ms.unwrapClearControl();
            }
            if (self.value == 1 || self.value == 2) {
                flt.attr('multiple', false);
                ms.unwrapControl();
            }
            else {
                flt.attr('multiple', true);
                ms.wrapControl(true);
            }
        }).trigger('change');

        $('#filter .fttsmalltree').change(function () {
            var self = this;
            var flt = $('#flt' + self.id.substr(3));
            var ms = flt.data('multipleselect');
            if (self.value == 0) {
                flt.attr('multiple', true);
                ms.unwrapClearControl();
            }
            else {
                flt.attr('multiple', true);
                ms.wrapControl(true);
            }
        }).trigger('change');


        //Если у фильтра есть класс additional добавим в доп поля
        $('#filter .additional').wrapAll('<div id="additionalwrapper"/>');
        //$('#additionalwrapper .assettype:first').prepend('<hr/><span class="additionaldescription">' + FilterResources.AssetFieldTypesAdditionalFields + '</span>');
        //$('#additionalwrapper .filtertype:first').prepend('<hr/><span class="additionaldescription">' + FilterResources.FieldTypesAdditionalFields + '</span>');
        if ((!$('#additionalwrapper .flttype option[value!="0"]').is(':selected') && $('#additionalwrapper .manualfilter').val() == '') || (!$('#additionalwrapper .flttype option[value!="0"]').is(':selected') && $('#additionalwrapper .manualfilter').length < 1)) {
            $('#additionalwrapper .additional').addClass('hidden');
            $('#additionalwrapper').prepend('<a href="#"class="nounderline" onclick="return toggle(this, \'#additionalwrapper .additional\',\'' + FilterResources.ShowAdditionalFields + '\',\'' + FilterResources.HideAdditionalFields + '\')">' + '&darr; ' + FilterResources.ShowAdditionalFields + '</a><div class="spacer10"></div>');
        }
        else {
            $('#additionalwrapper').prepend('<a href="#" class="nounderline" onclick="return toggle(this, \'#additionalwrapper .additional\',\'' + FilterResources.ShowAdditionalFields + '\',\'' + FilterResources.HideAdditionalFields + '\')">' + '&uarr; ' + FilterResources.HideAdditionalFields + '</a><div class="spacer10"></div>');
        }

        if ($("#handlerService_Path").length) {
            var handler = $("#handlerService_Path");
            handler.on("click", "input[type='checkbox']", recheckServices);
        }
        $('#filterholder').show();

        $('.flttype').change(function () {
            var clickElement = $(this).parents('tr').find('.tdvalue div .checklisttitle a');
            if (this.value != 0) {
                setTimeout(function () {
                    clickElement.click();
                }, 0);

            }
        });
    }
}