﻿(function()
{
    BSC.UI.Ws.Invite = function()
    {
        var localdata = {};

        var AddProfilesToLocaldata = function(guid, data)
        {
            localdata[guid].profiles = {};
            var l = data.length;
            for (i = 0; i < l; i++)
            {
                if (!localdata[guid].addedProfiles[data[i].ID])
                    localdata[guid].profiles[data[i].ID] = data[i].IsMember;
            }
        }

        var LoadProfiles = function(guid, name)
        {
            var w = BSC.UI.Ws.Get(guid);
            var jQ = BSC.U.ParseQuery(w.query);
            var data = {
                fKey: jQ.key,
                type: jQ.type,
                addedprofiles: []
            };

            if (name)
            {
                data.name = name;
                for (profileID in localdata[guid].addedProfiles)
                {
                    data.addedprofiles.push(profileID);
                }
            }

            BSC.D.AjaxPost("/Invite/Result", data, function(res)
            {
                $("#" + guid + "_profilelistadd").hide().html(res);

                var json = $("#" + guid + "_profilejson").getValue();
                var data = BSC.D.JSON.Parse(json);
                if (data)
                    AddProfilesToLocaldata(guid, data);

                var allReadyAddedProfiles = false;
                for (profileID in localdata[guid].addedProfiles)
                {
                    $("#" + profileID + "_dd_pid").remove();
                    allReadyAddedProfiles = true;
                }

                if ($("#" + guid + "_profilelistadd dd").length == 0 && allReadyAddedProfiles)
                    $("#" + guid + "_profilelistadd").html("<br/><br/><br/><br/><center>Found profile(s) allready added</center>");
                else if ($("#" + guid + "_profilelistadd dd").length == 0)
                    $("#" + guid + "_profilelistadd").html("<br/><br/><br/><br/><center>No profiles found</center>");

                $("#" + guid + "_profilelistadd").show();
            }, "html", guid);
        };

        /// <summary>
        /// Bind events to ui elements
        /// </summary>
        var load = function(p1)
        {
            var guid = p1;
            localdata[guid] = { profiles: {}, addedProfiles: {} };

            var json = $("#" + guid + "_profilejson").getValue();
            var data = BSC.D.JSON.Parse(json);
            if (data)
            {
                AddProfilesToLocaldata(guid, data);
            }
        };

        /// <summary>
        /// Bind events to ui elements
        /// </summary>
        var bind = function(p1)
        {
            var guid = p1;

            $("#" + guid + " input:radio").bind("change", guid, function(e)
            {
                var guid = e.data;
                var t = (this.id).split("_");
                var scope = t[1];

                $(this).trigger("blur");

                if (scope == "friends")
                {
                    LoadProfiles(guid);
                    $("#" + guid + "_searchInputFields").hide();
                    BSC.E.Stop(e);
                    return false;
                }
                else //(scope == "entire")
                {
                    $("#" + guid + "_profilelistadd").html("");
                    localdata[guid].profiles = {};
                    $("#" + guid + "_searchInputFields").show();
                    $("#" + guid + "_searchInput").val("");
                    BSC.E.Stop(e);
                    return false;
                }
            });

            /*
            var guid = e.data;
            var t = (this.id).split("_");
            var identifier = t[1];
            if (identifier == "friends")
            {
            $("#" + guid + "_profilelistadd dd").remove();
            if (invitedProfiles.friends != "")
            $("#" + guid + "_profilelistadd").append(invitedProfiles.friends);
            $("#" + guid + "_searchInput").attr('disabled', true);
            $("#" + guid + "_searchProfiles").attr('disabled', true);
            $("#" + guid + "_addall").attr('disabled', false);
            $("#" + guid + "_entire").attr('checked', false);
            $("#" + guid + "_searchInput").val('');
            //invitedProfiles.tempProf = $("#" + guid + "_profilelistadd");
            //alert(invitedProfiles.tempProf.html());
            //                BSC.D.AjaxGet("/Ajax/Invite/Result", { id: invitedProfiles.InviteTypeID, friends: "friends" }, function(res) {
            //                    $("#" + guid + "_profilelistadd dd").remove();
            //                    ddelements = res.replace(/remove_ico/g, 'add_ico');

				//                    $("#" + guid + "_profilelistadd a.add_ico").bind("click", guid, BSC.UI.Ws.Invite.AddProfileToInvitation);
            //                }, "html", guid);
            $("#" + guid + "_profilelistadd a.add_ico").bind("click", guid, BSC.UI.Ws.Invite.AddProfileToInvitation);
            }
            else
            {

				//alert(invitedProfiles.tempProf.html());
            $("#" + guid + "_searchInput").attr('disabled', false);
            $("#" + guid + "_searchProfiles").attr('disabled', false);
            $("#" + guid + "_addall").attr('disabled', true);
            $("#" + guid + "_friends").attr('checked', false);
            $("#" + guid + "_friends").val();
            }
            */

            // Search Profiles
            // -------------------------------------------------
            $("#" + guid + "_searchProfiles").bind("click", guid, function(e)
            {
                var guid = e.data;
                var value = $("#" + guid + "_searchInput").val();
                LoadProfiles(guid, value);
            });

            // Sent invitation
            // -------------------------------------------------
            $("#" + guid + "_sendit").bind("click", guid, function(p1)
            {
                var guid = p1.data;
                BSC.UI.Loader(guid);
                var message = $("textarea#" + guid + "_personalmessage").val();
                var w = BSC.UI.Ws.Get(guid);
                var jQ = BSC.U.ParseQuery(w.query);
                var groupkey = jQ.key;
                var invitetype = jQ.type;

                //				var invitetype = invitedProfiles.InviteType;
                //				var invitetypeid = invitedProfiles.InviteTypeID;
                var ids = "";
                //				for (var i in invitedProfiles.ProfileIDs) 
                //				{
                //					ids += invitedProfiles.ProfileIDs[i];
                //					ids += ",";
                //				}
                var addedprofiles = [];
                for (profileID in localdata[guid].addedProfiles)
                {
                    addedprofiles.push(profileID);
                }
                ids = ids.substring(0, ids.length - 1);
                if (addedprofiles.length == 0)
                {
                    BSC.UI.Alert(BSC.T.Get("JS.BSC.UI.Ws.Admin.OK"), null, "Ups..", "You forgot to invite a friend!", null, null, "info")
                    return;
                }

                $.post("/Invite/InvitationSend", { invitedIDs: addedprofiles, personalmessage: message, _type: invitetype, fKey: groupkey }, function(res)
                {
                    //do callback logic here!!!
                    if (res.success)
                    {
                        BSC.UI.Alert(BSC.T.Get("JS.BSC.UI.Ws.Admin.OK"), null, "Group invitations sent", "To invite more friends click the <br />'Invite friends to group' button", Close(groupkey, guid), null, "info");
                        if ($("#" + guid + "_profilelistadd center").length > 0)
                            $("#" + guid + "_profilelistadd").html("");

                        var dl = $("#" + guid + "_profilelistremove");
                        var ddelements = $("#" + guid + "_profilelistremove").html();
                        if (ddelements)
                        {
                            ddelements = ddelements.replace(/remove_ico/g, 'add_ico');
                            $("#" + guid + "_profilelistadd").append(ddelements);
                        }
                        $("#" + guid + "_profilelistremove").html("");
                        localdata[guid].addedProfiles = {};

                        //BSC.UI.Alert(BSC.T.Get("JS.BSC.UI.Ws.Admin.OK"), null, BSC.T.Get("JS.BSC.UI.Ws.Admin.Send.Success.Title"), BSC.T.Get("JS.BSC.UI.Ws.Admin.Send.Success.Desc"), GO("/admin/profilereports/" + page), null, "info")
                    }
                    else
                    {
                        alert("error");
                    }
                    BSC.UI.HideStatus(guid, 200);
                }, "json");
            });

            // Add All Profiles
            // -------------------------------------------------
            $("#" + guid + "_addall").bind("click", guid, function(e)
            {
                var guid = e.data;
                if ($("#" + guid + "_profilelistadd dd").length == 0) return;

                var dds = $("#" + guid + "_profilelistadd dd");

                var l = dds.length;
                for (x = 0; x < l; x++)
                {
                    var p = dds[x];
                    if (p.title == "Add by clicking the icon")
                    {
                        var pid = p.id.split('_');
                        var profileID = pid[0];
                        localdata[guid].addedProfiles[profileID] = true;
                        var html = $("#" + profileID + "_dd_pid").html();
                        html = " <dd class='friend' id='" + profileID + "_dd_pid_added' title='Added'>" + html + "</dd>";
                        html = html.replace(/add_ico/i, 'remove_ico');
                        html = html.replace(/friendadd/i, 'friendremove');
                        $("#" + profileID + "_dd_pid").remove();
                        $("#" + guid + "_profilelistremove").append(html);
                        html = "";
                        localdata[guid].addedProfiles[profileID] = true;
                    }
                }
            });

            // Remove All Profiles
            // -------------------------------------------------
            $("#" + guid + "_removeall").bind("click", guid, function(e)
            {
                var guid = e.data;

                if ($("#" + guid + "_profilelistadd center").length > 0)
                    $("#" + guid + "_profilelistadd").html("");

                var dl = $("#" + guid + "_profilelistremove");
                var ddelements = $("#" + guid + "_profilelistremove").html();
                ddelements = ddelements.replace(/remove_ico/g, 'add_ico').replace(/_dd_pid_added/g, '_dd_pid').replace(/Added/g, 'Add by clicking the icon');
                $("#" + guid + "_profilelistadd").append(ddelements);
                $("#" + guid + "_profilelistremove").html("");
                localdata[guid].addedProfiles = {};
            });


            // Add/Remove profile in lists
            // -------------------------------------------------
            $("#" + guid + "_profilelists").bind("click", guid, function(e)
            {
                var guid = e.data;
                // A Tags
                var el = BSC.E.GetElement(e, "dl", "a");
                if (el.id)
                {
                    var t = (el.id).split("_");
                    var profileID = t[0];

                    if ($(el).hasClass("add_ico"))
                    {
                        AddProfileToInvitation(profileID, guid);
                    }
                    else if ($(el).hasClass("remove_ico"))
                    {
                        RemoveProfileFromInvitation(profileID, guid);
                    }
                }
                BSC.E.Stop(e);
            });


        };
        var Close = function(key, guid)
        {
            BSC.UI.W.Close(guid);
            GO("group/" + key);
        }
        var AddProfileToInvitation = function(p1, p2)
        {
            var profileID = p1;
            var guid = p2;

            var html = $("#" + profileID + "_dd_pid").html();

            // Remove from Not selected list
            $("#" + profileID + "_dd_pid").remove();

            // Add to selected list
            html = " <dd class='friend' id='" + profileID + "_dd_pid_added' title='Added'>" + html + "</dd>";
            html = html.replace(/add_ico/i, 'remove_ico');
            html = html.replace(/friendadd/i, 'friendremove');
            $("#" + guid + "_profilelistremove").append(html);

            localdata[guid].addedProfiles[profileID] = true;
        };

        var RemoveProfileFromInvitation = function(p1, p2)
        {
            var profileID = p1;
            var guid = p2;

            var html = $("#" + profileID + "_dd_pid_added").html();

            // Remove from Not selected list
            $("#" + profileID + "_dd_pid_added").remove();

            // Add to selected list
            html = " <dd class='friend' id='" + profileID + "_dd_pid' title='Added'>" + html + "</dd>";
            html = html.replace(/remove_ico/i, 'add_ico');
            html = html.replace(/friendremove/i, 'friendadd');
            html = html.replace(/_dd_pid_added/i, '_dd_pid').replace(/Added/i, 'Add by clicking the icon');
            $("#" + guid + "_profilelistadd").append(html);

            delete localdata[guid].addedProfiles[profileID];
        };


        var ProfileSearch = function(p1)
        {
            var guid = p1;
            var w = BSC.UI.Ws.Get(guid);
            var jQ = BSC.U.ParseQuery(w.query);
            var value = $("#" + guid + "_searchInput").val();
            var data = {
                name: value,
                id: jQ.id,
                type: jQ.type
            };

            BSC.D.AjaxGet("/Invite/Result", data, function(res)
            {
                $("#" + guid + "_profilelistadd").html(res);

                var json = $("#" + guid + "_profilejson").getValue();
                var data = BSC.D.JSON.Parse(json);
                if (data)
                {
                    alert(data);
                }
            }, "html", guid);
        };



        /// <summary>
        /// Unbind events to ui elements
        /// </summary>
        var unbind = function(p1)
        {
            var guid = p1;

        };


        return {

            /// <summary></summary>
            /// <param name="data"></param>
            /// <return></return>
            Load: load,

            /// <summary></summary>
            /// <param name="data"></param>
            /// <return></return>
            Bind: bind,

            /// <summary></summary>
            /// <param name="data"></param>
            /// <return></return>
            Unbind: unbind
        };
    } ();
})();
BSC.E.Subscribe("load", BSC.UI.Ws.Invite.Load, null, "invite");
BSC.E.Subscribe("bind", BSC.UI.Ws.Invite.Bind, null, "invite");
BSC.E.Subscribe("unbind", BSC.UI.Ws.Invite.Unbind, null, "invite");
