﻿var chatWindows = new Array();

ChatWindow = function()
{

}

ChatWindow.prototype.HolderID = "";
ChatWindow.prototype.Holder = null;
ChatWindow.prototype.ContactName = "";
ChatWindow.prototype.EntityHashID = "";
ChatWindow.prototype.ConversationHashID = "";
ChatWindow.prototype.Conversation = null;
ChatWindow.prototype.Subject = "";
ChatWindow.prototype.RefreshInterval = 0;
ChatWindow.prototype.IsTalking = false;
ChatWindow.prototype.IsFetching = false;
ChatWindow.prototype.FirstRefresh = true;

ChatWindow.prototype.Initialise = function(holderID, entityhash, convhash)
{
    chatWindows.push(this);
    
    this.HolderID = holderID;
    this.Holder = $(holderID);
    this.EntityHashID = entityhash;
    this.ConversationHashID = convhash;// && convhash.length>0?convhash:" ";
    this.DrawOuterUI();
}

ChatWindow.prototype.GetElementID = function(id)
{
    return this.HolderID+id;
}

ChatWindow.prototype.GetElement = function(id)
{
    return $(this.GetElementID(id));
}

//
// InitConversation
//
ChatWindow.prototype.InitConversation = function()
{
    if (this.Conversation!=null)
        return;
    
    //ChatWindow_OnGetConversation(res, holderID)
    GlobalCB("ChatWindowControl.GetConversation", this.HolderID, this.ConversationHashID, this.EntityHashID, this.Subject);

    
}

function ChatWindow_OnGetConversation(res, holderID)
{
    var win = GetChatWindow(holderID);
    if (!win)
        return;
    win.OnInitConversation(res);
}

ChatWindow.prototype.OnInitConversation = function(res)
{
    this.Conversation = res;
    if (this.Conversation.InvalidHash)
    {
        
        this.GetElement("_content").innerHTML = this.Conversation.Msg;
        this.Conversation = null;
        return;
    }
    
    this.ConversationHashID = this.Conversation.ConversationHashID;
    this.GetElement("_Link").innerHTML = "Link to this Conversation<br/>"+this.Conversation.Url;
    
    this.DrawMainContent();
    this.DrawMembers();
    this.Start();
}

ChatWindow.prototype.DrawMainContent = function()
{
    var s = "";
    s += "<div id=\""+this.GetElementID("_Text")+"\" style=\"height: 200px; background: #FEFEFE url(/v2.0/images/comment_bg.gif) 0px 0px no-repeat; padding: 10px;  overflow-y: scroll; vertical-align: top;\">";
    s += "<div> Initialising, please wait ... </div>";
    s += "</div>";
    this.GetElement("_content").innerHTML = s;
    
    s = "";
    s += "<table style=\"margin: 0px 10px 0px 10px;\"><tr valign=\"top\">";
    s += "<tr><td width=\"100%\">";
    s += "<textarea style=\"width: 100%; height: 60px;\" id=\""+this.GetElementID("_Input")+"\" onkeydown=\"if (event.keyCode==10) { ChatWindow_Send('"+this.HolderID+"'); return false; }\"></textarea>";
    s += "</td><td>";
    s += "<input type=\"button\" style=\"width: 80px; height: 60px;\" onclick=\"ChatWindow_Send('"+this.HolderID+"');\" value=\" Send \"/>";
    s += "</td></tr></table>";
    this.GetElement("_inputArea").innerHTML = s
}

ChatWindow.prototype.Start = function()
{
    this.RefreshInterval = setInterval("ChatWindow_Refresh('"+this.HolderID+"')", 4000)
}

ChatWindow.prototype.Stop = function()
{
    if (!this.RefreshInterval)
        return;
   clearInterval(this.RefreshInterval);
   this.RefreshInterval = 0;
}

//
// DrawOuterUI
//
ChatWindow.prototype.DrawOuterUI = function()
{        
    //ChatWindow_OnRenderOuterUI(res, holderID)
    GlobalCB("ChatWindowControl.RenderOuterUI", this.HolderID, this.ConversationHashID);
}

function ChatWindow_OnRenderOuterUI(res, holderID)
{
    var win = GetChatWindow(holderID);
    if (!win)
        return;
    win.OnDrawOuterUI(res);
}

ChatWindow.prototype.OnDrawOuterUI = function(res)
{ 
    this.Holder.innerHTML = res;
    
    var s  = "";
    s += "<div id=\""+this.GetElementID("_members")+"\" style=\"width: 200px; overflow-y:scroll;float: right; height: 200px; margin-right: 2px\"></div>";
    s += "<div id=\""+this.GetElementID("_content")+"\" style=\"margin-right: 200px;\"><div class=\"Loading\"></div></div>";
    s += "<div id=\""+this.GetElementID("_inputArea")+"\" style=\"margin-right: 30px;\"></div>";
    this.GetElement("_main").innerHTML = s;
    
    if (!this.EntityHashID || !this.ConversationHashID)
        this.InitLogin();
    else
        this.InitConversation();
}

//
// InitLogin
//
ChatWindow.prototype.InitLogin = function()
{
   //ChatWindow_OnRenderLoginUI(res, holderID)
   GlobalCB("ChatWindowControl.RenderLoginUI", this.HolderID, this.ConversationHashID);   
}
function ChatWindow_OnRenderLoginUI(res, holderID)
{
    var win = GetChatWindow(holderID);
    if (!win)
        return;
    win.OnInitLogin(res);
}
ChatWindow.prototype.OnInitLogin = function(res)
{
    this.GetElement("_content").innerHTML = res;
}



ChatWindow.prototype.DrawMembers = function() 
{
    if (this.Conversation.Members==null)
        this.Conversation.Members = new Array();
    var ar = this.Conversation.MemberString.split('\n');
    var s = "<table>";
    for(var i=0;i<ar.length;i++)
    {
        if (ar[i].length==0)
            continue;
        
        var details = ar[i].split('|');
        var isEmployee = details[2]=="true";
        
        this.Conversation.Members.push(details[0]);
        
        s += "<tr valign=\"top\">";
        s += "<td><img src=\"/?SendAvatarHash="+details[0]+"&width=24&height=24\" /></td>"
        s += "<td>";
        if (details.length==4)
        {
            s += "<a href=\"/Contacts?EntityID=" + details[3] + "\" onmouseover=\"PopupItemBubble(event, 'Entity',  " + details[3] + ")\" target=\"_blank\">" + details[1] + "</a>";
        }
        else
        {
            s += details[1];
        }
        s += "</td>";
        s += "</tr>";
    }
    s += "</table>";
    
    this.GetElement("_members").innerHTML = s;
}

ChatWindow.prototype.ContainsMember = function(EntityHashID)
{
    if (this.Conversation.Members==null)
        this.Conversation.Members = new Array();
    for(var i=0;i<this.Conversation.Members.length;i++)
        if (this.Conversation.Members[i]==EntityHashID)
            return true;
            
    return false;
}

ChatWindow.prototype.AppendMessage = function(m)
{
   
    if (this.Conversation.Messages==null)
        this.Conversation.Messages = new Array();
    for(var i=0;i<this.Conversation.Messages.length;i++)
        if (this.Conversation.Messages[i].MessageID==m.MessageID)
            return false;
    
    this.Conversation.Messages.push(m);
   
    return true;
}

function GetChatWindow(holderID)
{
    for(var i=0;i<chatWindows.length;i++)
        if (chatWindows[i].HolderID==holderID)
            return chatWindows[i];
            
    return null;
}

function ChatWindow_EmailChanged(holderID)
{
    var win = GetChatWindow(holderID);
    if (!win)
    return;
    
    win.GetElement("_PassRow").style.display = "none";
    win.GetElement("_Continue").disabled = false;
    if (win.GetElement('_Email').value.length==0)
    {
        win.GetElement("_PassGlyph").innerHTML = "";
        win.GetElement("_EmailFeedback").innerHTML = "";
        win.GetElement("_EmailGlyph").innerHTML = "";
        return;
    }
    
    
    win.GetElement("_EmailGlyph").innerHTML = "<div class=\"Loading\">&nbsp;</div>";
    
    //ChatWindow_OnIsEmailPresent
    GlobalCB("ChatWindowControl.IsEmailPresent", win.HolderID, win.ConversationHashID, win.GetElement('_Email').value);
}

function ChatWindow_OnIsEmailPresent(res, holderID)
{
    var win = GetChatWindow(holderID);
    if (!win)
        return;
    if (res.HasError)
    {
        win.GetElement("_EmailGlyph").innerHTML = "<img src=\"/v2.0/images/validate_error.gif\"/>";
        win.GetElement("_EmailFeedback").innerHTML = "<div class=\"FeedbackError\">"+res.Msg+"</div>";
        win.GetElement("_Continue").disabled = true;
    }
    else if (res.IsDupe)
    {
        win.GetElement("_Continue").disabled = true;
        win.GetElement("_EmailGlyph").innerHTML = "<img src=\"/v2.0/images/validate_ok.gif\"/>";
        win.GetElement("_EmailFeedback").innerHTML = "<div class=\"FeedbackError\">"+res.Msg+"</div>";
        win.GetElement("_PassRow").style.display = "block";
        win.GetElement("_Pass").focus();
    }
    else
    {
        win.GetElement("_Continue").disabled = false;
        win.GetElement("_EmailGlyph").innerHTML = "<img src=\"/v2.0/images/validate_ok.gif\"/>";
    }
}

function ChatWindow_SignIn(holderID)
{
    var win = GetChatWindow(holderID);
    if (!win)
    return;
    win.GetElement("_Continue").disabled = false;
    if (win.GetElement('_Email').value.length==0)
    {
        win.GetElement("_PassGlyph").innerHTML = "";
        win.GetElement("_EmailFeedback").innerHTML = "";
        return;
    }
    win.GetElement("_PassGlyph").innerHTML = "<div class=\"Loading\">&nbsp;</div>";
    
    // ChatWindow_OnAuthenticate
    GlobalCB("ChatWindowControl.Authenticate", win.HolderID, win.ConversationHashID, win.GetElement('_Email').value, win.GetElement('_Pass').value);    
}

function ChatWindow_OnAuthenticate(res, holderID)
{
    var win = GetChatWindow(holderID);
    if (!win)
        return;
        
    if (res.HasError)
    {
        win.GetElement("_PassGlyph").innerHTML = "<img src=\"/v2.0/images/validate_error.gif\"/>";
        win.GetElement("_EmailFeedback").innerHTML = "<div class=\"FeedbackError\">"+res.Msg+"</div>";
    }
    else
    {
        win.EntityHashID = res.EntityHashID;
        win.GetElement("_LoginTable").innerHTML = "<div style=\"padding: 2px;\">"+res.Welcome+"</div>";
        win.GetElement("_Continue").disabled = false;
        win.ContactName = res.Name;
    } 
}

function ChatWindow_Continue(holderID)
{
   var win = GetChatWindow(holderID);
   if (!win)
        return;
   
   if (!win.EntityHashID 
        && win.GetElement("_FirstName").value.replace(" ","").length==0)
   {
        win.GetElement("_FirstNameGlyph").innerHTML = "<img src=\"/v2.0/images/validate_error.gif\"/>";
        return;
   }
   
   if( win.GetElement("_FirstName") )
    win.ContactName = win.GetElement("_FirstName").value;
   
   //ChatWindow_OnCreateAnonymousPerson(res, holderID)
   GlobalCB("ChatWindowControl.CreateAnonymousPerson", win.HolderID, win.ConversationHashID, win.ContactName);

}

function ChatWindow_OnCreateAnonymousPerson(res, holderID)
{
    var win = GetChatWindow(holderID);
    if (!win)
        return;
    if (!win.EntityHashID)
        win.EntityHashID = res;
       
   if (win.GetElement("_Subject"))
        win.Subject = win.GetElement("_Subject").value;
    
   win.InitConversation();
}

function ChatWindow_Refresh(holderID)
{
    var win = GetChatWindow(holderID);
    if (!win || win.IsFetching)
        return;
    
    
    win.IsFetching = true;
    
    //ChatWindow_OnGetUnreadMessages(res, holderID)
    GlobalCB("ChatWindowControl.GetUnreadMessages", win.HolderID, win.ConversationHashID, win.EntityHashID);
}

function ChatWindow_OnGetUnreadMessages(res, holderID)
{
    var win = GetChatWindow(holderID);
    if (!win)
        return;

    win.Conversation.Subject = res.Subject;
    win.Conversation.IsClosed = res.IsClosed;
    
    var newlyRead = "";
    for(var i=0;i<res.Messages.length;i++)
    {
        if (win.AppendMessage(res.Messages[i]))
        {
            if (newlyRead.length>0)
                newlyRead += "|";
            newlyRead += res.Messages[i].MessageID;
        }
    }
    
    if (newlyRead.length>0)
        GlobalCB("ChatWindowControl.MarkRead", win.HolderID, win.ConversationHashID, win.EntityHashID, newlyRead);   
    
    
    if (res.Messages.length>0||win.FirstRefresh)
    {
        var messageBox = win.GetElement("_Text");
        var isScrolledToBottom = messageBox.scrollTop >= (messageBox.scrollHeight-messageBox.offsetHeight); 
        var s = "";
        
        var hasMembersChanges = false;
        
        for(var i=0;i<win.Conversation.Messages.length;i++)
        {
            var m = win.Conversation.Messages[i];
            if (!win.ContainsMember(m.Person.EntityHashID))
            {
                hasMembersChanges = true;
                if (win.Conversation.MemberString.length>0)
                    win.Conversation.MemberString += "\n";
                win.Conversation.MemberString += m.Person.EntityHashID+"|"+m.Person.Name+"|"+m.Person.IsEmployee+(m.EntityID?"|"+m.EntityID:"");
            }
            s += "<div title=\""+m.Date+"\">";
            s += "<b>"+m.Person.Name+":</b> ";
            s += ParseLinks(m.Body).replace(/\n/g, "<br/>");
            s += "</div>"
        }
        
        if (hasMembersChanges)
            win.DrawMembers();
         
       
        messageBox.innerHTML = s;
        
        if (win.FirstRefresh || isScrolledToBottom)
        {
            if (messageBox.doScroll)
            {
                for(var a = 0; a < 50; a++) 
                    messageBox.doScroll('pageDown'); 
            }
            else
            {
               messageBox.scrollTop = 100000;
            }
        }
    }
    
    if (win.Conversation.Messages.length==0)
    {
        win.GetElement("_Text").innerHTML = "Someone should be attending to you shortly.";
    }
        
    win.FirstRefresh = false;
    win.IsFetching = false;
}

function ChatWindow_StartTalking(holderID)
{
    var win = GetChatWindow(holderID);
    if (!win)
    return;
    
    if (!win.IsTalking)
    {
        win.IsTalking = true;
        //Veetro.Service.UserStartedTypingWebSafe(ConversationHashID, EntityHashID);
    }
}

function ChatWindow_StopTalking(holderID)
{
    var win = GetChatWindow(holderID);
    if (!win)
    return;
    if (win.IsTalking)
    {
        //Veetro.Service.UserStoppedTypingWebSafe(ConversationHashID, EntityHashID);
        win.IsTalking = false;
    }
}
function ChatWindow_Send(holderID)
{
    var win = GetChatWindow(holderID);
    if (!win)
    return;
    if (win.GetElement("_Input").value.length==0)
        return;
    GlobalCB("ChatWindowControl.SendMessage", win.HolderID, win.ConversationHashID, win.EntityHashID, win.GetElement("_Input").value);
    win.GetElement("_Input").value = "";
}

function ParseLinks(text)
{

    text = text.replace(/(\w+:\/\/)[^\s]+/g, "<a href=\"$&\" target=\"_blank\" Title=\"Click to launch in new Browser Window...\">$&</a>");
    text = text.replace(/(www\.)[^\s]+/g, "<a href=\"http://$&\" target=\"_blank\" Title=\"Click to launch in new Browser Window...\">$&</a>");
    text = text.replace(/[\w|.|_|-]+[@|#]+[\w|-]+[.]+[\w|.]+/g, "<a href=\"mailto:$&\" Title=\"Click to e-mail\">$&</a>");
    
    return text;
}
function SendPassword() {
    var win = chatWindows[0];
    if (!win)
        return;

    if (win.GetElement('_Email').value.length != 0)
        GlobalCB("ChatWindowControl.SendPassword", win.GetElement('_Email').value);
}