﻿var firstRun = true;

var activeDialog;

$(function() {
    InitContactsDialog();
    RestoreDialogState('Contacts');
});

function replaceAll(txt, replace, with_this) {
    return txt.replace(new RegExp(replace, 'g'), with_this);
}

function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom)
      && (elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

jQuery.fn.swapWith = function(to) {
    var oldNodeAtPosition = this;
    var newNodeAtPosition = $(to)[0];
    // swap DOM nodes
    // API: replaceChild(child1,child2)  --  replace node child2 by node child1
    oldNodeAtPosition.parentNode.replaceChild(newNodeAtPosition.cloneNode(true), oldNodeAtPosition);
    newNodeAtPosition.parentNode.replaceChild(oldNodeAtPosition.cloneNode(true), newNodeAtPosition);

};

function htmlEncode(value) {
    return $('<div/>').text(value).html();
}

function htmlDecode(value) {
    return $('<div/>').html(value).text();
}

function Log(obj) {
    //if ($.browser.mozilla)
        //console.log(obj);
    //else
    //alert(obj);
}

function UpdateAll(statusData, messageList)
{
    $(function(){
        if (statusData != null)
        {
            UpdateContactsStatus(statusData);
        }
        
        if (messageList != null && messageList.length > 0)
        {
            UpdateMessages(messageList);
        }
        
        firstRun = false;
    });
}

function UpdateContactsStatus(statusData) {
    $(function() {
        Log(statusData);
        $(".contacts-list-inner").html('');
        if (statusData.length > 0) {
            var result = $("#tplContactStatus").tmpl(statusData).appendTo(".contacts-list-inner");
            $(statusData).each(function() {
                $('.status-icon','.chat-dialog[title=' + this.Username + ']').attr('src','images/status-' + this.StatusText + '.png');
            });
            Log(result);
        }
        else {
            $(".contacts-list-inner").append('No Users Online');
        }
    });
}

function UpdateMessages(messageList, sentMessage) {
    $(function() {
        Log(messageList);
        $(messageList).each(function(index) {
            if (this.Messages.length <= 0)
                return;

            //replaceAll(message, '\n', '<br/>')
            $(this.Messages).each(function() {
                this.Msg = unescape(this.Msg);
                this.Msg = $.encode(this.Msg);
                this.Msg = replaceAll(this.Msg, '\n', '<br/>');
                this.Msg = $().emoticon(this.Msg);
            });

            var divMessages = GetMessagesList(this.Username);
            Log('divMessages');
            Log(divMessages);
            var result = $('#tplChatMessage').tmpl(this.Messages);
            Log('Result');
            Log(result);
            result.appendTo(divMessages);
            if (firstRun)
                RestoreDialogState(this.Username);
            else
                ShowChatDialog(this.Username);

            if (!isScrolledIntoView(GetChatDialog(this.Username))) {
                //                $(this.Messages).each(function(){
                //                    $.jGrowl(this.Msg, { header: this.Sender });
                //                });
                BringChatDialogToTop(this.Username);
            }

            //if (GetChatDialog(this.Username) != activeDialog) {
            if (!sentMessage && !firstRun) {
                BlinkDialog(this.Username);
            }
            //}

            divMessages.scrollTop = divMessages.scrollHeight;
        });
        if (!windowFocused) {
            notifySound.play();
        }
    });
}

function GetChatDialogContainer() {
    return $('.chat-dialog-container')[0];
}

function BringChatDialogToTop(username) {
    var dialog = GetChatDialog(username);

    if (dialog != $('.chat-dialog:first')[0]) {
        var container = GetChatDialogContainer();
        container.removeChild(dialog.parentNode);

        var firstColumn = $('.chat-column:first')[0];

        Log(dialog);
        container.insertBefore(dialog.parentNode, firstColumn);
        
    }
}

function RestoreDialogState(title) {
    var dialogState = GetDialogState(title);
    Log(dialogState);
    if (dialogState == null) {
        ShowChatDialog(title);
        if (title == 'Contacts')
            MinimizeChatDialog(title);
    }
    else {
        if (dialogState.State == 'Open') {
            ShowChatDialog(title);
        }
        else if (dialogState.State == 'Minimized') {
            ShowChatDialog(title);
            MinimizeChatDialog(title);
        }
    }
}

function GetMyUsername() {
    return $('input[type=hidden]', '#spnHdnMyUsername').val();
}

function AddMessage(username, messageContents) {
    var myUsername = GetMyUsername();
    var divMessages = GetMessagesList(username);
    var msg = { Id: -1, Sender: myUsername, Msg: messageContents };
    UpdateMessages([{ Username: username, Messages: [msg]}], true);
}

function CreateChatDialog(username) {
    if ($('.ui-widget[title=' + username + ']').length == 0) {
        $('#tplChatDialog').tmpl([{ Username: username}]).prependTo('.chat-dialog-container');
        InitChatDialog(username);
    }
}

function InitContactsDialog() {
    var dialog = GetChatDialog('Contacts');
    $('.toggle-minimize-button', dialog).button({ text: false, icons: { primary: 'ui-icon-circle-triangle-n'} });
}

function InitChatDialog(username) {
    var dialog = GetChatDialog(username);
    var txtMessage = $('.message-text-box', dialog);
    txtMessage.keydown(function(e) {
        if (e.shiftKey && (e.which == '13')) {
            Log(e);
            e.preventDefault();
            SendChatMessage(username);
        }
    });

    //txtMessage.autoResize({ limit: 100, extraSpace: 0, animate:false });
    $(txtMessage).TextAreaExpander();

    if ($.browser.msie) {

        txtMessage.focus(function() {
            $('.chat-dialog-container').css('visibility', 'visible');
        });

        txtMessage.blur(function() {
            $('.chat-dialog-container').css('visibility', 'hidden');
        });
    }
    
    $('.send-message-button', dialog).button();
    $('.hide-dialog-button', dialog).button({ text: false, icons: { primary: 'ui-icon-circle-close'} });
    $('.toggle-minimize-button', dialog).button({ text: false, icons: { primary: 'ui-icon-circle-triangle-s'} });
    $(dialog).click(function() { activeDialog = this; });
    $('.status-icon', dialog).attr('src', 'images/status-' + GetLastKnownStatusText(username) + '.png');

}

function GetLastKnownStatusText(username) {
    var statusIcon = $('.status-icon', '.contacts-list-status[title=' + username + ']');
    if (statusIcon.length == 0)
        return 'Offline';
    else
        return statusIcon.attr('alt');
}

function GetChatDialog(title) {
    var dialog = $('.ui-widget[title=' + title + ']');
    if (dialog.length == 0) {
        if (title != "Contacts")
            CreateChatDialog(title);
        dialog = $('.ui-widget[title=' + title + ']');
    }
    return dialog[0];
}

function GetMessagesList(username) {
    var divMessages = $('.chat-messages', GetChatDialog(username));
    return divMessages[0];
}

function ShowChatDialog(username) {
    var chatDialog = GetChatDialog(username);
    $(chatDialog).parent().show("fast");
    SaveDialogState(username, 'Open');
    MaximizeChatDialog(username);
}

function MaximizeChatDialog(title) {
    var chatDialog = GetChatDialog(title);
    var toggleButton = $('.toggle-minimize-button', chatDialog);
    $('.ui-widget-content', chatDialog).show();

    toggleButton.button("option", "icons", { primary: 'ui-icon-circle-triangle-s' });
    toggleButton.attr('title', 'Minimize');
    SaveDialogState(title, 'Open');
}

function MinimizeChatDialog(title) {
    var chatDialog = GetChatDialog(title);
    var toggleButton = $('.toggle-minimize-button', chatDialog);
    $('.ui-widget-content', chatDialog).hide();

    toggleButton.button("option", "icons", { primary: 'ui-icon-circle-triangle-n' });
    toggleButton.attr('title', 'Maximize');
    SaveDialogState(title, 'Minimized');
}

function HideChatDialog(title, e) {
    $(GetChatDialog(title)).parent().hide("fast");
    SaveDialogState(title, 'Closed');
    e.cancelBubble = true;
    return false;
}

function BlinkDialog(title) {
    $('.ui-widget-header', GetChatDialog(title)).effect('pulsate', {}, 400)
}

function OnContactClick(username) {
    if (!$(GetChatDialog(username)).is(':visible') || !isScrolledIntoView(GetChatDialog(username))) {
        BringChatDialogToTop(username);
    }
    ShowChatDialog(username);
    BlinkDialog(username);
    $('.message-text-box', GetChatDialog(username)).focus();
    activeDialog = GetChatDialog(username);
}

function ToggleMinimize(title, e) {
    Log(e);
    var chatDialog = GetChatDialog(title);
    var toggleButton = $('.toggle-minimize-button', chatDialog);
    var icons = toggleButton.button("option", "icons");

    if (icons.primary == 'ui-icon-circle-triangle-s')
        MinimizeChatDialog(title);
    else
        MaximizeChatDialog(title);
    e.cancelBubble = true;
    return false;
}

function SendChatMessage(username) {
    var chatDialog = GetChatDialog(username);
    var txtMessage = $('.message-text-box', chatDialog);
    var message = escape(txtMessage.val());
    
    txtMessage.val('');
    txtMessage.change();
    txtMessage.focus();
    if (message != null && message.trim().length > 0) {
        SendMessage(username, message);
        //AddMessage(username, replaceAll(message, '\n', '<br/>'));
        AddMessage(username, message);
        var divMessages = GetMessagesList(username);
        divMessages.scrollTop = divMessages.scrollHeight;
    }
}

function SendMessage(username, message) {
    $('input[type=hidden]', '#spnHdnUsername').val(username);
    $('input[type=hidden]', '#spnHdnMessage').val(message);
    $('.send-message-proxy-button')[0].click();
}

function GetDialogState(username) {
    var states = $.cookie('DialogState');

    if (states == null) {
        states = new Object();
    }
    else {
        states = $.evalJSON(states);
    }

    return states[username];
}

function SaveDialogState(username, state) {
    var states = $.cookie('DialogState');

    if (states == null) {
        states = new Object();
    }
    else {
        states = $.evalJSON(states);
    }

    var stateObj = { State: state };
    states[username] = stateObj;
    $.cookie('DialogState', $.toJSON(states))
    Log($.cookie('DialogState'));
}

function OpenTestWindows(n) {
    for (var i = 0; i < n; i++) {
        SendTestMessage('Sonu' + i.toString());
    }
}

function SendTestMessage(sender) {
    UpdateMessages([{ Username: sender, Messages: [{ Sender: sender, Id: 1, Msg: 'Test'}]}]);
}
