﻿function start_chat() {
    getChatInfo();
    setInterval("getChatInfo()", 2000);
}

function getChatInfo() {
    if (typeof (WebService) != "undefined") {
        WebService.PullChatInfo(OnChatSucceeded);
    }
}

/* system-generated */
function showChat() {
    var pos = getChatPoint();
    var height = $('#divSPList').height();

    $('#divSPList').css('top', pos.top - height);
    $('#divSPList').css('left', pos.left);

    $('#divSPList').show('slide', { direction: 'up' }, 150);

    $('#divSPList').css('position', 'fixed');

}

function showChatInvitation(divid) {
    var divInvNotice = $('#' + divid);
    var pos = getChatPoint();
    var h = $(divInvNotice).height();
    $(divInvNotice).css('top', pos.top - h);
    $(divInvNotice).css('left', pos.left);
    //$(this).stop().animate({ top: -5 }, 200);
    $(divInvNotice).show('slide', { direction: 'up' }, 500);
    $(divInvNotice).css('position', 'fixed');
}

/* user actions */
// invite chat
function inviteChat() {//alert('will invite...');
    if (typeof (WebService) != "undefined") {
        buyername = $('#spanBuyerName').text();
        var splist = [];
        //alert($('#tableActiveSPList .checkUsername:checked').length);
        $('#tableActiveSPList .checkUsername:checked').each(function() {
            if ($(this).is(':checked')) {
                spname = $(this).parent().prev().text();
                chkid = $(this).attr('id');
                spid = chkid.replace('cb_', '');
                splist.push(spid + ':' + spname);
            }
        });
        chattitle = $('#txtChatTitle').val().trim();
        if (chattitle.length <= 0) chattitle = "chat " + ($('.divOpenChatRoom').length + 1);
        WebService.OpenChatRoom(buyername, chattitle, splist, OnOpenChatSucceeded);

    }
}

// join chat (accept chat invitation)
var acceptguid;
var accepttitle;
function acceptInvitation(guid) {
    if (typeof (WebService) != "undefined") {
        name = $('#spanBuyerName').text();
        acceptguid = guid;
        //alert('calling web service participate chat: ' + guid + ' ' + name)
        WebService.ParticipateChat(guid, name, OnJoinSucceeded, OnJoinFailed);
    }
}

// refuse chat invitation
function rejectInvitation(guid) {
    if (typeof (WebService) != "undefined") {
        //alert(guid);
        WebService.RefuseChatInvitation(guid);

        // hide chat invitation
        $('#divInvitationNotice_' + guid).hide();
    }
}

// hide chat
function hideChat() {
    $('#divSPList').css('position', 'absolute');
    $('#divSPList').hide('slide', { direction: 'down' }, 150);
}

// leave chat
// defined in document.ready


function adjustChatRoomContainer() {
    // position of chatroom container
    var pos = $('#divStatusBar').position();
    var pos2 = $('#divChat').position();
    var y = pos.top;
    var x = pos2.left;
    var height = $('#tableChatRoomContainer').height();
    var width = $('#tableChatRoomContainer').width();
    //alert(y + ' ' + height + ' ' + x + ' ' + width);
    $('#divChatRoomContainer').css('top', y - height);
    $('#divChatRoomContainer').css('left', x + pos.left - width);
}



function getChatPoint() {
    var pos = $('#divStatusBar').position();
    var pos2 = $('#divChat').position();
    var y = pos.top;
    var x = pos2.left;


    return { top: y, left: x + pos.left };
}






function OpenChatRoom(guid, title) {
    chatroom = $('#divChatRoomTemplate').clone();
    $(chatroom).attr('id', 'divChatRoom_' + guid);
    //alert($(chatroom).find('.txtMessage').length);
    $(chatroom).find('.txtMessage:first').attr('id', 'txtMessage_' + guid);
    $(chatroom).attr('class', 'divChatRoomActive');
    $('#trChatRoomContainer').prepend('<td id="td_' + guid + '"></td>');
    //alert($('#trChatRoomContainer #td_' + guid).length);
    $('#trChatRoomContainer #td_' + guid).append(chatroom);
    //$('#divChatRoomContainer').append(chatroom);

    $(chatroom).show();

    //$(chatroom).css('top', 10);
    //$(chatroom).css('left', 10);
    $('#divChatRoom_' + guid + ' .spanChatRoomTitle').text(title);
    $('#divChatRoomList').show();
    $('#divActivityFeed').hide();
    activechaticon = '<%=Page.ResolveUrl("~/images/icon_af_chat_active.gif") %>';
    $('#trChatRoomList').prepend('<td style="padding-left:3px; padding-right:3px;"><img class="iconChatRoomActive" id="iconChatRoom_' + guid + '" src="' + activechaticon + '" title="' + title + '" /></td>');
    //alert($(chatroom).attr('id'));


}

/* web service call back */
function OnOpenChatSucceeded(resultStr) {
    //alert(resultStr);
    jsonResult = eval(resultStr);
    result = jsonResult[0];

    if (result.result) {
        //OpenChatRoom(result.title);
        //alert(result.guid + ' ' + result.title);
        OpenChatRoom(result.guid, result.title);
        adjustChatRoomContainer();
    }
}

function OnChatSucceeded(resultStr) {
    //alert(resultStr);
    if (typeof (resultStr) == "undefined")
        return;

    jsonResult = eval(resultStr);
    result = jsonResult[0];

    UpdateStatusBar(result);

}

function OnJoinSucceeded(resultStr) {//alert(resultStr);
    jsonResult = eval(resultStr);
    if (jsonResult[0].result) {
        //alert('will open a chatroom with guid: ' + acceptguid);
        OpenChatRoom(acceptguid, '');
        adjustChatRoomContainer();

        UpdateStatusBar(jsonResult[0]);
    }
    else {
        // show fail reason to user : ex: already closed chat

    }
}

function OnJoinFailed(error) {
    alert('join chat failed!');

}

function addNewMessagesToChatRooms(newmessage) {
    for (var i = 0; i < newmessage.length; i++) {
        chatmessage = newmessage[i];
        guid = chatmessage.guid;
        if (chatmessage.message.length > 0) {
            //alert(guid + ' ' + chatmessage.message.length);
            AddNewMessage(guid, chatmessage.message);
        }

    }
}

var messageSeparator = '<tr><td style="border-bottom:1px solid #e0e0e0;"><img src="<%=Page.ResolveUrl("~/images/1x1.gif") %>" height="3" width="3" /></td></tr>';


function AddNewMessage(guid, messages) {
    // check if exists
    //alert($('#divChatRoom_' + guid).length);
    if ($('#divChatRoom_' + guid).length <= 0)
        return;

    // check if active
    //alert($('#divChatRoom_' + guid).attr('class'));
    if ($('#divChatRoom_' + guid).attr('class') != 'divChatRoomActive')
        return;

    username = '<%=HttpContext.Current.User.Identity.Name %>';

    for (var i = 0; i < messages.length; i++) {

        var message = messages[i];
        if (message.whisper.length <= 0 || (message.whisper.length > 0 && username == message.whisper)) {
            var name = message.name;
            var text = message.text;
            var time = message.time;
            var textclass = message.typed ? "chatmessage_text" : "chatmessage_action";
            aMessage = messageSeparator + '<tr><td style="padding-top:3px;"> \
                        <table cellpadding="0" cellspacing="0" style="width:100%"> \
                        <tr><td style="text-align:left;"><span class="chatmessage_name">' + name + '</span></td> \
                        <td style="text-align:right"><span class="chatmessage_datetime">' + time + '</span></td></tr> \
                        <tr><td colspan="2" style="text-align:left; vertical-align:top; padding-top: 3px;"><span class="' + textclass + '">' + text + '</span></td></tr> \
                        </table></td></tr>';
            //alert(aMessage);
            $('#divChatRoom_' + guid + ' .tableChatMessage:first').append(aMessage);
        }
    }

    $('#divChatRoom_' + guid + ' .divChatMessage').scrollTop($('#divChatRoom_' + guid + ' .tableChatMessage:first').height());
}
