﻿/// <reference path="~/Scripts/IntelliSense/Intellisense.js" />

(function()
{
    BSC.UI.Ws.Chat = function()
    {
        var localdata = {};
        var updateTime = 30000;
        var current = null;

        /// Private End
        var bind = function(p1)
        {
            var guid = p1;
            current = guid;
            localdata[guid] = { timer: null }

            $("#chat_onlinefriends").click(function(e)
            {
                var el = BSC.E.GetElement(e, "dl", "a");
                if (!el.id) return;

                var profileid = ((el.id).split("_"))[1];

                BSC.UI.Ws.Chat.Room.CreatePrivateChat(profileid);
            });

            $("#public_chat").click(function(e)
            {
                BSC.UI.Ws.Chat.Room.CreatePublicChat('public');
                return;
            });
        };

        var unbind = function(p1)
        {
            var guid = p1;
            $("#chat_onlinefriends a").unbind();
            delete localdata[guid];
            current = null;
        };


        return {
            Bind: bind,
            Unbind: unbind,
            UpdateProfileCount: function(count)
            {
                if (!count || count == "undefined")
                    count = 0;

                $(".publicProfileChatCount").html(count);
                if (count == 0)
                {
                    $("#badge_chat").hide();
                    return;
                }
                $("#badge_chat").html(count).show();
            }
        };
    } ();
})();

BSC.E.Subscribe("bind", BSC.UI.Ws.Chat.Bind, null, "chat");
BSC.E.Subscribe("unbind", BSC.UI.Ws.Chat.Unbind, null, "chat");

/// *************************************************************
/// *************************************************************
/// *************************************************************
/// *************************************************************

(function()
{
    BSC.UI.Ws.Chat.Room = function()
    {
        var chats = [];
        var chat = {};
        var current = null;
        var activeChannel = null;
        var hasSentIsTyping = false;
        var scrollTimer = null;
        var blinkTimers = {};
        var scrollToBottom = true;

        //************************************************
        //************************************************
        // Private
        //************************************************
        //************************************************
        var SubscribeToChat = function(room)
        {
            fm.websync.client.subscribe({
                channel: '/c/' + room,
                ext: { ticketid: BSC.D.P.GetData("TicketID"), langaugecode: BSC.D.P.GetData("LanguageCode") },
                onSuccess: function(args)
                {
                    var channel = args.channel[0].replace(/\/c\//i, "");
                    chats.push(channel);
                    LoadProfileList(channel, { id: BSC.D.P.GetData("ID"), gender: BSC.D.P.GetData("Gender"), name: BSC.D.P.GetData("Name") });
                },
                onFailure: function(args) { alert('Error connecting to room!'); },
                onReceive: function(args) { BSC.UI.Ws.Chat.Room.ParseData(args); }
            });
        }

        var AddMessageToLocal = function(channel, message)
        {

        };

        var Init = function(guid)
        {
            current = guid;

            // UI
            $("#" + guid + "_tabs_content_ul").unbind().bind("click", { guid: guid }, BSC.UI.Ws.Chat.Room.OnTabClick);
            $("#" + guid + "_sendmsg").unbind().bind("click", { guid: guid }, BSC.UI.Ws.Chat.Room.SendMessage);
            $("#" + guid + "_chatmsg").bind("keyup", guid, function(e)
            {
                if (hotkeys.specialKeys[e.which] == 'return')
                {
                    BSC.UI.Ws.Chat.Room.SendMessage(e);
                    return false;
                }
                var text = "" + $(this).val();
                var profileLoggedIn = BSC.D.P.GetData();
                if (text.length == 0)
                {
                    fm.websync.client.publish({
                        channel: "/c/" + activeChannel,
                        data: {
                            event: "ntyping",
                            profile: {
                                id: profileLoggedIn.ID,
                                name: profileLoggedIn.Name,
                                gender: profileLoggedIn.Gender
                            }
                        },
                        onSuccess: function(args) { hasSentIsTyping = false; /*alert('Published!');*/ },
                        onFailure: function(args) { hasSentIsTyping = false; /*alert('Publish failed: ' + args.error);*/ }
                    });
                }
                else if (!hasSentIsTyping)
                {
                    fm.websync.client.publish({
                        channel: "/c/" + activeChannel,
                        data: {
                            event: "typing",
                            profile: {
                                id: profileLoggedIn.ID,
                                name: profileLoggedIn.Name,
                                gender: profileLoggedIn.Gender
                            }
                        },
                        onSuccess: function(args) { hasSentIsTyping = true; /*alert('Published!');*/ },
                        onFailure: function(args) { hasSentIsTyping = false; /*alert('Publish failed: ' + args.error);*/ }
                    });
                }

            });
            //$("#" + guid).bind('keydown', 'return', BSC.UI.Ws.Chat.Room.SendMessage);
            $("#" + guid + "_content").addClass("chat");


            SubscribeToChat(activeChannel);
            // Load chat details
            if (activeChannel.indexOf("public") == 0)
            {
                var lCode = BSC.D.P.GetData("LanguageCode");
                var lChannel = (activeChannel.indexOf("public-") == 0) ? 'public' : 'public-' + lCode;
                var name = (activeChannel.indexOf("public-") == 0) ? 'Public (' + lCode + ')' : 'Public';

                chat[activeChannel] = { Name: name, Messages: [] };
                AddChat(activeChannel);

                if (false)
                {
                    name = (activeChannel.indexOf("public-") == 0) ? 'Public' : 'Public (' + lCode + ')';
                    SubscribeToChat(lChannel);
                    chat[lChannel] = { Name: name, Messages: [] };
                    AddChat(lChannel, true);
                }
            }
            else
            {
                if (!chat[activeChannel])
                {
                    BSC.D.AjaxPost("/chat/getdetails", { channel: activeChannel }, function(res)
                    {
                        // res :{Channel, Created, Id, LastUpdated, Messages, Name, Profiles, Scope }
                        chat[activeChannel] = res;

                        var ms = res.Messages;

                        chat[activeChannel].Messages = [];

                        for (i = ms.length - 1; i >= 0; i--)
                        {
                            var m = ms[i];

                            var date = eval(m.Created.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));
                            chat[activeChannel].Messages.push(message =
                            {
                                ID: BSC.U.NewGUID(),
                                ChatRoomID: activeChannel,
                                Target: null,
                                Text: m.Text,
                                Date: date,
                                Type: 0,
                                SenderID: m.Profile.ID,
                                SenderPicture: m.Profile.PictureID,
                                SenderName: m.Profile.Name,
                                SenderCountryCode: m.Profile.CountryCode,
                                SenderGender: m.Profile.Gender,
                                SenderStatus: 1,
                                SenderLanguageCode: m.Profile.LanguageCode
                            });
                        }


                        AddChat(activeChannel);
                        RenderChatMessages(activeChannel);
                    }, "json", current);
                }
            }

            // $("#" + guid + "_chatcontainer").stop().scrollTo($("#" + guid + "_chatcontainer div.section:last"));
        };

        var LoadProfileList = function(p1, p2)
        {
            var channel = "" + p1;
            var profile = p2; // {id, gender, name}

            if (channel != activeChannel) return;

            if (channel.indexOf("/c/") < 0)
                channel = "/c/" + channel;

            BSC.D.AjaxGet("/chat/getprofiles", { channel: channel }, function(html)
            {
                $("#" + current + "_profileitems").html(html);
                // Add To List if not in list
                if (profile && $("#cp_" + profile.id).length == 0)
                {
                    var genderClass = (profile.gender == 1) ? "male" : "female";
                    $("#" + current + "_profileitems").prepend("<li id=\"cp_" + profile.id + "\"><a href=\"/" + profile.id + "\"><span class=\"title " + genderClass + "\">" + profile.name + "</span><span class=\"arrowright\"></span></a></li>");
                }
            }, "html", current);
        }
        
        var RenderChatMessages = function(channel, p1)
        {
            $("#" + current + "_chatcontainer").html("");
            var ml = chat[channel].Messages.length;
            for (i = 0; i < ml; i++)
            {
                RenderChatMessage(current, chat[channel].Messages[i], p1);
            }
        };



        var RenderChatMessage = function(p1, p2, p3)
        {
            var guid = p1;
            var message = p2;
            var html = GenerateHtmlMessage(message);
            $("#" + guid + "_chatcontainer").append(html);

            if (message.Type == 0 && !p3)
            {
                google.language.detect(message.Text, function(result)
                {
                    if (!result.error && result.language && result.language != BSC.D.P.GetData("LanguageCode") && ("" + result.language).trim() != "undefined")
                    {
                        var l = result.language;
                        google.language.translate(message.Text, result.language, BSC.D.P.GetData("LanguageCode"),
                        function(result)
                        {
                            if (result.translation)
                            {
                                $("#" + message.ID + "_message").append("<p class=\"translation\"><span style=\"color:silver;\">" + l + " » " + BSC.D.P.GetData("LanguageCode") + ":</span> " + result.translation + "</p>");

                                if (scrollTimer)
                                    clearTimeout(scrollTimer);

                                if (scrollToBottom)
                                {
                                    scrollTimer = setTimeout(function()
                                    {
                                        $("#" + current + "_chatcontainer").stop().scrollTo($("#" + current + "_chatcontainer div.section:last"));
                                    }, 200);
                                }
                            }
                        });
                    }
                });
            }


            //            if (!p3)
            //                BSC.E.MapHrefs();

            if (scrollTimer)
                clearTimeout(scrollTimer);

            if (scrollToBottom)
            {
                scrollTimer = setTimeout(function()
                {
                    $("#" + current + "_chatcontainer").stop().scrollTo($("#" + current + "_chatcontainer div.section:last"));
                }, 200);
            }

            BSC.E.MapHrefs();
        };

        var GenerateHtmlMessage = function(message)
        {
            var html = "";
            switch (message.Type)
            {
                case 10: // Profile Join
                case 20: // Profile Leave
                    html = BSC.D.Ts.Get("Chat.SystemMessageBox");
                    break;
                default:
                    html = BSC.D.Ts.Get("Chat.MessageBox");
                    break;
            }


            var messageToRender = message.Text.replace(/\</ig, "&lt;");
            messageToRender = messageToRender.replace(/\>/ig, "&gt;");

            messageToRender = MergeEmoticonToMessage(messageToRender);

            var now = (new Date()).format("yyyy-mm-dd");

            var date = message.Date;  //new Date();
            var dd = date.getDate();
            var isSameDate = ((new Date()).format("yyyy-mm-dd") == (date.format("yyyy-mm-dd")));
            var MM = parseInt(date.getMonth()) + 1; MM = (MM < 10) ? "0" + MM : MM;
            var YYYY = date.getFullYear();
            var hh = date.getHours();
            var mm = date.getMinutes(); mm = (mm < 10) ? "0" + mm : mm;
            var displayTime = (isSameDate) ? date.format("HH:MM") : date.format("yyyy-mm-dd @ HH:MM");

            var gender = (message.SenderGender == 1) ? "male" : "female";
            html = html.replace(/\{gender\}/ig, gender);
            html = html.replace(/\{profilename\}/ig, message.SenderName);
            if (!messageToRender || messageToRender.length == 0) return;
            html = html.replace(/\{profileid\}/ig, message.SenderID);
            html = html.replace(/\{message\}/ig, messageToRender);
            html = html.replace(/\{datetime\}/ig, displayTime);
            html = html.replace(/\{id\}/ig, message.ID);

            return html;
        };

        var MergeEmoticonToMessage = function(p1)
        {
            var text = p1;

            //            var list = [
            //                            { codes: [":)", ":-)"], regex: [/\:\)/ig, /\:\-\)/ig], file: "laugh.png" }
            //                       ];

            //            var l = list.length;
            //            for (i = 0; i < l; i++)
            //            {
            //                var el = list[i];
            //                var lcodes = el.codes.length;
            //                for (j = 0; j > lcodes; j++)
            //                {
            //                    text = text.replace(el.regex[j], "<img src=\"/beautifulpeoplecdn/images/icons/smileys/"+el.file+"\" style=\"width:18px; height:18px;\" />"); // :-)
            //                }
            //            }
            return text;
        };


        var BlinkTab = function(guid, channel)
        {
            if (activeChannel == channel) return;
            if (blinkTimers[channel]) return;

            blinkTimers[channel] = setInterval(function()
            {
                for (tabid in blinkTimers)
                {
                    var addColor = ($("#" + tabid + "_tab").hasClass("blue")) ? "orange" : "blue";
                    var removeColor = ($("#" + tabid + "_tab").hasClass("blue")) ? "blue" : "orange";
                    $("#" + tabid + "_tab").fadeTo(250, 1, function()
                    {
                        $("#" + tabid + "_tab").removeClass(removeColor).addClass(addColor);
                    });
                }
            }, 500);
        };

        var SetIsTyping = function(profile)
        {
            if ($("#chat_nowtyping a").length == 0) $("#chat_nowtyping").html("Now typing: ");
            var genderClass = (profile.gender == 1) ? "male" : "female";
            if ($("#typing_" + profile.id).length == 0)
                $("#chat_nowtyping").append(" <a id=\"typing_" + profile.id + "\" class=\"" + genderClass + "\">" + profile.name + "</a>");
        };

        var SetIsNotTyping = function(profile)
        {
            $("#typing_" + profile.id).remove();
            if ($("#chat_nowtyping a").length == 0) $("#chat_nowtyping").html("");
        };

        var AddTab = function(channel)
        {
            var guid = current;
            var html = BSC.D.Ts.Get("TabItem");

            if (chat[channel] && $("#" + channel + "_tab").length == 0)
            {
                var selected = (!BSC.UI.Ws.Get(guid).showtabs) ? " selected" : "";
                var tabHtml = html;
                tabHtml = tabHtml.replace(/\{listclass\}/ig, "id=\"" + channel + "_tab\" class=\"blue main" + selected + "\"");
                tabHtml = tabHtml.replace(/\{linkclass\}/ig, "class=\"first\"");
                tabHtml = tabHtml.replace(/\{title\}/ig, "" + chat[channel].Name);
                $("#" + guid + "_tabs_content_ul").append(tabHtml);
                $("#" + channel + "_tab span").after("<span id=\"" + channel + "_close\" class=\"close\"></span>");
                $("#" + guid + "_tabs_content_ul a").removeAttr('href');

                BSC.UI.Ws.Get(guid).showtabs = true;
                BSC.UI.W.SetTabs(guid);
            }
        };

        var AddChat = function(channel, noblick)
        {
            // Add tab
            if (chat[channel]) //  && activeChannel.indexOf("public") == 0
            {
                AddTab(channel);
                if (!noblick)
                    BlinkTab(current, channel);
            }
            else if (!chat[channel])
            {
                SubscribeToChat(channel);
                BSC.D.AjaxPost("/chat/getdetails", { channel: channel }, function(res)
                {
                    chat[channel] = res;

                    var ms = res.Messages;

                    chat[channel].Messages = [];

                    for (i = ms.length - 1; i >= 0; i--)
                    {
                        var m = ms[i];
                        var date = eval(m.Created.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));
                        chat[channel].Messages.push(message =
                            {
                                ID: BSC.U.NewGUID(),
                                ChatRoomID: channel,
                                Target: null,
                                Text: m.Text,
                                Date: date,
                                Type: 0,
                                SenderID: m.Profile.ID,
                                SenderPicture: m.Profile.PictureID,
                                SenderName: m.Profile.Name,
                                SenderCountryCode: m.Profile.CountryCode,
                                SenderGender: m.Profile.Gender,
                                SenderStatus: 1,
                                SenderLanguageCode: m.Profile.LanguageCode
                            });
                    }


                    AddTab(channel);
                    BlinkTab(current, channel);
                }, "json", current);
                return;
            }

            if (channel != activeChannel)
                BlinkTab(current, channel);
        };

        var ChangeChat = function(channel)
        {
            $("#" + current + "_tabs_content_ul li.selected").removeClass("selected");
            $("#" + channel + "_tab").addClass("selected");

            activeChannel = channel;

            // Change Uri
            BSC.UI.Ws.Get(current).uri = "/chat/room/" + channel;
            BSC.P.ChangeURI(BSC.UI.Ws.Get(current).uri);

            LoadProfileList(channel, { id: BSC.D.P.GetData("ID"), gender: BSC.D.P.GetData("Gender"), name: BSC.D.P.GetData("Name") });
            RenderChatMessages(channel);

            BSC.UI.W.Focus(current);
        };

        var BlinkDocTitle = function(newTitle)
        {
            //            var oldTitle = document.title;
            //            var msg = newTitle;
            //            var timeoutId = setInterval(function()
            //            {
            //                document.title = document.title == msg ? ' ' : msg;
            //            }, 1000);
            //            window.onmousemove = function()
            //            {
            //                clearInterval(timeoutId);
            //                document.title = oldTitle;
            //                window.onmousemove = null;
            //            };
        };

        var UnsubscribeChats = function()
        {
            if (chats.length == 0) return;

            var room = chats.pop();
            fm.websync.client.unsubscribe({
                channel: '/c/' + room,
                ext: { ticketid: BSC.D.P.GetData("TicketID") },
                onSuccess: function(args) { /*chats.push(room);*/ },
                onFailure: function(args) { alert('Error unsubscribing to room (' + room + '!'); }
            });
            if (chats.length > 0)
                setTimeout(UnsubscribeChats, 0);
        };

        var CloseChat = function(channel)
        {
            var guid = current;
            // UI
            $("#" + channel + "_tab").remove();

            delete chat[channel];

            if ($("#" + guid + "_tabs_content_ul li").length == 0)
            {
                setTimeout(UnsubscribeChats, 0);
                BSC.UI.W.Close(guid);
                return;
            }

            // Change chat
            if (channel == activeChannel)
            {
                var nextChannel = (($("#" + guid + "_tabs_content_ul li:first")[0].id).split("_"))[0];
                ChangeChat(nextChannel);
            }
        };

        //************************************************
        //************************************************
        // Public
        //************************************************
        //************************************************

        var unbind = function(guid)
        {
            setTimeout(UnsubscribeChats, 0);

            //chats = [];
            chat = {};
            current = null;
            activeChannel = null;
            hasSentIsTyping = false;

            $("#" + guid + "_chatcontainer").unbind('mousewheel');
        };


        var bind = function(guid)
        {
            hasSentIsTyping = false;
            var w = BSC.UI.Ws.Get(guid);
            var channel = w.data.id;

            //            $("#" + guid + "_chatcontainer").scroll(function()
            //            {
            //                // hide the arrow
            //                //alert($("#" + guid + "_chatcontainer div:last").offset().top + " == " + $(this).scrollTop());
            //            });

            $("#" + guid + "_profileitems").unbind().bind("click", guid, function(e)
            {
                BSC.E.Stop(e);
                var guid = e.data;
                var el = BSC.E.GetElement(e, "ul", "a");
                if (!el.id) return false;

                var href = $(el).attr("href");
                GO(href);
                return false;
            });

            $("#" + guid + "_chatcontainer").unbind().bind("click", guid, function(e)
            {
                BSC.E.Stop(e);
                var guid = e.data;
                var el = BSC.E.GetElement(e, "ul", "a");
                if (!el.id) return false;
                if (!$(el).hasClass("profile")) return false;

                var href = $(el).attr("href");
                GO(href);
                return false;
            });

            if (current != null)
            {
                AddChat(channel);
                return;
            }

            activeChannel = channel;
            Init(guid);


        };



        var parseData = function(args)
        {
            var guid = current;
            var channel = args.channel.replace(/\/c\//i, "");
            var data = args.data;

            var messageType = 0;
            var text = "";
            var renderMessage = false;
            switch (data.event)
            {
                case "typing":
                    SetIsTyping(args.data.profile);
                    break;
                case "ntyping":
                    // chat_nowtyping
                    SetIsNotTyping(args.data.profile);
                    break;
                case "unsubscribe":
                    if (args.data.profile.id == BSC.D.P.GetData("ID")) return;

                    LoadProfileList(channel);
                    messageType = 20;
                    text = "has left the chat";
                    renderMessage = true;
                    SetIsNotTyping(args.data.profile);
                    break;
                case "subscribe":
                    if (args.data.profile.id == BSC.D.P.GetData("ID")) return;

                    LoadProfileList(channel, args.data.profile);
                    messageType = 10;
                    text = "has joined the chat";
                    renderMessage = true;
                    break;
                case "message":
                    messageType = 0;
                    text = args.data.text;
                    renderMessage = true;
                    SetIsNotTyping(args.data.profile);
                    break;
            }

            if (renderMessage)
            {
                var message =
                {
                    ID: BSC.U.NewGUID(),
                    ChatRoomID: channel,
                    Target: null,
                    Text: text,
                    Date: new Date(),
                    Type: messageType,
                    SenderID: args.data.profile.id,
                    SenderPicture: args.data.profile.picture,
                    SenderName: args.data.profile.name,
                    SenderCountryCode: args.data.profile.cc,
                    SenderGender: args.data.profile.gender,
                    SenderStatus: 1,
                    SenderLanguageCode: args.data.languagecode
                };


                if (activeChannel == channel)
                {
                    BSC.P.PlaySound("click");
                    RenderChatMessage(current, message);

                    if (chat[channel] && channel.indexOf("public") == 0)
                        chat[channel].Messages.push(message);
                }
                else
                {
                    BSC.P.PlaySound("notice");
                    if (chat[channel])
                        chat[channel].Messages.push(message);
                    BlinkTab(guid, channel);
                    BlinkDocTitle("New chat message from " + args.data.profile.name);
                }
            }
            BSC.E.MapHrefs();
        }

        var sendMessage = function(e)
        {
            e.stopPropagation();
            e.preventDefault();

            var guid = current;
            hasSentIsTyping = false;
            var text = ("" + $("#" + guid + '_chatmsg').val()).trim();
            $("#" + guid + '_chatmsg').val("");

            if (text.length == 0)
            {
                $("#" + guid + '_chatmsg').trigger("focus");
                alert("Please enter some text");
                return false;
            }

            var profileLoggedIn = BSC.D.P.GetData();
            var message =
                {
                    ID: BSC.U.NewGUID(),
                    ChatRoomID: activeChannel,
                    Target: null,
                    Text: text,
                    Date: new Date(),
                    Type: 0,
                    SenderID: profileLoggedIn.ID,
                    SenderPicture: profileLoggedIn.PictureID,
                    SenderName: profileLoggedIn.Name,
                    SenderCountryCode: profileLoggedIn.CountryCode,
                    SenderGender: profileLoggedIn.Gender,
                    SenderStatus: 1,
                    SenderLanguageCode: profileLoggedIn.LanguageCode
                };
            RenderChatMessage(guid, message);
            chat[activeChannel].Messages.push(message);

            fm.websync.client.publish({
                channel: "/c/" + activeChannel,
                data: {
                    event: "message",
                    text: text,
                    date: new Date(),
                    language: profileLoggedIn.LanguageCode,
                    profile: {
                        id: profileLoggedIn.ID,
                        picture: profileLoggedIn.PictureID,
                        name: profileLoggedIn.Name,
                        cc: profileLoggedIn.CountryCode,
                        gender: profileLoggedIn.Gender,
                        lanuagecode: profileLoggedIn.LanguageCode
                    }
                },
                onSuccess: function(args) { /*alert('Published!');*/ },
                onFailure: function(args) { /*alert('Publish failed: ' + args.error);*/ }
            });

            //            if (activeChannel == "public")
            //            {
            //                chat[activeChannel + "-" + profileLoggedIn.LanguageCode].Messages.push(message);
            //                fm.websync.client.publish({
            //                    channel: "/c/" + activeChannel + "-" + profileLoggedIn.LanguageCode,
            //                    data: {
            //                        event: "message",
            //                        text: text,
            //                        date: new Date(),
            //                        language: profileLoggedIn.LanguageCode,
            //                        profile: {
            //                            id: profileLoggedIn.ID,
            //                            picture: profileLoggedIn.PictureID,
            //                            name: profileLoggedIn.Name,
            //                            cc: profileLoggedIn.CountryCode,
            //                            gender: profileLoggedIn.Gender,
            //                            lanuagecode : profileLoggedIn.LanguageCode
            //                        }
            //                    },
            //                    onSuccess: function(args) { /*alert('Published!');*/ },
            //                    onFailure: function(args) { /*alert('Publish failed: ' + args.error);*/ }
            //                });
            //            }
            //            else if (activeChannel.indexOf("public-") == 0)
            //            {
            //                chat["public"].Messages.push(message);
            //                fm.websync.client.publish({
            //                    channel: "/c/public",
            //                    data: {
            //                        event: "message",
            //                        text: text,
            //                        date: new Date(),
            //                        language: profileLoggedIn.LanguageCode,
            //                        profile: {
            //                            id: profileLoggedIn.ID,
            //                            picture: profileLoggedIn.PictureID,
            //                            name: profileLoggedIn.Name,
            //                            cc: profileLoggedIn.CountryCode,
            //                            gender: profileLoggedIn.Gender,
            //                            lanuagecode : profileLoggedIn.LanguageCode
            //                        }
            //                    },
            //                    onSuccess: function(args) { /*alert('Published!');*/ },
            //                    onFailure: function(args) { /*alert('Publish failed: ' + args.error);*/ }
            //                });
            //            }

            return false;
        };

        var onTabClick = function(e)
        {
            // Close
            var el = BSC.E.GetElement(e, "ul", "span");
            if (el.id && $(el).hasClass("close"))
            {
                var channel = (el.id.split("_"))[0];
                CloseChat(channel);
                //alert("close: " + channel);
                return;
            }

            var el = BSC.E.GetElement(e, "ul", "li");
            if (!el.id) return;
            // Reset GUI selected
            var channel = (el.id.split("_"))[0];

            if (blinkTimers[channel])
            {
                clearInterval(blinkTimers[channel]);
                delete blinkTimers[channel];
            }
            $("#" + channel + "_tab").removeClass("orange").addClass("blue");

            ChangeChat(channel);
        };

        var createPublicChat = function(p1)
        {
            var channel = p1;
            if (!BSC.D.P.IsLoggedIn())
            {
                BSC.UI.AlertLogin();
                return;
            }

            if (!BSC.D.P.IsPaying())
            {
                BSC.UI.AlertCurrentlyFREE();
                return;
            }

            if (current == null)
            {
                GO("/chat/room/" + channel);
                return;
            }

            chat[channel] = { Name: 'Public', Messages: [] };
            SubscribeToChat(channel);
            AddTab(channel);
            ChangeChat(channel);
        };
        var createPrivateChat = function(p1)
        {
            var profileKey = p1;

            if (!BSC.D.P.IsLoggedIn())
            {
                BSC.UI.AlertLogin();
                return;
            }

            if (!BSC.D.P.IsPaying())
            {
                BSC.UI.AlertCurrentlyFREE();
                return;
            }

            BSC.D.AjaxPost("/chat/invite", { profileid: p1 }, function(res)
            {
                if (res.Invitation && !res.Invitation.CanChat)
                {
                    alert("Profile unavailable for chat, send a mail instead");
                    return;
                }

                var channel = res.ID;

                if (current == null)
                {
                    GO("/chat/room/" + channel);
                    return;
                }
                if (!chat[channel])
                {
                    activeChannel = channel;
                    SubscribeToChat(activeChannel);
                    BSC.D.AjaxPost("/chat/getdetails", { channel: channel }, function(res)
                    {
                        chat[channel] = res;

                        var ms = res.Messages;

                        chat[channel].Messages = [];

                        for (i = ms.length - 1; i >= 0; i--)
                        {
                            var m = ms[i];
                            var date = eval(m.Created.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));
                            chat[channel].Messages.push(message =
                            {
                                ID: BSC.U.NewGUID(),
                                ChatRoomID: channel,
                                Target: null,
                                Text: m.Text,
                                Date: date,
                                Type: 0,
                                SenderID: m.Profile.ID,
                                SenderPicture: m.Profile.PictureID,
                                SenderName: m.Profile.Name,
                                SenderCountryCode: m.Profile.CountryCode,
                                SenderGender: m.Profile.Gender,
                                SenderStatus: 1,
                                SenderLanguageCode: m.Profile.LanguageCode
                            });
                        }

                        AddTab(channel);

                        // Goto tab
                        ChangeChat(channel);
                    }, "json", current);
                    return;

                }
                else
                {
                    ChangeChat(channel);
                }
                return false;
            }, "json");
        };

        var incommingChatInvitation = function(p1)
        {
            var channel = p1;

            if (!BSC.D.P.IsLoggedIn())
            {
                BSC.UI.AlertLogin();
                return;
            }

            if (current == null)
            {
                GO("/chat/room/" + channel);
                return;
            }
            AddChat(channel);
        };

        return {
            Bind: bind,
            Unbind: unbind,
            //UnsubscribeChat : unsubscribeChat,
            SendMessage: sendMessage,
            OnTabClick: onTabClick,
            CreatePrivateChat: createPrivateChat,
            CreatePublicChat: createPublicChat,
            IncommingChatInvitation: incommingChatInvitation,
            ParseData: parseData,
            GetActiveChats: function()
            {
                return chats ? chats : [];
            }
        };
    } ();
})();

//BSC.E.Subscribe("load", BSC.UI.Ws.Chat.Room.Load, null, "chat.room");
BSC.E.Subscribe("bind", BSC.UI.Ws.Chat.Room.Bind, null, "chat.room");
BSC.E.Subscribe("unbind", BSC.UI.Ws.Chat.Room.Unbind, null, "chat.room");


