﻿/// <reference path="~/Scripts/ByteStorm/_BSC_Interface.js" />
(function()
{
    BSC.Require("BSC.D", true);
    BSC.D.P = function()
    {
        /// <summary>Javascript data cache 1</summary>
        var contactslist = new Array();
        var pagekeys = {};
        /* list of
        ==========
        Guid id
        string screenname
        string displayname
        bool gender
        bool online
        int priority
        */
        var profiledata = null;
        var access = {};
        var routeAccess = {};
        var settings = {};
        function FilterConatctById(element, index, array)
        {
            var e = (element.ID === this.ID);
            return e;
        }

        function SaveSettings()
        {

        }
        return {
            AddPageKey: function(k)
            {
                pagekeys[k] = true;
            },
            MemberTypes: { Guest: 0, Suspended: 30, Applicant: 40, Standard: 50 },
            Init: function(cb)
            {
                BSC.D.Send(null, "Content.Profile", "Init", BSC.D.P.InitCB, null, cb);
            },
            InitCB: function(res)
            {
                // Loader 
                // - profile data
                // - settings
                profiledata = res.d.i;

                BSC.UI.Ws.Chat.UpdateProfileCount(res.d.c);
                BSC.UI.Ws.Mail.UpdateMailCount(res.d.m);

                var ac = profiledata.Access;
                profiledata.Access = {};
                if (!profiledata.Settings)
                    profiledata.Settings = {};
                if (ac)
                {
                    for (i in ac)
                    {
                        var scriptid = ac[i].ScriptID;
                        //if (scriptid == "group") scriptid = scriptid + ".summary";
                        profiledata.Access[scriptid] = ac[i];
                    }
                }
                var a = {
                    admin:
						{
						    __key: {
						        members: { isValid: true },
						        discussions: { isValid: true },
						        posts: {
						            __discussionkey: { isValid: true }
						        },
						        isValid: true
						    }
						},
                    group:
						{
						    __key: {
						        members: { isValid: true },
						        discussions: { isValid: true },
						        posts: {
						            __discussionkey: { isValid: true }
						        },
						        isValid: true
						    }
						}
                };

                ///
                //					var a = {
                //						group:
                //						{
                //							__key: {
                //								members: {isValid : true},
                //								discussions: {isValid : true},
                //								posts: {
                //									__discussionkey: { isValid : true }
                //								},
                //								isValid : true
                //							}
                //						}
                //					};

                //				for (k in profiledata.Access)
                //				{
                //					var uri = profiledata.Access[k].Route;
                //					if (!uri) continue;

                //					var t = uri.split("/");

                //					var cn = "";
                //					var root = {};
                //					var currentPath = "routeAccess";
                //					for (i = 1; i < t.length; i++)
                //					{
                //						var key = t[i];
                //						if (!key || key.length == 0) continue;

                //						if (key.indexOf("{") == 0)
                //							key = "__" + (key.replace(/{/, "").replace(/}/, ""));

                //						currentPath = currentPath + "." + key;

                //						var tdt = eval(currentPath);

                //						if (!tdt)
                //						{
                //							if (i == t.length - 1)
                //								eval(currentPath + " = {isValid : true};")
                //							else
                //								eval(currentPath + " = {};")
                //						} else if (i == t.length - 1)
                //							eval(currentPath + ".isValid = true;")
                //					}

                //				}

                if (profiledata.ChangePassword)
                {
                    $("#bluroverlay").addClass("none");
                    BSC.UI.Alert("Change Password", null, "Change password", "Your password was reset.<br/><br/>Please create your own password to remember. The password must be minimum 4 characters.<br/>New password<br/><input type=\"password\" id=\"setnewpassword1\" name=\"setnewpassword2\" style=\"width:80%\" /><br/>Repeat password<br/><input type=\"password\" id=\"setnewpassword2\" name=\"setnewpassword2\" style=\"width:80%\" />", function(e)
                    {
                        // sdfsd
                        var pwd1 = $("#setnewpassword1").getValue();
                        var pwd2 = $("#setnewpassword2").getValue();


                        if (!pwd1 || pwd1.lenth < 5)
                        {
                            $("#setnewpassword1").val("").trigger("focus");
                            $("#setnewpassword2").val("");
                            BSC.UI.HideHelpBubble();
                            BSC.UI.ShowHelpBubble("setnewpassword1", "info", "Invalid password", "Please the same password the the two fields. The password must be minimum 4 characters.", { top: -9, left: 180 });
                            return false;
                        }

                        if (pwd1 != pwd2)
                        {
                            $("#setnewpassword1").val("").trigger("focus");
                            $("#setnewpassword2").val("");
                            BSC.UI.HideHelpBubble();
                            BSC.UI.ShowHelpBubble("setnewpassword1", "info", "Password don't match", "The two passwords don't match", { top: -9, left: 180 });
                            return false;
                        }

                        $.post("/profile/setpassword", { p: pwd1 }, function()
                        {
                            //alert("done")
                        }, "json");

                        if (e.data) e.data.apply(null, []);



                    }, this.d, "info");
                }
                else
                {
                    if (this.d)
                        this.d.apply(null, []);
                }
            },
            SetLanguage: function(id)
            {
                var p = new BSC.D.Param("BSC.WS.JS.Profile.Language");
                p.Add("LanguageID", id);
                BSC.D.Send(p, "Content.Profile", "ChangeLanguage", function(res)
                {
                    self.location.reload();
                });
            },
            LoadContacts: function(guid, cb)
            {
                BSC.D.Send(null, "Content.Profile", "GetContacts",
                function(res)
                {
                    contactslist = res.d;
                    if (this.d.cb)
                        this.d.cb.apply(null, [this.d.guid]);
                }, null, { guid: guid, cb: cb });
            },

            StartNotificationChannel: function()
            {

                var pd = BSC.D.P.GetData();
                var dt = BSC.D.DateDelta();
                dt = parseInt(dt);
                var p = { pkey: pd.PKey, timezonediff: dt };
                var channel = BSC.D.Channel.Get(BSC.BASE_SERVICE_PATH, "/ProxyPage.aspx", "GetNotifications", 60);
                channel.Send(p, BSC.UI.Ws.Chat.QueueData, null, true);
            },

            DestroyNotificationChannel: function()
            {
                /// implementation missing
            },

            GetContacts: function(id)
            {
                return contactslist;
            },

            GetContact: function(id)
            {
                var result = contactslist.filter(FilterConatctById, { ID: id });
                if (result.length == 0)
                {
                    var contact = BSC.D.SendSync({ data: id }, "Content.Profile", "GetContact");
                    if (contact)
                    {
                        delete contact.__type;
                        contactslist.push(contact);
                    }
                    return contact;
                }
                else
                    return result[0];
            },

            AddContact: function(contact)
            {
                var result = contactslist.filter(FilterConatctById, { ID: contact.ID });
                if (result.length > 0) return;
                contactslist.push(contact);
            },

            GetData: function(key)
            {
                if (arguments.length == 0)
                    return profiledata;

                if (profiledata)
                    return profiledata[key];

                return null;
            },

            SetData: function(key, value)
            {
                profiledata[key] = value;
            },

            HasAccess: function(p)
            {
                //var sdsd = /\/(\w*)=/.test(id);
                var id = (p) ? p.replace(/\/(\w*)=(.*)/i, "") : null;
                if (!id) return false;
                if (id.charAt(id.length - 1) == "/") id = id.substr(0, id.length - 1);
                return (profiledata.Access[id] != null);
            },

            GetAccess: function(p)
            {
                //id = (id) ? id.split(/\/(\w*)=/)[0] : null;
                if (arguments.length == 0)
                    return profiledata.Access;
                else
                {
                    var id = (p) ? p.replace(/\/(\w*)=(.*)/i, "") : null;
                    if (!id) return null;
                    if (id != "/" && id.charAt(id.length - 1) == "/") id = id.substr(0, id.length - 1);
                    if (id.indexOf("?") > -1) id = id.substr(0, id.indexOf("?") - 1);
                    id = id.toLowerCase();

                    //					// parse mvc cases
                    //					var data = {};
                    //					var accessID = id;
                    //					if (id.indexOf("/group/") == 0
                    //						&& id.indexOf("/group/create") == -1
                    //						//&& id.indexOf("/group/search") == -1
                    //						&& id.indexOf("/group/mygroups") == -1
                    //						&& id.indexOf("/group/searchresult") == -1
                    //					)
                    //					{
                    //						var t = id.split("/");
                    //						var newPathID = "/" + t[1];
                    //						if (t.length > 2) data["val1"] = t[2];
                    //						if (t.length > 4) data["val2"] = t[4];

                    //						if (t.length > 3)
                    //							newPathID = newPathID + "/" + t[3];

                    //						accessID = (newPathID == "/group") ? newPathID + "/summary" : newPathID;
                    //					}

                    //					var a = {
                    //						group:
                    //						{
                    //							__key: {
                    //								members: {isValid : true},
                    //								discussions: {isValid : true},
                    //								posts: {
                    //									__discussionkey: { isValid : true }
                    //								},
                    //								isValid : true
                    //							}
                    //						}
                    //					};
                    // /profile/rasmus

                    var specialFormat =
					{
					    profile:
							{
							    __key: {
							        about: { isValid: true },
							        friends: { isValid: true },
							        admin: { isValid: true },
							        photos: {
							            __albumkey: { isValid: true }
							        },
							        isValid: true
							    }
							},
					    rating:
							{
							    __key: {
							        isValid: true
							    },
							    isValid: true

							},
					    chat:
							{
							    room: {
							        __id: { isValid: true }
							    },
							    isValid: true

							},
					    group:
							{
							    __key: {
							        members: { isValid: true },
							        edit: { isValid: true },
							        discussions: { isValid: true },
							        discussion: {
							            __discussionkey: { isValid: true }
							        },
							        isValid: true
							    }
							},
					    groups:
						{
						    search: {
						        __query: { isValid: true }
						    },
						    isValid: true
						},
					    members:
							{
							    latestonline: { isValid: true },
							    nearby: { isValid: true },
							    findfriends: { isValid: true },
							    criteriasearch: { isValid: true },
							    premium: { isValid: true },
							    search: {
							        __name: { isValid: true }
							    },
							    top50: {
							        __list: { isValid: true }
							    },
							    applicants: {
							        __list: { isValid: true }
							    },
							    isValid: true
							},
					    feedback: ///feedback/reportprofile/{id} /feedback/reportapplicant/{id}
					            {
					            reportprofile: {
					                __id: { isValid: true }
					            },
					            reportapplicant: {
					                __id: { isValid: true }
					            },
					            isValid: true
					        }
					}
                    var a_id = id.split("/");
                    var root = a_id[1];
                    var identifier = "";

                    if (!pagekeys[root] && root != "groups")
                    {
                        // profile
                        root = "profile";
                        var tid = "/profile" + id;
                        a_id = tid.split("/");
                    }


                    if (specialFormat[root])
                    {
                        var l = a_id.length;
                        var url = "/" + a_id[1];
                        var vars = {};
                        identifier = root;
                        var rootIndex = specialFormat[root];
                        var validUri = (rootIndex && rootIndex.isValid);
                        for (i = 2; i < l; i++)
                        {
                            validUri = false;
                            for (k in rootIndex)
                            {
                                if (k.indexOf("__") == 0)
                                {
                                    var var_id = k.replace(/__/, "");
                                    vars[var_id] = a_id[i];
                                    rootIndex = rootIndex[k];
                                    validUri = (root && root.isValid);
                                    break;
                                }
                                else if (k == a_id[i])
                                {
                                    rootIndex = rootIndex[k];
                                    identifier = identifier + "." + k;
                                    validUri = (root && root.isValid);
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        identifier = (id.substring(1, id.length)).replace(/\//g, ".");
                    }


                    //					var a_id = id.split("/");
                    //					var l = a_id.length;
                    //					var root = routeAccess[a_id[1]];
                    //					var url = "/" + a_id[1];
                    //					var vars = {};
                    //					var identifier = a_id[1];
                    //					var validUri = (root && root.isValid);
                    //					for (i = 2; i < l; i++)
                    //					{
                    //						validUri = false;
                    //						for (k in root)
                    //						{
                    //							if (k.indexOf("__") == 0)
                    //							{
                    //								var var_id = k.replace(/__/, "");
                    //								vars[var_id] = a_id[i];
                    //								root = root[k];
                    //								validUri = (root && root.isValid);
                    //								break;
                    //							}
                    //							else if (k == a_id[i])
                    //							{
                    //								root = root[k];
                    //								identifier = identifier + "." + k;
                    //								validUri = (root && root.isValid);
                    //								break;
                    //							}
                    //						}
                    //					}

                    //					var d = identifier;

                    if (p == "/group/create") identifier = "group.create";
                    else if (p == "/groups/mygroups") identifier = "group.mygroups";
                    //else if (identifier == "groups.search") identifier = "group.search";
                    else if (identifier == "group") identifier = "group.summary";

                    var cw = profiledata.Access[identifier];
                    if (cw)
                    {
                        cw.cp = id;
                        cw.identifier = identifier;

                        cw.Key = vars;
                        cw.Data = vars;

                        var q = p.replace(id, "", "i");
                        q = q.replace(/\//, "");
                        q = q.replace(/\?/, "");
                        cw.Query = q;
                        cw.p = id;
                        if (cw.Query)
                            cw.p = cw.p + "/?" + cw.Query;
                    }
                    return cw;
                }
            },

            //			ChangeStatus: function(txt)
            //			{
            //				var p = new BSC.D.Param("BSC.WS.JS.Profile.ChangeStatus");
            //				p.Add("status", txt);
            //				BSC.D.Send(p, "Content.Profile", "ChangeStatus");
            //			},

            IsLoggedIn: function()
            {
                return (profiledata && profiledata.IsAuthenticated);
            },

            IsFullMember: function()
            {
                return (profiledata && profiledata.IsFullMember);
            },

            IsPremiumMember: function()
            {
                return (profiledata && profiledata.IsPremiumMember);
            },

            IsPremiumMemberPLUS: function()
            {
                return (profiledata && profiledata.IsPremiumMemberPLUS);
            },

            ShowBanners: function()
            {
                return (profiledata && profiledata.ShowBanners);
            },

            VisibilityScope: function()
            {
                return (profiledata && profiledata.VisibilityScope);
            },

            IsNotApplicant: function()
            {
                return (profiledata && profiledata.IsNotApplicant);
            },

            IsApplicant: function()
            {
                return (profiledata && profiledata.IsApplicant);
            },

            IsApplicantPLUS: function()
            {
                return (profiledata && profiledata.IsApplicantPLUS);
            },

            IsPaying: function()
            {
                return (profiledata && profiledata.IsPaying);
            },

            GetLog: function()
            {
                return { pd: profiledata, access: access };
            },

            IsMute: function()
            {
                return (BSC.D.P.Setting("sound_mute") && BSC.D.P.Setting("sound_mute") == "true");
            },

            Setting: function(id, value)
            {
                var sett = (profiledata.ID == null) ? settings : profiledata.Settings;

                //

                if (arguments.length == 0)
                    return sett;
                else if (arguments.length == 1)
                {
                    var setting = (sett[id] == undefined) ? null : sett[id];
                    return setting;
                }
                else if (arguments.length == 2)
                {
                    if (profiledata.ID == null)
                    {
                        settings[id] = value;
                        return;
                    }
                    profiledata.Settings[id] = value;
                    var p = new BSC.D.Param("BSC.WS.JS.Profile.Settings");
                    p.Add("setting", BSC.D.JSON.ToString(profiledata.Settings));
                    BSC.D.Send(p, "Content.Profile", "SaveSettings");
                }
            }
        };
    } ();
})();    
