﻿var GroupMember = {

    Init: function (settings) {
        var opts = $.extend({}, GroupMember.Settings, settings);
        var param = null;

        if (opts.GroupId != '0') {

            if (opts.IsRequest) {
                param = GroupSettings.GroupId;
            }
            else if (opts.IsFilter) {
                param = GroupSettings.GroupId + '/' + this.Settings.regionList + '/' + this.Settings.relationshipNaturaList + '/' + this.Settings.Search;
            }
            else {
                param = GroupSettings.GroupId + '/' + opts.DirectionSort + '/' + opts.TimePeriod
            }

            param += '/' + opts.PageSkip + '/' + opts.PageSize;

            var urlService = opts.UrlService + '/' + opts.Method + '/' + param;

            try {

                $.getJSON(urlService, MemberLoadResult);

            } catch (e) {
                LogFailure('', document.location, e.Message);
            }

        }

        function MemberLoadResult(results) {

            $('#MembrosContainer').LoadTemplate({
                Data: [{ 'AjaxResponse': results, 'IsRequest': opts.IsRequest, 'IsUserModerator': GroupSettings.IsUserModerator, 'IdLogin': AccountSettings.LoggedUserId, 'IsLogged': AccountSettings.LoggedUserId == '0' ? false : true}],
                TemplateName: 'tmpMember',
                UrlTemplate: '/Group/Member/AsyncTemplates/MemberList.htm',
                CallMethod: GroupMember.RegisterAfterScript,
                DataPaging: results.Paging,
                IsPaging: true,
                PagingTarget: $('#paging'),
                PagingOptions: { callMethod: GroupMember.NavigatePage, IndexPage: GroupMember.Settings.PageSkip }
            });

            GroupMember.Settings.PageSkip = 0;
        }

    },

    NavigatePage: function (Index) {
        Index = Index == undefined ? 1 : Index;
        GroupMember.Settings.PageSkip = Index < 1 ? 1 : Index;

        if (Index != 1)
            GroupMember.Settings.PageSkip = ((parseFloat(Index) - 1) * parseFloat(GroupMember.Settings.PageSize));
        else
            GroupMember.Settings.PageSkip = 0;

        GroupMember.Load();
    },

    Load: function () {
        this.Init();
    },

    SelectMember: function (DirectionSort, TimePeriod) {
        this.Settings.TimePeriod = TimePeriod;
        this.Settings.DirectionSort = DirectionSort;
        this.Init();
    },

    Request: function () {
        this.Init({ Method: 'GetGroupRequestListByGroupId', IsRequest: true });
    },

    Search: function () {
        this.FilterSide();
    },

    SetCountMember: function (callReferece) {

        if (GroupMember.Settings.GroupId != '0') {
            var urlService = GroupMember.Settings.UrlService + '/GetMemberCount/' + GroupSettings.GroupId;

            try {

                $.getJSON(urlService, SetCountMemberResult);

            } catch (e) {
                LogFailure('', document.location, e.Message);
            }

        }

        function SetCountMemberResult(results) {
            $('' + callReferece.selector + '').html(results.EntityCount);
        }
    },

    FilterRegion: function () {
        this.FilterSide();
    },

    SetCallEventRegion: function (callReferece) {
        $('' + callReferece.selector + '').each(function (i, e) {
            $(this).click(function () {

                GroupMember.FilterRegion();
            });
        });
    },

    FilterRelationshipNatura: function () {
        this.FilterSide();
    },

    FilterSide: function () {

        var relationshipNaturaList = null;
        var regionList = null;

        $("fieldset#RelacaoNaturaList").find("input").each(function () {
            if (this.checked) {
                if (relationshipNaturaList == null) {
                    relationshipNaturaList = this.value;
                }
                else {
                    relationshipNaturaList += "," + this.value;
                }
            }
        });

        $('#RegicoesList input').each(function () {
            if (this.checked) {
                if (regionList == null) {
                    regionList = this.value;
                }
                else {
                    regionList += "," + this.value;
                }
            }
        });

        var Search = $('input[id$=idSearchInitF]').val().replace("busca", ' ');

        if (relationshipNaturaList != null || Search != "" || regionList != "" || Search) {
            $('#menuTabs').find('a').removeClass("selected");
            $('#lkAz').addClass("selected");

            this.Settings.regionList = regionList;
            this.Settings.relationshipNaturaList = relationshipNaturaList;
            this.Settings.Search = (Search == "") ? null : Search;
            this.Init({ Method: 'GetMemberFilter', IsFilter: true });
        }
        else {

            this.Settings.regionList = null;
            this.Settings.relationshipNaturaList = null;
            this.Settings.Search = null;
            GroupMember.SelectMember('Az', null);
        }
    },


    /* --------   Interaction -----------*/

    Interaction: function (Method, Parameters, IsRemove, CallReferece, IsReload) {
        var param = GroupSettings.GroupId + '/' + AccountSettings.LoggedUserId + '/' + Parameters;
        var urlService = GroupMember.Settings.UrlService + '/' + Method + '/' + param;

        try {

            $.getJSON(urlService, InteractionResult);

        } catch (e) {
            LogFailure('', document.location, e.Message);
        }

        function InteractionResult(results) {
            if (IsRemove && IsReload == undefined) {
                GroupMember.RemoveElement(CallReferece);
            }
            else if (IsReload != undefined && GroupSettings.GroupOwnerId != AccountSettings.LoggedUserId) {
                window.location.reload();
            }
        }
    },

    Save: function (callReferece, userId) {
        var param = userId + '/' + false;
        this.Interaction('Save', param, true, callReferece);
    },

    SaveRequest: function (callReferece, userId) {
        this.Interaction('SaveRequest', userId, true, callReferece);
    },

    RevemoRequest: function (param) {
        if (param) {
            $("#MemberList input").each(function () {
                if (this.checked)
                    GroupMember.Interaction('RemoveRequest', this.id, true, this);
            });
        }
    },

    Remove: function (param) {
        if (param) {
            $("#MemberList input").each(function () {
                if (this.checked)
                    GroupMember.Interaction('Remove', '' + this.id + '', true, this);
            });
        }
    },

    RealizeAction: function (param) {
        if ($('.check_list input:checked').length > 0)
            ModalBox.Confirm({ Title: 'Membros', Description: 'Você tem certeza que deseja excluir?', Callback: param == 1 ? GroupMember.RevemoRequest : GroupMember.Remove, CallbackArguments: true })
        else
            ModalBox.Show({ Title: 'Selecione os registros que deseja excluir.', Width: 275, Error: true });

    },

    SetModerator: function (callReferece, userId) {
        var param = userId;
        var isModerator = true;

        if ($(callReferece).hasClass('moderator_active')) {
            $(callReferece).removeClass('moderator_active');
            isModerator = false;
        }
        else {
            $(callReferece).addClass('moderator_active');
        }

        param += '/' + isModerator;
        this.Interaction('Save', param, false, null, isModerator);

    },

    /* --------   Interaction -----------*/


    RemoveElement: function (callRefece) {
        $(callRefece).parents('li').each(function (e) {
            if (e < 1) {
                $(this).css({ overflow: 'hideen' }).animate({ height: 0 }, 500, function () {
                    $(this).remove();
                });
            }
        });
    },

    RegisterAfterScript: function () {
        $('.allSelect').AllCheck({ fatherElementClass: 'memberListRef' });
        $('.removeSelect').AllCheck({ fatherElementClass: 'memberListRef', Checked: false });
    },

    Settings: {
        UrlService: '/Service/Group/Member/MemberService.svc',
        Method: 'GetMemberList',
        DirectionSort: 'MoscAtive',
        TimePeriod: null,
        IsRequest: false,
        IsFilter: false,
        Parameters: '',
        PageSize: 10,
        PageSkip: 0,
        relationshipNaturaList: null,
        regionList: null,
        Search: null
    }
}



$(document).ready(function () {

    $('.drop_list a').click(function () {
        $('.drop_list ul.drop_sub').append('<li></li>');
        $('.drop_list ul.drop_sub li:last').append($('.drop_list li a:first'));
        $('ul.drop_sub').before($(this));
    });


    $('input[id$=idSearchInitF]').blur(function (e) {
        e.preventDefault();
        GroupMember.FilterSide();
    });

    SetEvent($('input[id$=idSearchInitF]'), GroupMember.FilterSide);

});



