﻿/// <reference path="~/Scripts/IntelliSense/Intellisense.js" />

(function()
{
    BSC.Require("BSC.UI.Ws");
    BSC.UI.Ws.Mail = function()
    {
        var tables = [];
        var selectedMails = {};
        var pagenumber = 1;
        var pagesize = 200;
        var pagemax = 0;
        var mailsinbox = {};
        var readchecked = false;
        var unreadchecked = false;
        var allselected = false;
        var page;
        var localcache = {};
        var current = null;

        var load = function(guid)
        {
            current = guid;
            var w = BSC.UI.Ws.Get(guid);
            LoadMails(guid, w.page);
        };

        var bind = function(p1)
        {
            var guid = p1;

            $("#" + guid + "_mailselect").bind("change", { guid: guid }, BSC.UI.Ws.Mail.OnSelectClick);
            $("#" + guid + "_mailfolders dl").bind("click", guid, BSC.UI.Ws.Mail.OnFolderClick);

            if(!localcache[guid]) localcache[guid] = {unreadmailcount:0};
            BSC.UI.Ws.Mail.UpdateMailCount($("#" + guid + "_mails table.mail.unread").length);
        };


        var unbind = function(p1)
        {
            var guid = p1;
            current = null;
            //If delete and mark button is binded
            DisableActions(guid);
            $("#" + guid + " a").unbind();
            $("#" + guid + " ul").unbind();
            $("#" + guid + " div").unbind();
            delete localcache[guid];
        };

        var reload = function(p1)
        {
            var guid = p1;
            LoadMails(guid);
        };

        var LoadMails = function(p1)
        {
            var guid = p1;
            var w = BSC.UI.Ws.Get(guid);

            $("#" + guid + "_content").scrollTo({ top: 0 }, 200);

            $("#" + guid + "_maillist").unbind();
            $("#" + guid + "_loader").show();
            $("#" + guid + "_mails").html("");

            var date = new Date();

            var data = {
                avoidcachingie: new Date(),
                contentOnly: true
            };
            BSC.D.AjaxGet(w.uri, data, function(res)
            {
                $("#" + guid + "_mails").html(res).show();
                $("#" + guid + "_maillist").bind("click", guid, BSC.UI.Ws.Mail.OnMailClick);
                $("#" + guid + "_loader").hide();

                // Parse json data
                var json = $("#" + guid + "_json_list").getValue();
                var data = BSC.D.JSON.Parse(json);
                if (data)
                {
                    BSC.UI.Ws.Mail.UpdateMailCount(data.unread);
                }

                return false;
                //					BSC.UI.HideStatus(guid, 200);
            }, "html", guid);
        };

        var onFolderClick = function(e)
        {
            var guid = e.data;
            var el = BSC.E.GetElement(e, "ul", "a");

            var title = $(el).text();
            var href = $(el).attr("href");
            href = (href).replace(/http:\/\/[^\/]+/i, "");
            BSC.UI.Ws.Get(guid).path = href;
            BSC.UI.Ws.Get(guid).cleanpath = href;
            BSC.UI.Ws.Get(guid).uri = href;
            BSC.P.ChangeURI(href);
            BSC.P.SetTitle(guid, title);

            $("#" + guid + "_mailfolders").removeClass().addClass("mailfolders " + el.className);
            $("#" + guid + "_header").html("" + title);

            LoadMails(guid);

            return false;
        };

        var onMailClick = function(e)
        {
            var guid = e.data;
            var el = BSC.E.GetElement(e, "ul", "li");
            var t = (el.id).split("_");
            // var guid = t[1];
            var id = t[2];
            var acl = el.className;

            if (e.target.nodeName.toLowerCase() == "input")
            {
                if ($("#mail_" + guid + "_" + id + " table.mail INPUT[type='checkbox']").attr('checked'))
                    $("#mail_" + guid + "_" + id + " table.mail").addClass("selected");
                else
                    $("#mail_" + guid + "_" + id + " table.mail").removeClass("selected");

                if ($("#" + guid + "_mails li table.selected").length > 0)
                    EnableActions(guid);
                else
                    DisableActions(guid);

                return;
            }

            if (e.target.nodeName.toLowerCase() == "img")
            {
                var el2 = BSC.E.GetTarget(e);
                if (el2.id == "00000000-0000-0000-0000-000000000000") return;

                GO("/" + el2.id);
                return;
            }

            if (!BSC.D.P.IsLoggedIn())
            {
                BSC.UI.AlertLogin();
                return false;
            }
            else if (!BSC.D.P.IsPaying())
            {
                BSC.UI.AlertCurrentlyFREE();
                return false;
            }

            // if unread mail
            var unreadmail = $("#mail_" + guid + "_" + id + " table.mail.unread");
            var length = unreadmail.length;
            if (unreadmail.length > 0)
            {
                if (unreadmail.length > 0)//localcache[guid].unreadmailcount
                {
                    localcache[guid].unreadmailcount--;
                    BSC.UI.Ws.Mail.UpdateMailCount(localcache[guid].unreadmailcount);
                }
                else
                    BSC.UI.Ws.Mail.UpdateMailCount(0); 
                    
                $("#mail_" + guid + "_" + id + " table.mail").removeClass("unread");
                $("#mail_" + guid + "_" + id + " table.mail").addClass("read");
            }

            GO("/mail/read/?id=" + id);
            BSC.P.ChangeURI("/mail/read/?id=" + id);

            return false;
        };

        var EnableActions = function(p1)
        {
            var guid = p1;
            $("#" + guid + "_body div.inboxaction a.tag").css('color', '');
            $("#" + guid + "_body div.inboxaction a.tag").click(BSC.UI.Ws.Mail.OnMailActionClick);
        };

        var DisableActions = function(p1)
        {
            var guid = p1;
            $("#" + guid + "_body div.inboxaction a.tag").css("color", "#ACA899");
            $("#" + guid + "_body div.inboxaction a.tag").unbind();
        };

        var onSelectClick = function(e)
        {
            var read = null;
            var el = BSC.E.GetTarget(e);
            var guid = e.data.guid;


            if (el.value === "selectall")
            {
                $("#" + guid + "_mails INPUT[type='checkbox']").attr('checked', true);
                $("#" + guid + "_mails li table").addClass("selected");
            } else if (el.value === "selectnone")
            {
                $("#" + guid + "_mails INPUT[type='checkbox']").attr('checked', false);
                $("#" + guid + "_mails li table").removeClass("selected");
            } else if (el.value === "selectread")
            {
                // Remove
                $("#" + guid + "_mails li table INPUT[type='checkbox']").attr('checked', false);
                $("#" + guid + "_mails li table").removeClass("selected");

                $("#" + guid + "_mails li table.read INPUT[type='checkbox']").attr('checked', true);
                $("#" + guid + "_mails li table.read").addClass("selected");
            } else if (el.value === "selectunread")
            {
                // Remove
                $("#" + guid + "_mails li table INPUT[type='checkbox']").attr('checked', false);
                $("#" + guid + "_mails li table").removeClass("selected");

                $("#" + guid + "_mails li table.unread INPUT[type='checkbox']").attr('checked', true);
                $("#" + guid + "_mails li table.unread").addClass("selected");
            }
            if ($("#" + guid + "_mails li table.selected").length > 0)
                EnableActions(guid);
            else
                DisableActions(guid);

            return;
        };

        var onMailActionClick = function(e)
        {
            var el = BSC.E.GetElement(e, "div", "a");
            var t = (el.id).split("_");
            var guid = t[0];
            var action = t[1];
            var param = t[2];

            if (action == "deletetag")
                Delete(guid);
            else if (action == "markas")
                ServerMarkAs(guid, param);
        };

        var ServerMarkAs = function(p1, p2)
        {
            var guid = p1;
            var markAsRead = (p2 == "read");
            var mails = $("#" + guid + "_mails li table.selected");
            var ml = mails.length
            var mailsToChange = [];
            for (i = 0; i < ml; i++)
            {
                var m = mails[i];
                var t = (m.id).split("_");
                var id = t[1];
                mailsToChange.push(id);
                if (markAsRead)
                    $("#" + guid + "_mails li table#mail_" + id + "").removeClass("unread");
                else
                    $("#" + guid + "_mails li table#mail_" + id + "").addClass("unread");
            }

            $("#" + guid + "_mails input[type='checkbox']").attr('checked', false);
            $("#" + guid + "_mails li table").removeClass("selected");

            var p = new BSC.D.Param("BSC.WS.JS.Mail.ChangeMail");
            p.Add("MailIDs", mailsToChange);
            p.Add("Read", markAsRead);
            BSC.UI.ShowStatus(guid, "Saving...");
            BSC.D.Send(p, "Content.Mail", "MarkAs", function(res)
            {
                if (res.d.success)
                {
                    BSC.UI.Ws.Mail.UpdateMailCount(parseInt(res.d.message));
                }
                BSC.UI.HideStatus(guid);
            });
        };

        var Delete = function(p1)
        {
            var guid = p1;
            var mailsToChange = [];

            var mails = $("#" + guid + "_mails li table.selected");
            var ml = mails.length

            for (i = 0; i < ml; i++)
            {
                var m = mails[i];
                var t = (m.id).split("_");
                var id = t[1];
                mailsToChange.push(id);
                $("#mail_" + guid + "_" + mailsToChange[i]).fadeOut(400, function() { $(this).remove(); });
            }
            if ($("#" + guid + "_mails li").length == 0)
            {
                $("#" + guid + "_mails").html("<div class=\"nomails\">No Mails in this folder</div>");
            }

            var param = new BSC.D.Param("BSC.WS.JS.Mail.DeleteMail");
            param.Add("MailIDs", mailsToChange);
            BSC.UI.ShowStatus(guid, "Deleting...");
            BSC.D.Send(param, "Content.Mail", "DeleteMail", function(res)
            {
                if (res.d.success)
                {
                    BSC.UI.Ws.Mail.UpdateMailCount(parseInt(res.d.message));
                }
                BSC.UI.HideStatus(guid);
            });
        };


        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,

            /// <summary></summary>
            /// <param name="data"></param>
            /// <return></return>
            OnMailClick: onMailClick,

            /// <summary></summary>
            /// <param name="data"></param>
            /// <return></return>
            OnFolderClick: onFolderClick,

            /// <summary></summary>
            /// <param name="data"></param>
            /// <return></return>
            OnSelectClick: onSelectClick,

            /// <summary></summary>
            /// <param name="data"></param>
            /// <return></return>
            OnMailActionClick: onMailActionClick,

            ReFreshFolderlist: function()
            {
                if (current)
                    LoadMails(current);
            },

            UpdateMailCount: function(count)
            {
                var guid = current;

                if (!count || count == "undefined") count = 0;


                if (!localcache[guid])
                    localcache[guid] = { unreadmailcount: count };
                else
                    localcache[guid].unreadmailcount = count;

                if (count == 0)
                {
                    $("#badge_mail").hide();
                    $("span.unreadmailcount").html("");
                    return;
                }
                $("span.unreadmailcount").html("(" + count + ")");
                $("#badge_mail").html(count).show();

            },

            ApplicantCantComposeMail: function()
            {
                BSC.UI.Alert("Ok", null, "Please note.", "During your 48 hour application period (while your profile is being rated) you can not write messages to other members.", null, null, "info");
                return false;
            }
        };
    } ();
})();

BSC.E.Subscribe("load", BSC.UI.Ws.Mail.Load, null, "mail");
BSC.E.Subscribe("bind", BSC.UI.Ws.Mail.Bind, null, "mail");
BSC.E.Subscribe("unbind", BSC.UI.Ws.Mail.Unbind, null, "mail");

BSC.E.Subscribe("load", BSC.UI.Ws.Mail.Load, null, "mail.inbox");
BSC.E.Subscribe("bind", BSC.UI.Ws.Mail.Bind, null, "mail.inbox");
BSC.E.Subscribe("unbind", BSC.UI.Ws.Mail.Unbind, null, "mail.inbox");

BSC.E.Subscribe("load", BSC.UI.Ws.Mail.Load, null, "mail.sent");
BSC.E.Subscribe("bind", BSC.UI.Ws.Mail.Bind, null, "mail.sent");
BSC.E.Subscribe("unbind", BSC.UI.Ws.Mail.Unbind, null, "mail.sent");

BSC.E.Subscribe("load", BSC.UI.Ws.Mail.Load, null, "mail.deleted");
BSC.E.Subscribe("bind", BSC.UI.Ws.Mail.Bind, null, "mail.deleted");
BSC.E.Subscribe("unbind", BSC.UI.Ws.Mail.Unbind, null, "mail.deleted");

BSC.E.Subscribe("load", BSC.UI.Ws.Mail.Load, null, "mail.unread");
BSC.E.Subscribe("bind", BSC.UI.Ws.Mail.Bind, null, "mail.unread");
BSC.E.Subscribe("unbind", BSC.UI.Ws.Mail.Unbind, null, "mail.unread");

BSC.E.Subscribe("load", BSC.UI.Ws.Mail.Load, null, "mail.virtual");
BSC.E.Subscribe("bind", BSC.UI.Ws.Mail.Bind, null, "mail.virtual");
BSC.E.Subscribe("unbind", BSC.UI.Ws.Mail.Unbind, null, "mail.virtual");


(function()
{
    BSC.UI.Ws.Mail.Compose = function()
    {
        /// <summary>Private: Local localcache to hold temporary information, while window is open</summary>
        var localcache = {};
        var current = null;
        var friends = {};
        /// <summary>Private: Filter profiles from profiles friendslist by name</summary>
        /// <param name="element">Current element in array</param>
        /// <param name="index">Number og current element in array</param>
        /// <param name="array">Full Array</param>
        /// <return>True if some profile name contains query</return>
        var Contains = function(element, index, array)
        {
            var q = this.q.toLowerCase();
            var username = element.Name.toLowerCase();
            for (key in this.sel)
            {
                if (key === element.ID)
                    return false;
            }
            return (username.indexOf(q) > -1);
        };

        /// <summary>Private: Display infobox then user click in to field</summary>
        /// <param name="guid">Windows UI Identifier</param>
        /// <param name="text">Text to displayed</param>
        var ShowInfo = function(guid, text)
        {
            $("#" + guid + "_searchresult dd").remove();
            var win = BSC.UI.Ws.Get(guid);
            var h = parseInt($("#" + guid + "_to").css("height")); if (isNaN(h)) { try { h = parseInt($("#" + guid + "_to")[0].clientHeight) } catch (ee) { } }
            var w = parseInt($("#" + guid + "_to").css("width")); if (isNaN(w)) { try { w = parseInt($("#" + guid + "_to")[0].clientHeight) } catch (ee) { } }
            w = w + 16;
            var divToPos = $("#" + guid + "_to").offset();
            var newLeft = divToPos.left - win.left - 16;
            var newTop = divToPos.top - win.top - h - 37;
            var uilist = $("#" + guid + "_searchresult");
            var totalWidth = parseInt($("#" + guid + "_td_searchresult").css("width"));
            if (isNaN(totalWidth)) totalWidth = parseInt($("#" + guid + "_td_searchresult").attr("scrollWidth"));
            uilist.css({ display: 'block', top: -3, left: -2, width: (totalWidth) });

            SetInputWidth(guid);

            var dd = $("<dd class=\"info\"></dd>");
            var t = BSC.D.Ts.Get("ComposeSearchInfo");
            t = t.replace(/\{info\}/i, text);
            t = t.replace(/\{id\}/i, guid);
            dd.html(t);
            uilist.append(dd);

            // Bind Profile Search click
            $("a#" + guid + "_profilesearch").bind("click", { guid: guid }, BSC.UI.Ws.Mail.Compose.OnProfileSearchClick);
        };

        /// <summary>Public: Called when user type in the to field, performs search</summary>
        /// <param name="e">Event</param>
        var hideInfo = function(e)
        {
            var guid = e.data;
            $("#" + guid).unbind('keypress', 'down').unbind('keypress', 'up').unbind('keypress', 'tab').unbind('keypress', 'Return').unbind('keypress', 'backspace');
            setTimeout(function()
            {
                $("#" + guid + "_searchresult").css({ display: 'none' });
            }, 300);

        };

        var SetInputWidth = function(guid)
        {
            //475 / 150 = 3 // 450
            //4 % 3 = 1
            //475 - (1*150) - 10
            //$("#" + guid + "_searchresult").css({ });
            //var totalWidth = parseInt($("#" + guid + "_tolistcontainer").css("width")) - 96;
            var totalWidth = parseInt($("#" + guid + "_td_searchresult").css("width"));
            if (isNaN(totalWidth)) totalWidth = parseInt($("#" + guid + "_td_searchresult").attr("scrollWidth"));
            var itemWidth = 150;
            var numberOfItems = localcache[guid].recipientcount;
            var itemPerRow = Math.floor(totalWidth / itemWidth);
            var widthLeft = totalWidth - 10 - (itemWidth * itemPerRow);
            var itemsOnLastRow = numberOfItems % itemPerRow;
            var widthLeft = totalWidth - 10 - (itemWidth * itemsOnLastRow);
            if (itemPerRow == itemsOnLastRow || itemsOnLastRow == 0)
                $("#" + guid + "_to").css("width", "97%");
            else
                $("#" + guid + "_to").css("width", widthLeft);

            return;


            //			if (totalWidth - (itemWidth * numberOfItems) > 150)
            //				$("#" + guid + "_to").css("width", totalWidth - (itemWidth * numberOfItems) - 10);
            //			else
            //				$("#" + guid + "_to").css("width", widthLeft);
            //			return;
            //			var dd = (localcache[guid].recipientcount * 150);
            //			var ss = ww - dd;
            //			if (ss < 150)
            //			{
            //				$("#" + guid + "_to").css("width", "97%");
            //			}
            //			else
            //			{
            //				$("#" + guid + "_to").css("width", ss - 10);
            //			}
        };

        /// <summary>Private: Search friends list by name</summary>
        /// <param name="guid">Window UI identifier</param>
        /// <param name="query">Profile name</param>
        var Search = function(guid, query)
        {
            if (!localcache[guid]) localcache[guid] = {};
            if (localcache[guid].searchTimer)
                clearTimeout(localcache[guid].searchTimer);

            if (query.length === 0)
            //BSC.T.Get("JS.BSC.UI.Ws.Mail.Search.TypeName")
                ShowInfo(guid, BSC.T.Get("JS.BSC.UI.Ws.Mail.Search.TypeName"));

            localcache[guid].searchTimer = setTimeout(function() { DoSearch(guid, query); }, 300);
        };

        /// <summary>Private: Delayed searched. Performf query in user has not typed in 3 miliseconds</summary>
        /// <param name="guid">Window UI identifier</param>
        /// <param name="query">Profile name</param>
        var DoSearch = function(guid, query)
        {
            var s = "";
            query = (!query) ? "" : "" + query;
            query = query.trim();

            var selected = (localcache[guid].recipient) ? localcache[guid].recipient : {};
            var contacts = BSC.D.P.GetContacts();

            if (query.length > 0)
            {
                if ($("#" + guid + "_searchresult").css("display") == "none") ShowInfo(guid, "");
                // Something is in query
                var result = contacts.filter(Contains, { q: query, sel: selected });
                if (result.length === 0)
                    ShowInfo(guid, BSC.T.Get("JS.BSC.UI.Ws.Mail.DoSearch.NonFound"));
                else
                {
                    ShowInfo(guid, "");
                    // Clear list
                    $("#" + guid + "_searchresult dd").remove();
                    // Sort query
                    result = result.objSort("Priority", "Name");
                    // Put result in list
                    var ll = Math.min(result.length, 6);
                    var uilist = $("#" + guid + "_searchresult");
                    for (i = 0; i < ll; i++)
                    {
                        var un = "" + result[i].Name;
                        un = un.replace(query.toLowerCase(), "<b>" + query.toLowerCase() + "</b>");
                        un = un.replace(query.toUpperCase(), "<b>" + query.toUpperCase() + "</b>");
                        var c = BSC.D.Ts.Get("ContactSearchItem");
                        c = c.replace(/\{pictureid\}/i, result[i].PictureID);
                        c = c.replace(/\{profileid\}/i, result[i].ID);
                        c = c.replace(/\{name\}/i, un);
                        c = c.replace(/\{alt\}/i, un);

                        var dd = $("<dd id=\"" + result[i].ID + "_dd\"></dd>");
                        if (i === 0)
                            dd.addClass("over");
                        dd.html(c);

                        //ResultList hover function 
                        dd.hover(function()
                        {
                            var s = $("#" + guid + "_searchresult dd.over");
                            s.removeClass("over");
                            $(this).addClass("over");
                        },
                        function()
                        {
                            $(this).removeClass("over");
                        })

                        uilist.append(dd);
                    }

                }
            }
        };

        /// <summary>Private: Send mail</summary>
        /// <param name="guid">Window UI identifier</param>
        var Sendmail = function(guid)
        {
            var profiles = [];
            var recipient = (localcache[guid].recipient) ? localcache[guid].recipient : {};
            var replyid = (localcache[guid].replyid) ? localcache[guid].replyid : null;
            for (recipientid in recipient)
            {
                profiles.push(recipientid);
            }

            // mail data
            var token = $("#" + guid + " input[name='__RequestVerificationToken']").val();
            var subject = $("input#" + guid + "_subject").val();
            var body = "" + BSC.U.CleanHtml($("textarea#" + guid + "_body").getValue());

            // Validating input data
            if (subject.length == 0)
            {
                BSC.UI.ShowHelpBubble(guid + "_subject", "info", BSC.T.Get("JS.BSC.UI.Ws.Mail.Sendmail.Title"), BSC.T.Get("JS.BSC.UI.Ws.Mail.Sendmail.Desc"));
                return false;
            }
            if (replyid)
                localcache[guid].replyid = null;

            var data =
            {
                __RequestVerificationToken: token,
                subject: subject,
                body: body,
                profiles: profiles,
                mailID: replyid
            };

            BSC.UI.Loader(guid);
            BSC.D.AjaxPost("/mail/send", data, function(res)
            {

                BSC.UI.HideLoader(guid);
                BSC.UI.W.CloseActive();
                BSC.UI.W.Close(guid);
            }, guid, "json");
        };

        /// <summary>Private: Cancel mail and closes window</summary>
        /// <param name="guid">Window UI identifier</param>
        var Cancelmail = function(guid)
        {
            // TODO: needs to check if user has enter some text, added profiles
            // ---> Promt user if user is sure about cancel mail
            BSC.UI.W.Close(guid);
        };

        /// <summary>Private: </summary>
        /// <param name="guid">Window UI identifier</param>
        /// <param name="id">Profile ID to added to recipient list</param>
        var AddContact = function(guid, id)
        {
            // Only one receipient then rating
//            if (!BSC.D.P.IsLoggedIn())
//            {
//                BSC.UI.AlertLogin();
//                return false;
//            }
//            else if (BSC.D.P.IsFullMember() && !BSC.D.P.IsPaying())
//            {
//                BSC.UI.AlertCurrentlyFREE();
//                return false;
//            }

            if (localcache[guid].recipient[id])
                return;

            // Reset search
            $("#" + guid + "_to").val("");
            $("#" + guid + "_searchresult dd").remove();
            $("#" + guid + "_searchresult").css({ display: 'none' });
            // Get profile
            var p = BSC.D.P.GetContact(id);
            // Add Profile
            var t = BSC.D.Ts.Get("ContactItem");
            if (p == null)
            {
                t = t.replace(/\{pictureid\}/ig, "systemmail.png");
            }
            else
            {
                t = t.replace(/\{name\}/ig, p.Name);
                t = t.replace(/\{alt\}/ig, p.Name);
                t = t.replace(/\{pictureid\}/ig, p.PictureID);
                t = t.replace(/\{profileid\}/ig, p.ID);
            }
            localcache[guid].recipientcount++;
            $("#" + guid + "_tolist").append(t);

            SetInputWidth(guid);

            localcache[guid].recipient[id] = 1;
            // Show list
            if (navigator.appVersion.indexOf("MSIE") > 0)
                $("#" + guid + "_rlist").css({ display: 'block' });
            else
                $("#" + guid + "_rlist").css({ display: 'table-row' });
        };

        /// <summary>Private: </summary>
        /// <param name="guid">Window UI identifier</param>
        /// <param name="id">Profile ID to removed from recipient list</param>
        var RemoveContact = function(guid, id)
        {
            var id = id;
            $("#" + id + "_item").fadeOut(150, function() { $("#" + id + "_item").remove(); SetInputWidth(guid); });
            delete localcache[guid].recipient[id];
            localcache[guid].recipientcount--;

            // Hide list
            if (localcache[guid].recipientcount == 0)
                setTimeout(function() { $("#" + guid + "_rlist").css("display", "none"); }, 150);
        };




        ///************************************************************************




        /// <summary>Public: Load mail data on window load</summary>
        /// <param name="guid">Window UI identifier</param>
        var load = function(p1)
        {
            var guid = p1;
            current = guid;
            localcache[guid] =
				{
				    recipient: {},
				    recipientcount: 0
				};

            var json = $("#" + guid + "_json").getValue();
            var data = BSC.D.JSON.Parse(json);
            if (data)
            {
                if (data.ID && data.ID != "00000000-0000-0000-0000-000000000000")
                    AddContact(guid, data.ID);
            }
            else
                $("#" + guid + "_tolist dd").remove();
            $("#" + guid + "_compose").css({ display: 'block' });

            if ((BSC.D.P.GetContacts()).length == 0)
            {
                BSC.D.P.LoadContacts(guid, function(res)
                {
                    //SetInputWidth(guid);
                });
            }

            //
            var w = BSC.UI.Ws.Get(guid);
            var jQ = BSC.U.ParseQuery(w.query);
            if (jQ.pid)
                AddContact(guid, jQ.pid);
        };

        /// <summary>Public: </summary>
        /// <param name="data"></param>
        var onResize = function(data)
        {
            SetInputWidth(data.guid);
        };

        /// <summary>Public: Bind events handlers to UI</summary>
        /// <param name="guid">Window UI identifier</param>
        var bind = function(p1)
        {
            var guid = p1;
            $("#" + guid + "_to")
				.bind("click", guid, BSC.UI.Ws.Mail.Compose.OnSearchEvent)
				.bind("keyup", guid, BSC.UI.Ws.Mail.Compose.OnSearchEvent)
				.bind("blur", guid, BSC.UI.Ws.Mail.Compose.HideInfo)
				.bind("focus", guid, function(e)
				{
				    var guid = e.data;
				    //Shortcut keys
				    $("#" + guid).bind('keypress', 'backspace', function(e)
				    {
				        var t = (this.id).split("_");
				        var guid = t[0];
				        var textLength = ($("#" + guid + "_to").getValue()).length;
				        if (textLength > 0) { return; }

				        // Remove Last Contact
				        var lastcontact = $("#" + guid + "_tolist dd:last");
				        if (lastcontact.length == 0) { return; }

				        lastcontact = lastcontact[0];

				        t = (lastcontact.id).split("_");
				        var id = t[0];

				        RemoveContact(guid, id);
				        BSC.E.Stop(e);
				        return false;
				    }).bind('keypress', 'up', function(e)
				    {
				        var t = (this.id).split("_");
				        var guid = t[0];
				        var s = $("#" + guid + "_searchresult dd.over");
				        if (s.length === 0) { s = $("#" + guid + "_searchresult dd:first"); s.addClass("over"); return; }
				        if (s[0].id == $("#" + guid + "_searchresult dd:first")[0].id) return;
				        s.removeClass("over");
				        s.prev().addClass("over");
				    }).bind('keypress', 'down', function(e)
				    {
				        var t = (this.id).split("_");
				        var guid = t[0];
				        var s = $("#" + guid + "_searchresult dd.over");
				        if (s.length === 0) { s = $("#" + guid + "_searchresult dd:first"); s.addClass("over"); return; }
				        if (s[0].id == $("#" + guid + "_searchresult dd:last")[0].id) return;
				        s.removeClass("over");
				        s.next().addClass("over");
				    }).bind('keypress', 'tab', function(e)
				    {
				        var t = (this.id).split("_");
				        var guid = t[0];
				        var els = $("#" + guid + "_searchresult dd.over");
				        if (els.length == 0) return;
				        var el = els[0];
				        var t2 = (el.id).split("_");
				        var id = t2[0];
				        if (el.id && id)
				            AddContact(guid, id);
				        BSC.E.Stop(e);
				        return false;
				    }).bind('keypress', 'Return', function(e)
				    {
				        var t = (this.id).split("_");
				        var guid = t[0];
				        var els = $("#" + guid + "_searchresult dd.over");
				        if (els.length == 0) return;
				        var el = els[0];
				        var t2 = (el.id).split("_");
				        var id = t2[0];
				        if (el.id && id)
				            AddContact(guid, id);
				        BSC.E.Stop(e);
				        return false;
				    });
				});
            $("#" + guid + "_searchresult").click(BSC.UI.Ws.Mail.Compose.OnContactsearchClick);
            $("#" + guid + "_tolist").click(BSC.UI.Ws.Mail.Compose.OnTolistClick);
            $("#" + guid + "_send").click(BSC.UI.Ws.Mail.Compose.OnSendmailClick);
            $("#" + guid + "_cancel").click(BSC.UI.Ws.Mail.Compose.OnCancelClick);


            $("#" + guid + "_topmarkasunread").bind("click", guid, function(e)
            {
                var guid = e.data;
                var w = BSC.UI.Ws.Get(guid);
                var jQ = BSC.U.ParseQuery(w.query);
                if (!jQ.id) return;


                var p = new BSC.D.Param("BSC.WS.JS.Mail.ChangeMail");
                p.Add("MailIDs", [jQ.id]);
                p.Add("Read", false);
                BSC.UI.ShowStatus(guid, "Saving...");
                BSC.D.Send(p, "Content.Mail", "MarkAs", function(res)
                {
                    if (res.d.success)
                    {
                        BSC.UI.Ws.Mail.ReFreshFolderlist();
                        BSC.UI.W.Close(guid);
                    }
                    BSC.UI.HideStatus(guid);
                });
            });
        };

        /// <summary>Public: Unbind events handlers from UI</summary>
        /// <param name="guid">Window UI identifier</param>
        var unbind = function(p1)
        {
            var guid = p1;
            $("#" + guid + "_to").unbind();
            $("#" + guid + " dd").unbind();
            $("#" + guid + " a").unbind();
            $("#" + guid + " div").unbind();
            $("#" + guid + " input").unbind();
            delete localcache[guid];
            current = null;
        };

        var appendContact = function(id)
        {
            if (current)
                AddContact(current, id);
            else
                GO("/mail/compose/?pid=" + id);
        };

        /// <summary>Public: </summary>
        /// <param name="e">Event</param>
        var onProfileSearchClick = function(e)
        {
            var guid = e.data.guid;
            var name = $("#" + guid + "_to").val();
            if (("" + name).length > 0)
            {
                GO("/members/search/" + name);
                return false;
            }
            else
            {
                alert("Please type a name");
                return false;
            }
        };

        /// <summary>Public: Called when user click on a profile in the searchresult list</summary>
        /// <param name="e">Event</param>
        var onContactsearchClick = function(e)
        {
            var el = BSC.E.GetElement(e, "dl", "dd");
            var t = (this.id).split("_");
            var guid = t[0];
            var t2 = (el.id).split("_");
            var id = t2[0];
            if (el && id)
            {
                //var id = el.id;
                AddContact(guid, id);
            }
        };

        /// <summary>Public: Called when a user click on recipient list. Action 1: Removes a profile from recipientlist</summary>
        /// <param name="e">Event</param>
        var onTolistClick = function(e)
        {
            var el = BSC.E.GetElement(e, "dd", "a");
            var t = (this.id).split("_");
            var guid = t[0];
            if (el && el.id)
            {
                var id = el.id;
                RemoveContact(guid, id);
            }
        };

        /// <summary>Public: Called when user click on actions (Send, cancel mail)</summary>
        /// <param name="e">Event</param>
        var onSendmailClick = function(e)
        {
            var el = BSC.E.GetElement(e, "div", "a");
            var guid = ((el.id).split("_"))[0];
            Sendmail(guid);
        };

        /// <summary>Public: Called when user click on actions (Send, cancel mail)</summary>
        /// <param name="e">Event</param>
        var onCancelClick = function(e)
        {
            var el = BSC.E.GetElement(e, "div", "a");
            var guid = ((el.id).split("_"))[0];
            Cancelmail(guid);
        };

        /// <summary>Public: Called when user type in the to field, performs search</summary>
        /// <param name="e">Event</param>
        var onSearchEvent = function(e)
        {
            if (e.keyCode == 40 || e.keyCode == 38)
                return;

            var el = e.target;
            var guid = ((el.id).split("_"))[0];
            Search(guid, el.value);
        };

        return {

            /// <summary>Public: Load mail data on window load</summary>
            /// <param name="guid">Window UI identifier</param>
            LoadData: load,

            /// <summary>Public: Bind events handlers to UI</summary>
            /// <param name="guid">Window UI identifier</param>
            Bind: bind,

            /// <summary>Public: Unbind events handlers from UI</summary>
            /// <param name="guid">Window UI identifier</param>
            Unbind: unbind,

            /// <summary>Public: </summary>
            /// <param name="data"></param>
            OnResize: onResize,

            /// <summary>Public: </summary>
            /// <param name="e">Event</param>
            OnProfileSearchClick: onProfileSearchClick,

            /// <summary>Public: Called when user click on a profile in the searchresult list</summary>
            /// <param name="e">Event</param>
            OnContactsearchClick: onContactsearchClick,

            /// <summary>Public: Called when a user click on recipient list. Action 1: Removes a profile from recipientlist</summary>
            /// <param name="e">Event</param>
            OnTolistClick: onTolistClick,

            /// <summary>Public: Called when user click on actions (Send mail)</summary>
            /// <param name="e">Event</param>
            OnSendmailClick: onSendmailClick,

            /// <summary>Public: Called when user click on actions (Cancel mail)</summary>
            /// <param name="e">Event</param>
            OnCancelClick: onCancelClick,

            /// <summary>Public: Called when user type in the to field, performs search</summary>
            /// <param name="e">Event</param>
            OnSearchEvent: onSearchEvent,

            /// <summary>Public: Called when user type in the to field, performs search</summary>
            /// <param name="e">Event</param>
            HideInfo: hideInfo,

            /// <summary>Public: Called when user type in the to field, performs search</summary>
            /// <param name="e">Event</param>
            AppendContact: appendContact
        };
    } ();
})();

BSC.E.Subscribe("load", BSC.UI.Ws.Mail.Compose.LoadData, null, "mail.read");
BSC.E.Subscribe("bind", BSC.UI.Ws.Mail.Compose.Bind, null, "mail.read");
BSC.E.Subscribe("unbind", BSC.UI.Ws.Mail.Compose.Unbind, null, "mail.read");
BSC.E.Subscribe("stopresize", BSC.UI.Ws.Mail.Compose.OnResize, null, "mail.read");
BSC.E.Subscribe("maximize", BSC.UI.Ws.Mail.Compose.OnResize, null, "mail.read");
BSC.E.Subscribe("restore", BSC.UI.Ws.Mail.Compose.OnResize, null, "mail.read");

BSC.E.Subscribe("load", BSC.UI.Ws.Mail.Compose.LoadData, null, "mail.compose");
BSC.E.Subscribe("bind", BSC.UI.Ws.Mail.Compose.Bind, null, "mail.compose");
BSC.E.Subscribe("unbind", BSC.UI.Ws.Mail.Compose.Unbind, null, "mail.compose");
BSC.E.Subscribe("stopresize", BSC.UI.Ws.Mail.Compose.OnResize, null, "mail.compose");
BSC.E.Subscribe("maximize", BSC.UI.Ws.Mail.Compose.OnResize, null, "mail.compose");
BSC.E.Subscribe("restore", BSC.UI.Ws.Mail.Compose.OnResize, null, "mail.compose");
