var emoticon = new Array(":)", ":D", ";)", ":-O", ":P", "(H)", ":@", ":S", ":$", ":(", ":'(", "(L)", "(U)", "(F)", "(W)", "(G)");
var chat_maxLen = 400;
var chat_heartbeatTimer = null;
var chat_stop_heartbeat = false;
var chat_windowHasFocus = true;
var chat_last_msg_count = 0;
var DIV_last_timer = 0;
var separator_timer = null;
var chat_fmi = 0;
var msgId = 0;
var chat_wait4send_msg = 0;
var isAutoTranslationEnabled = false;
var is_chat_saved = false;
var str_general_error = "Due to some technical reasons we are unable to connect you at the moment. Please try again after some time. If you continue facing this problem, please send us an email at support@tradekey.com.";

var chat_content = {
    "SHORTCUT" : 1,
    "CDS_CONTENT_LIST" : 2
};

function loadjscssfile(filename, filetype, callback)
{
	if(filetype=="js")
	{
        var html_doc = document.getElementsByTagName('head').item(0);
        var js = document.createElement('script');
        js.setAttribute("type", "text/javascript");
        js.setAttribute("src", filename);
        js.defer = true;
        if (document.all) {
            if (js.readyState) {
                if (callback != null) {
                    js.onreadystatechange = function () {
                        if (js.readyState == "loaded" || js.readyState == "complete") {
                            eval(callback);
                        }
                    };
                }
                html_doc.appendChild(js);
            } else {
                html_doc.appendChild(js);
                if (callback != null) eval(callback);
            }
        } else {
            if (callback != null) js.onload = function () {
                eval(callback);
            };
            html_doc.appendChild(js);
        }
    } else if (filetype == "css") {
        var fileref = document.createElement("link");
        fileref.setAttribute("rel", "stylesheet");
        fileref.setAttribute("type", "text/css");
        fileref.setAttribute("href", filename)
    }
    if (typeof fileref != "undefined") document.getElementsByTagName("head")[0].appendChild(fileref)
}
if (typeof(jQuery) != "function") loadjscssfile(chat_js_url + "jquery/jquery-1.3.2.min.js", "js", "onafter_jquery()");
else
onafter_jquery();

function onafter_jquery() {
    jQuery.fn.insertAtCaret = function (myValue) {
        return this.each(function () {
            if (document.selection) {
                this.focus();
                sel = document.selection.createRange();
                sel.text = myValue;
                this.focus();
            } else if (this.selectionStart || this.selectionStart == '0') {
                var startPos = this.selectionStart;
                var endPos = this.selectionEnd;
                var scrollTop = this.scrollTop;
                this.value = this.value.substring(0, startPos) + myValue + this.value.substring(endPos, this.value.length);
                this.focus();
                this.selectionStart = startPos + myValue.length;
                this.selectionEnd = startPos + myValue.length;
                this.scrollTop = scrollTop;
            } else {
                this.value += myValue;
                this.focus();
            }
        });
    };
    if (typeof(is_b2c) != "undefined" && is_b2c) {
        if (typeof(chat_im_sendmessage_url) != "undefined") {
            jQuery(window).resize(function () {
                resize_window();
            }).ready(function () {
                resize_window();
                jQuery("#chatCustomer .chatboxtextarea").addClass('chatboxtextareaselected');
                document.title = jQuery("#chatbox .chatboxhead").text();
            }).load(function () {
                document.title = jQuery("#chatbox .chatboxhead").text();
                resize_window();
                jQuery("#chatCustomer .chatboxtextarea").addClass('chatboxtextareaselected');
                jQuery("#chatCustomer .chatboxtextarea").focus();
            }).unload(function () {
                if (is_chat_saved) return;
                chat_close_session();
            }).focus(function () {
                jQuery("#chatCustomer .chatboxtextarea").focus();
            }).blur(function () {
                chat_windowHasFocus = false;
            });
            window.onbeforeunload = function (e) {
                if (chat_heartbeatTimer != null) {
                    if (is_chat_saved) return;
                    var message = "You have not saved your chat. Clicking OK will try to save your chat automatically in CRM. \n(Note: Automatic saved is not 100% guaranteed)\n To manually save your chat in CRM click \"Save & Close\" from toolbar.";
                    e = e || window.event;
                    if (e) e.returnValue = message;
                    return message;
                }
            };
            jQuery("#chatCustomer .chatboxtextarea").blur(function () {
                jQuery("#chatCustomer .chatboxtextarea").removeClass('chatboxtextareaselected');
            }).focus(function () {
                jQuery("#chatCustomer .chatboxtextarea").addClass('chatboxtextareaselected');
                chat_windowHasFocus = true;
            }).click(function () {
                jQuery("#emoticon_list").hide();
                jQuery("#chat_tags_list").hide();
                jQuery("#file_transfer_list").hide();
            });
            if (jQuery("#chatAgent").is(':visible')) {
                jQuery("#chatAgent .chatboxtextarea").blur(function () {
                    jQuery("#chatAgent .chatboxtextarea").removeClass('chatboxtextareaselected');
                }).focus(function () {
                    jQuery("#chatAgent .chatboxtextarea").addClass('chatboxtextareaselected');
                })
                if (jQuery('#agent_separator').is(':visible')) {
                    jQuery('#agent_separator').hover(function () {
                        if (separator_timer != null) clearTimeout(separator_timer);
                        if (jQuery("#chatAgent").css('width') == "10px") return;
                        if (jQuery("#agent_separator").css('opacity') < 1) jQuery('#agent_separator').fadeTo('fast', 1);
                        separator_timer = setTimeout("jQuery('#agent_separator').fadeTo('fast', 0.1);", 1000);
                    }, function () {});
                    jQuery('#agent_separator').fadeTo('fast', 0.1);
                }
                setTimeout("init_agent_session()", 10);
            }
        } else if (typeof(chat_im_presence_url) != "undefined") {
            jQuery(window).ready(function () {
                chat_get_status();
            });
        }
    }(function ($) {
        $.fn.rc4 = function (settings) {
            var defaults = {
                key: null,
                method: "encrypt",
                callback: null
            };
            var options = $.extend(defaults, settings);
            if ($.fn.rc4.ctrlrInst == null) {
                $.fn.rc4.ctrlrInst = new $.fn.rc4.ctrlr(options);
            }
            return this.each(function () {
                $.fn.rc4.ctrlrInst.settings = options;
                $.fn.rc4.ctrlrInst.container = this;
                $.fn.rc4.ctrlrInst.initialise(this);
            });
        }
        $.extend({
            hexEncode: function (data) {
                var b16D = '0123456789abcdef';
                var b16M = new Array();
                for (var i = 0; i < 256; i++) {
                    b16M[i] = b16D.charAt(i >> 4) + b16D.charAt(i & 15);
                }
                var result = new Array();
                for (var i = 0; i < data.length; i++) {
                    result[i] = b16M[data.charCodeAt(i)];
                }
                return result.join('');
            },
            hexDecode: function (data) {
                var b16D = '0123456789abcdef';
                var b16M = new Array();
                for (var i = 0; i < 256; i++) {
                    b16M[b16D.charAt(i >> 4) + b16D.charAt(i & 15)] = String.fromCharCode(i);
                }
                if (!data.match(/^[a-f0-9]*$/i)) return false;
                if (data.length % 2) data = '0' + data;
                var result = new Array();
                var j = 0;
                for (var i = 0; i < data.length; i += 2) {
                    result[j++] = b16M[data.substr(i, 2)];
                }
                return result.join('');
            },
            rc4Encrypt: function (key, pt) {
                s = new Array();
                for (var i = 0; i < 256; i++) {
                    s[i] = i;
                };
                var j = 0;
                var x;
                for (i = 0; i < 256; i++) {
                    j = (j + s[i] + key.charCodeAt(i % key.length)) % 256;
                    x = s[i];
                    s[i] = s[j];
                    s[j] = x;
                }
                i = 0;
                j = 0;
                var ct = '';
                for (var y = 0; y < pt.length; y++) {
                    i = (i + 1) % 256;
                    j = (j + s[i]) % 256;
                    x = s[i];
                    s[i] = s[j];
                    s[j] = x;
                    ct += String.fromCharCode(pt.charCodeAt(y) ^ s[(s[i] + s[j]) % 256]);
                }
                return ct;
            },
            rc4Decrypt: function (key, ct) {
                return $.rc4Encrypt(key, ct);
            },
            rc4EncryptStr: function (str, key) {
                return $.hexEncode($.rc4Encrypt(key, unescape(encodeURIComponent(str))));
            },
            rc4DecryptStr: function (hexStr, key) {
                return decodeURIComponent(escape($.rc4Decrypt(key, $.hexDecode(hexStr))));
            }
        });
        $.rc4 = {};
        $.fn.rc4.ctrlrInst = null;
        $.fn.rc4.ctrlr = function (settings) {
            this.settings = settings;
        };
        var ctrlr = $.fn.rc4.ctrlr;
        ctrlr.prototype.initialise = function () {
            if (this.settings.key) {
                if (this.settings.method) {
                    if ($.trim(this.settings.method.toUpperCase()) == "ENCRYPT") {
                        this.setObjectValue($.hexEncode($.rc4Encrypt(this.settings.key, this.getObjectValue())))
                    }
                    if ($.trim(this.settings.method.toUpperCase()) == "DECRYPT") {
                        this.setObjectValue($.rc4Decrypt(this.settings.key, $.hexDecode(this.getObjectValue())));
                    }
                }
            };
        }
        ctrlr.prototype.getObjectValue = function () {
            if ($.fn.rc4.ctrlrInst.container.innerHTML) {
                return $.fn.rc4.ctrlrInst.container.innerHTML;
            }
            if ($.fn.rc4.ctrlrInst.container.value) {
                return $.fn.rc4.ctrlrInst.container.value;
            }
        }
        ctrlr.prototype.setObjectValue = function (data) {
            if ($.fn.rc4.ctrlrInst.container.innerHTML) {
                $.fn.rc4.ctrlrInst.container.innerHTML = data;
            }
            if ($.fn.rc4.ctrlrInst.container.value) {
                $.fn.rc4.ctrlrInst.container.value = data;
            }
        }
    })(jQuery);
}


/**
* @author: Muhammad Hashim
* @since: Wednesday, April 20, 2011
* @Desc: Send chat invitation to Buyer.
* @Params:
*    new_customer_im_id :  Buyer Email Id
*    username : Buyer Username.
*    chat_im_id (global): Seller Email Id. (variable, chat_im_id set from chatwindow.php file in view/im folder)
* */
function add_buyer(new_customer_im_id, username, firstname, lastname)
{
    try
    {
        jQuery.getJSON(chat_im_getmessage_url + "?callback=?",
        {
            "action": "addUser",
            "CustomerIMId": jQuery.rc4DecryptStr(chat_im_id, chat_user_id),
            "NewCustomerIMId": new_customer_im_id,
            "UserName": username,
            "rtype": "JSON",
            "noCache": Math.floor(Math.random() * 100001)
        },
        function (data)
        {
            if (data.response.success)
            {
				alert("Buyer (" + username + ") has been added successfully.");
				jQuery("#div_user_info").append(" , <b>" + firstname + " " + lastname + "</b> (Buyer)");
                jQuery('#div_user_account :input').attr('disabled', true);
				jQuery('#div_user_search :input').attr('disabled', true);
            }
            else
            {
                jQuery('#div_user_account :input').attr('disabled', false);
				jQuery('#div_user_search :input').attr('disabled', false);
                jQuery("#chatCustomer .chatboxmessage").append(data.response.error);
            }
        });
    }
    catch(e)
    {
		alert (e);
        jQuery('#div_user_account :input').attr('disabled', false);
        jQuery("#chatCustomer .chatboxmessage").append("There is some error in sending invitation, please try later");
    }

}


function get_presence()
{
    user_val = jQuery.trim(jQuery("#buyer_val").val());

    if (user_val == "")
        return;
    
    var user_info = new Array();
    var user_email_id = "";

    jQuery.getJSON(chat_im_presence_url[0] + "?callback=?", {
        "action": "presenceInfoExtended",
        "userids": user_val,
        "rtype": "JSON",
        "noCache": Math.floor(Math.random() * 100001)
        },
        function (data)
        {
            try
            {
                jQuery("#user_messages").html("");
                jQuery("#user_account").html("");
                var user_email_id = "";
                var username = "";
                var firstname = "";
                var lastname = "";

                if (data.response.success)
                {
                    if (data.response.Users.OnlineUsers.Records > 0)
                    {
                        var online = data.response.Users.OnlineUsers.User;

                        for (var i = 0; i < data.response.Users.OnlineUsers.Records; i++)
                        {
                            if (online[i] != null && online[i] != "")
                            {
                                user_info = online[i].split("|");

                                user_email_id = jQuery.trim(user_info[1]);
                                username = jQuery.trim(user_info[4]);
                                firstname = jQuery.trim(user_info[5]);
                                lastname = jQuery.trim(user_info[6]);

                                arr_user_email = user_email_id.split("@");
                                account_domain = arr_user_email[1];

                                jQuery("#user_account").append("<option value='"+ username + "<<>>" + user_email_id +"'> "+ account_domain +" </option>");
                            }
                        }

                        jQuery("#div_user_account").css("display", "block");

                        jQuery("#add_buyer").click
                        (
                            function ()
                            {
                                user_account_value = jQuery("#user_account").val();
                                arr_user_account_value = user_account_value.split("<<>>");

                                user_name = jQuery.trim(arr_user_account_value[0]);
                                user_email_id = jQuery.trim(arr_user_account_value[1]);

                                add_buyer(user_email_id, user_name, firstname, lastname);
                            }
                        );
                    }
                    else
                    {
                        jQuery("#div_user_account").css("display", "none");
                        jQuery("#user_messages").html("Buyer Presence not found. <br /><br /> ");
                    }
                }
                

            }
            catch (e)
            {
            }
        }
    )
}


function chat_get_impresence() {
    if (img_users.length == 0) return;
    var place_holder = "CHAT_STATUS_";
    var user_info = new Array();
    for (var img_index = 1; img_index < img_users.length; img_index++) {
        if (typeof(img_users[img_index]) == "undefined") continue;
        jQuery.getJSON(chat_im_presence_url[(img_index - 1)] + "?callback=?", {
            "action": "presenceInfo",
            "userids": array_unique(img_users[img_index]).toString(),
            "rtype": "JSON",
            "noCache": Math.floor(Math.random() * 100001)
        }, function (data) {
            try {
                if (data.response.success) {
                    if (data.response.Users.OnlineUsers.Records > 0 || data.response.Users.OfflineUsers.Records > 0) {
                        if (data.response.Users.OnlineUsers.Records > 0) {
                            var online = data.response.Users.OnlineUsers.User;
                            for (var i = 0; i < data.response.Users.OnlineUsers.Records; i++) {
                                if (online[i] != null && online[i] != "") {
                                    user_info[user_info.length] = Array(true).concat(online[i].split("|"));
                                }
                            }
                        }
                        if (data.response.Users.OfflineUsers.Records > 0) {
                            var offline = data.response.Users.OfflineUsers.User;
                            for (var i = 0; i < data.response.Users.OfflineUsers.Records; i++) {
                                if (offline[i] != null && offline[i] != "") user_info[user_info.length] = Array(false).concat(offline[i].split("|"));
                            }
                        }
                        user_info = array_unique(user_info);
                        for (var i = 0; i < userid_array.length; i++) {
                            for (var j = 0; j < user_info.length; j++) {
                                if (jQuery('#' + place_holder + userid_array[i]).html().search('Online') == -1 && jQuery('#' + place_holder + userid_array[i]).html().search('Offline') == -1) jQuery('#' + place_holder + userid_array[i]).html("");
                                if (userid_array[i] == user_info[j][1]) {
                                    var im_id = jQuery.rc4EncryptStr(user_info[j][2], user_info[j][1]);
                                    jQuery('#CHAT_ICON_STATUS_' + user_info[j][3] + im_id).remove();
                                    if (user_info[j][0]) {
                                        try {
                                            for (var k = 0; k < img_server.length; k++) {
                                                if (user_info[j][2] == img_server[k][0]) break;
                                            }
                                            jQuery('#' + place_holder + userid_array[i]).append("<span id='CHAT_ICON_STATUS_" + user_info[j][3] + im_id + "' style='float:left;cursor:pointer;height:26px;width:26px;display:inline-block;margin-right:2px;background-image:url(" + chat_image_url + "chat_status.gif);background-position: -" + (parseInt(user_info[j][3]) * 26) + "px -" + ((parseInt(user_info[j][4]) + 1) * 26) + "px;' onclick='chat_start_chat(\"" + user_info[j][1] + "\",\"" + im_id + "\",\"" + jQuery('#' + place_holder + userid_array[i]).attr("title") + "\", " + user_info[j][3] + ", " + img_server[k][1] + ");' title='Online " + ((parseInt(user_info[j][4])) ? "- Busy in chat " : "") + "[" + bot_type[user_info[j][3]] + "]' alt='Online [" + bot_type[user_info[j][3]] + "]'" + ((parseInt(user_info[j][4])) ? " class='CHAT_STATUS_BUSY_" + userid_array[i] + "'" : "") + ">&nbsp;</span>");
                                        } catch (e) {}
                                    } else {
                                        jQuery('#' + place_holder + userid_array[i]).append("<span id='CHAT_ICON_STATUS_" + user_info[j][3] + im_id + "' style='float:left;height:26px;width:26px;display:inline-block;margin-right:2px;background-image:url(" + chat_image_url + "chat_status.gif);background-position: -" + (parseInt(user_info[j][3]) * 26) + "px -0px;' title='Offline [" + bot_type[user_info[j][3]] + "]' alt='Offline [" + bot_type[user_info[j][3]] + "]' >&nbsp;</span>");
                                    }
                                    if (chat_show_chatlog == '1' && jQuery('#' + place_holder + userid_array[i]).html().search('Chat Log') == -1) jQuery('#' + place_holder + userid_array[i]).append('<a href="javascript:display_chatlog(\'' + user_info[j][1] + '\', this)" style="float:right;" title="View last chat">Chat Log</a>');
                                }
                            }
                            if (chat_show_addcontact == '1' && jQuery('#' + place_holder + userid_array[i]).html().search('Add contact') == -1) jQuery('#' + place_holder + userid_array[i]).append("<img border='0' alt='Add contact' title='Add contact' src='" + chat_image_url + "chat_add_contact.png' style='cursor:pointer;cursor:hand;margin-left:2px;vertical-align:middle;' onclick='chat_add_contact(\"" + userid_array[i] + "\");' />");
                        }
                    } else {
                        if (chat_show_addcontact == '1') for (var i = 0; i < userid_array.length; i++)
                        jQuery('#' + place_holder + userid_array[i]).html("<img border='0' alt='Add contact' title='Add contact' src='" + chat_image_url + "chat_add_contact.png' style='cursor:pointer;cursor:hand;margin-left:2px;vertical-align:middle;' onclick='chat_add_contact(\"" + userid_array[i] + "\");' />");
                    }
                } else {
                    for (var i = 0; i < userid_array.length; i++) {
                        jQuery('#' + place_holder + userid_array[i]).html("<img border='0' alt='Offline' title='Offline user' src='" + chat_image_url + "chat_status_offline.png' />");
                        if (chat_show_addcontact == '1') jQuery('#' + place_holder + userid_array[i]).append("<img border='0' alt='Add contact' title='Add contact' src='" + chat_image_url + "chat_add_contact.png' style='cursor:pointer;cursor:hand;margin-left:2px;' onclick='chat_add_contact(\"" + userid_array[i] + "\");' />");
                    }
                }
            } catch (e) {
                for (var i = 0; i < userid_array.length; i++) {
                    jQuery('#' + place_holder + userid_array[i] + ' img').remove();
                    jQuery('#' + place_holder + userid_array[i]).append("<img border='0' alt='Offline server' title='Offline server' src='" + chat_image_url + "chat_status_offline.png' />");
                }
            }
            chat_get_agent_inchat();
        });
    }
    setTimeout("chat_get_impresence()", 60000);
}


function close_all_menus()
{
    if(jQuery("#emoticon_list").is(':visible'))
    	jQuery("#emoticon_list").hide();

	if(jQuery("#file_transfer_list").is(':visible'))
    	jQuery("#file_transfer_list").hide();

    if(jQuery("#cds_content_list").is(':visible'))
    	jQuery("#cds_content_list").hide();

    if(jQuery("#chat_tags_list").is(':visible'))
    	jQuery("#chat_tags_list").hide();
}


function chat_translate(from, to)
{
    close_all_menus();

    chatboxtextarea = jQuery('#chatbox #chatCustomer .chatboxtextarea');
    var text = jQuery(chatboxtextarea).val();
    if (jQuery.trim(text) == "") return;
    google.language.translate(text, from, to, function (result) {
        if (result.translation) {
            jQuery(chatboxtextarea).val(result.translation)
        }
    });
}

function resize_window() {
    jQuery("#chatCustomer .chatboxcontent").css('height', (jQuery("#chatbox").innerHeight() - jQuery("#chatCustomer .chatboxhead").innerHeight() - jQuery("#chatCustomer  .chatboxinput").innerHeight() - 15) + "px");
    jQuery("#chatAgent .chatboxcontent").css('height', (jQuery("#chatbox").innerHeight() - jQuery("#chatAgent .chatagentlist").innerHeight() - jQuery("#chatAgent .chatboxinput").innerHeight() - jQuery("#chatAgent .addbuyerwindow").innerHeight() - 15) + "px");
}
var userid_array;
var img_users;
var img_server;

function chat_get_status() {
    var place_holder = "CHAT_STATUS_"; {
        userid_array = new Array();
        var body_ele = jQuery("body").find("*");
        for (var i = 0; i < body_ele.length; i++) {
            if (body_ele[i].id.match(place_holder)) {
                id = body_ele[i].id.replace(place_holder, "");
                jQuery('#' + place_holder + id).html('<img border="0" alt="Loading..." title="Loading online status" src="' + chat_image_url + 'chat_status_loading.gif" />');
                if (chat_show_chatlog == '1') jQuery('#' + place_holder + id).append('<a href="javascript:display_chatlog(\'' + id + '\', this)" style="float:right;" title="View last chat">Chat Log</a>');
                userid_array[userid_array.length] = id;
            }
        }
        userid_array = array_unique(userid_array);
    }
    if (userid_array.length > 0) {
        {
            jQuery.getJSON(chat_im_gw_resolution_url + "?callback=?", {
                "action": "imGatewayResolution",
                "userids": userid_array.toString(),
                "type": 1,
                "rtype": "JSON",
                "noCache": Math.floor(Math.random() * 100001)
            }, function (img_data) {
                img_users = new Array();
                img_server = new Array();
                if (img_data.response.success) {
                    if (img_data.response.IMG != null && img_data.response.IMG.IMG != null) {
                        for (var img_index = 0; img_index < img_data.response.IMG.IMG.length - 1; img_index++) {
                            var img_temp = img_data.response.IMG.IMG[img_index].split("|");
                            if (img_temp[2] == 2) continue;
                            img_server[img_server.length] = new Array(img_temp[1], img_temp[2]);
                            if (typeof(img_users[parseInt(img_temp[2])]) == "undefined") img_users[parseInt(img_temp[2])] = new Array(img_temp[0]);
                            else
                            img_users[parseInt(img_temp[2])][img_users[parseInt(img_temp[2])].length] = img_temp[0];
                        }
                    }
                }
                if (img_users.length == 0) {
                    for (var i = 0; i < userid_array.length; i++) {
                        if (chat_show_addcontact == '1') jQuery('#' + place_holder + userid_array[i]).html("<img border='0' alt='Add contact' title='Add contact' src='" + chat_image_url + "chat_add_contact.png' style='cursor:pointer;cursor:hand;margin-left:2px;' onclick='chat_add_contact(\"" + userid_array[i] + "\");' />");
                        else
                        jQuery('#' + place_holder + userid_array[i]).html("");
                    }
                    return;
                }
                chat_get_impresence();
            });
        }
    }
}

function chat_add_contact(userid) {
    var win = window.open(chat_site_url + "index.html?action=im_chat_adduser&uid=" + userid, "CHAT_ADD_USER", "width=600,height=300");
    win.focus();
}

function chat_start_chat(chat_user_id, chat_im_id, nickname, bot_type, server) {
    if (typeof(is_b2c) != "undefined" && is_b2c) {
        var win = window.open(chat_site_url + "index.html?action=im_chat_chatwindow&uid=" + chat_user_id + "&id=" + chat_im_id + "&nickname=" + nickname + "&bot=" + bot_type + "&server=" + server, "CHAT_WINDOWS_" + chat_user_id + bot_type, "location=no,toolbar=0,resizable=1,status=no");
        win.focus();
    }
}

function chat_chatbox_input(event, chatboxtextarea, usertype) {
    if (chat_im_sendmessage_url == null) return;
    if (event.keyCode == 13 && event.ctrlKey == 0 && event.shiftKey == 0) {
        message = jQuery(chatboxtextarea).val();
        message = message.replace(/^\s+|\s+$/g, "");
        if (message == '') return false;
        var agent_ids = "";
        if (usertype == null) usertype = "Customer";
        if (usertype == "Agent") {
            selected_agent = jQuery("#agentlist option:selected");
            for (var i = 0; i < selected_agent.length; i++)
            agent_ids += selected_agent[i].value + ",";
            if (agent_ids == "") {
                selected_agent = jQuery("#agentlist option");
                for (var i = 0; i < selected_agent.length; i++)
                agent_ids += selected_agent[i].value + ",";
                if (agent_ids == "") {
                    alert("No agent exist in this chat session");
                    jQuery(chatboxtextarea).val(jQuery.trim(message));
                    return;
                }
            }
            chat_display_msg(message, "Me", usertype);
        }
        jQuery(chatboxtextarea).val('Message sending...');
        jQuery(chatboxtextarea).attr("disabled", "disabled");
        jQuery(chatboxtextarea).focus();
        clearTimeout(chat_heartbeatTimer);
        chat_heartbeatTimer = null;
        chat_wait4send_msg++;
        try {
            jQuery.getJSON(chat_im_sendmessage_url + "?callback=?", {
                "action": "sendMessage",
                "AgentID": chat_agent_id,
                "CustomerIMId": jQuery.rc4DecryptStr(chat_im_id, chat_user_id),
                "UserId": chat_user_id,
                "Message": urlencode(message),
                "fmi": chat_fmi,
                "MessageType": usertype + "Message",
                "RecipientAgentUsername": agent_ids,
                "rtype": "JSON",
                "noCache": Math.floor(Math.random() * 100001)
            }, function (data) {
                if (data.response.success) {
                    if (data.response.messages != null) {
                        if (data.response.messages.message != null && data.response.messages.message instanceof Array) {
                            for (var counter = 0; counter < data.response.messages.message.length - 1; counter++) {
                                if (data.response.messages.message[counter].type == "EN_MSG") {
                                    var message_data = data.response.messages.message[counter].content.toString().split("|");
                                    chat_fmi = parseInt(message_data[0]) + 1;
                                    var nickname = (message_data[1] == "CustomerMessage") ? chat_nickname : message_data[1];
                                    var message = message_data[2];
                                    for (var i = 3; i < message_data.length; i++)
                                    message += "|" + message_data[i];
                                    chat_display_msg(message, nickname, usertype);
                                    chat_stop_heartbeat = false;
                                } else {
                                    chat_display_msg(data.response.messages.message[counter].content.toString());
                                    chat_stop_heartbeat = true;
                                }
                            }
                        }
                    }
                } else
                chat_display_msg("Undelivered: " + data.response.error, null, usertype);
                chat_wait4send_msg--;
                if (!chat_stop_heartbeat && chat_heartbeatTimer == null) chat_heartbeatTimer = setTimeout('chat_get_msg()', 5000);
                if (jQuery("#chatCustomer .chatboxtextarea").attr("disabled") != "") {
                    jQuery("#chatCustomer .chatboxtextarea").removeAttr("disabled");
                    jQuery("#chatCustomer .chatboxtextarea").val('');
                }
                if (trim(jQuery("#agentlist").text()) != "" && jQuery("#chatAgent .chatboxtextarea").attr("disabled") != "") {
                    jQuery("#chatAgent .chatboxtextarea").removeAttr("disabled");
                    jQuery("#chatAgent .chatboxtextarea").val('');
                }
            });
            return false;
        } catch (e) {
            chat_wait4send_msg--;
            if (!chat_stop_heartbeat && chat_heartbeatTimer == null) chat_heartbeatTimer = setTimeout('chat_get_msg()', 5000);
            if (jQuery("#chatCustomer .chatboxtextarea").attr("disabled") != "") {
                jQuery("#chatCustomer .chatboxtextarea").removeAttr("disabled");
                jQuery("#chatCustomer .chatboxtextarea").val('');
            }
            if (jQuery("#chatAgent .chatboxtextarea").attr("disabled") != "") {
                jQuery("#chatAgent .chatboxtextarea").removeAttr("disabled");
                jQuery("#chatAgent .chatboxtextarea").val('');
            }
            return false;
        }
    } else if (event.keyCode == 13 && event.ctrlKey) {
        jQuery(chatboxtextarea).insertAtCaret("\n");
    }
}

function init_agent_session() {
    try {
        jQuery.getJSON(chat_im_getmessage_url + "?callback=?", {
            "action": "sessionInitiation",
            "AgentID": chat_agent_id,
            "CustomerIMId": jQuery.rc4DecryptStr(chat_im_id, chat_user_id),
            "UserId": chat_user_id,
            "rtype": "JSON",
            "noCache": Math.floor(Math.random() * 100001)
        }, function (data) {
            if (data.response.success) {
                chat_fmi = (data.response.fmi == null) ? 0 : data.response.fmi;
                if (chat_fmi > 0 && !chat_stop_heartbeat) chat_heartbeatTimer = setTimeout('chat_get_msg()', 5);
                else if (chat_proactive) chat_heartbeatTimer = setTimeout('chat_get_msg()', 5);
            }
        });
    } catch (e) {}
}

function chat_get_msg() {
    try {
        jQuery.getJSON(chat_im_getmessage_url + "?callback=?", {
            "action": "getMessage",
            "AgentID": chat_agent_id,
            "CustomerIMId": jQuery.rc4DecryptStr(chat_im_id, chat_user_id),
            "UserId": chat_user_id,
            "fmi": chat_fmi,
            "rtype": "JSON",
            "noCache": Math.floor(Math.random() * 100001)
        }, function (data) {
            if (data.response.success) {
                if (document.getElementById("agentlist") != "undefined") {
                    if (data.response.agents != null) {
                        if (data.response.agents.agent != null) {
                            var agents_html = "";
                            var agents_text = "";
                            for (var i = 0; i < data.response.agents.agent.length - 1; i++) {
                                var agent_info = data.response.agents.agent[i].split("|");
                                if (agent_info[2] == chat_agent_id) continue;
                                agents_html += '<option value="' + agent_info[2] + '">' + agent_info[0] + ' (' + agent_info[1] + ')</option>';
                                agents_text += agent_info[0] + ' (' + agent_info[1] + ')';
                            }
                            if (jQuery.trim(jQuery("#agentlist").text().replace(/ /g, "")) != jQuery.trim(agents_text).replace(/ /g, "")) jQuery("#agentlist").html(agents_html);
                            if (trim(jQuery("#agentlist").text()) == "") jQuery("#chatAgent .chatboxtextarea").attr("disabled", "disabled");
                            else
                            jQuery("#chatAgent .chatboxtextarea").removeAttr("disabled");
                        }
                        if (data.response.agents.AgentMessages != null && data.response.agents.AgentMessages instanceof Array) {
                            for (var counter = 0; counter < data.response.agents.AgentMessages.length - 1; counter++) {
                                var message = "";
                                if (data.response.agents.AgentMessages[counter] != null) {
                                    var message_data = data.response.agents.AgentMessages[counter].toString().split("|");
                                    var nickname = message_data[0];
                                    message = message_data[1];
                                    for (var i = 2; i < message_data.length; i++)
                                    message += "|" + message_data[i];
                                    chat_display_msg(message, nickname, "Agent");
                                }
                                chat_blink_title(message);
                            }
                        }
                    }
                }
                if (chat_wait4send_msg > 0) return;
                if (data.response.messages != null) {
                    if (data.response.messages.message != null && data.response.messages.message instanceof Array) {
                        for (var counter = 0; counter < data.response.messages.message.length - 1; counter++) {
                            var message = "";
                            if (data.response.messages.message[counter].type == "EN_MSG") {
                                var message_data = data.response.messages.message[counter].content.toString().split("|");
                                chat_fmi = parseInt(message_data[0]) + 1;
                                var nickname = (message_data[1] == "CustomerMessage") ? chat_nickname : message_data[1];
                                message = message_data[2];
                                for (var i = 3; i < message_data.length; i++)
                                message += "|" + message_data[i];
                                chat_display_msg(message, nickname);
                            } else {
                                chat_display_msg(data.response.messages.message[counter].content.toString());
                                chat_stop_heartbeat = true;
                            }
                            chat_blink_title(message);
                        }
                    }
                }
            }
            if (!chat_stop_heartbeat) chat_heartbeatTimer = setTimeout('chat_get_msg()', 5000);
        });
    } catch (e) {
        if (!chat_stop_heartbeat) chat_heartbeatTimer = setTimeout('chat_get_msg()', 5000);
    }
    if (chat_last_msg_count == 0) {
        var currentTime = new Date();
        var month = currentTime.getMonth() + 1;
        var day = currentTime.getDate();
        var hours = currentTime.getHours();
        var minutes = currentTime.getMinutes();
        chat_last_time_str = ((day < 10) ? '0' + day : day) + '/' + ((month < 10) ? '0' + month : month) + ' at ' + ((hours > 12) ? (hours - 12) : hours) + ':' + ((minutes < 10) ? '0' + minutes : minutes) + ' ' + ((hours > 12) ? ' PM' : ' AM');
    } else if (chat_last_msg_count == 3 && jQuery.trim(jQuery("#chatCustomer .chatboxcontent .chatboxmessage").text().replace(/ /g, "")) != "") {
        jQuery("#chatCustomer .chatboxcontent").append('<div class="lasttimemsg">Last message received on ' + chat_last_time_str + '</div>');
        jQuery("#chatCustomer .chatboxcontent .lasttimemsg").fadeIn("show");
        jQuery("#chatCustomer .chatboxcontent").scrollTop(jQuery("#chatbox .chatboxcontent")[0].scrollHeight);
    }
    chat_last_msg_count++;
}


function chat_close_session()
{
    close_all_menus();

    try {
        jQuery.getJSON(chat_im_chatclose_url + "?callback=?", {
            "action": "closeSession",
            "CustomerIMId": jQuery.rc4DecryptStr(chat_im_id, chat_user_id),
            "AgentID": chat_agent_id,
            "rtype": "JSON",
            "noCache": Math.floor(Math.random() * 100001)
        }, function (data) {
            if (data.response.success) {
                is_chat_saved = true;
                window.close();
            } else {
                alert("Your chat is not saved, Please contact system administrator.");
            }
        });
        return false;
    } catch (e) {
        return false;
    }
}

function chat_impose_max_length(event, chatboxtextarea) {
    if (event.keyCode == 13 || event.keyCode == 8 || event.keyCode == 46 || (event.keyCode >= 37 && event.keyCode <= 40)) return true;
    return (chatboxtextarea.value.length <= chat_maxLen);
}

function chat_show_emoticon()
{
	if(jQuery("#file_transfer_list").is(':visible'))
    	jQuery("#file_transfer_list").hide();

    if(jQuery("#cds_content_list").is(':visible'))
    	jQuery("#cds_content_list").hide();

    if(jQuery("#chat_tags_list").is(':visible'))
    	jQuery("#chat_tags_list").hide();

	if(jQuery.browser.msie && !jQuery("#emoticon_list").is(':visible'))
    {
        jQuery('#chatbox .chatboxtextarea').focus();
        ie_sel = document.selection.createRange();
    }
    jQuery("#emoticon_list").toggle();
    if(jQuery("#emoticon_list").is(':visible'))
        jQuery("#emoticon_list").focus();
}

function chat_display_msg(message, title, chat_for) {
    if (typeof(message) != "string") return;
    if (jQuery("#chatbox .chatboxcontent .lasttimemsg").is(':visible')) jQuery("#chatbox .chatboxcontent .lasttimemsg").remove();
    message = urldecode(message);
    message = message.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\"/g, "&quot;").replace(/\n/g, "<br />");
    message = chat_replace_emoticon(message);
    if (chat_for == null) chat_for = "Customer";
    if (title == null) jQuery("#chatbox #chat" + chat_for + " .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxinfo" style="font-style:italic">' + message + '</span></div>');
    else {
        jQuery("#chatbox #chat" + chat_for + " .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">' + title + ':&nbsp;&nbsp;</span><span class="chatboxmessagecontent" id="transchat' + (++msgId) + '">' + message + '</span></div>');
        if (chat_for == "Customer") chat_translate_zh_to_en(msgId);
    }
    jQuery("#chatbox #chat" + chat_for + " .chatboxcontent").scrollTop(jQuery("#chatbox #chat" + chat_for + " .chatboxcontent")[0].scrollHeight);
    chat_last_msg_count = 0;
}

function chat_replace_emoticon(str) {
    str = str.replace(/:-?\)/g, "<span class='emoticon1'></span>");
    str = str.replace(/:-?D/ig, "<span class='emoticon2'></span>");
    str = str.replace(/;-?\)/g, "<span class='emoticon3'></span>");
    str = str.replace(/:-?O/ig, "<span class='emoticon4'></span>");
    str = str.replace(/:-?0/g, "<span class='emoticon4'></span>");
    str = str.replace(/:-?P/ig, "<span class='emoticon5'></span>");
    str = str.replace(/\(H\)/ig, "<span class='emoticon12'></span>");
    str = str.replace(/\B-?\)/ig, "<span class='emoticon12'></span>");
    str = str.replace(/:-?\@/g, "<span class='emoticon7'></span>");
    str = str.replace(/X\(/ig, "<span class='emoticon7'></span>");
    str = str.replace(/:-?S/ig, "<span class='emoticon8'></span>");
    str = str.replace(/:\"\>/g, "<span class='emoticon9'></span>");
    str = str.replace(/:-?\$/g, "<span class='emoticon9'></span>");
    str = str.replace(/:-?\(/g, "<span class='emoticon10'></span>");
    str = str.replace(/:'\(/g, "<span class='emoticon11'></span>");
    str = str.replace(/:-?\(\(/g, "<span class='emoticon11'></span>");
    str = str.replace(/\(L\)/ig, "<span class='emoticon12'></span>");
    str = str.replace(/:-?X/ig, "<span class='emoticon12'></span>");
    str = str.replace(/\(U\)/ig, "<span class='emoticon13'></span>");
    str = str.replace(/\=\(\(/ig, "<span class='emoticon13'></span>");
    str = str.replace(/\(F\)/ig, "<span class='emoticon14'></span>");
    str = str.replace(/\@\};-/ig, "<span class='emoticon14'></span>");
    str = str.replace(/\(W\)/ig, "<span class='emoticon15'></span>");
    str = str.replace(/\(G\)/ig, "<span class='emoticon16'></span>");
    return str;
}

function chat_add_emoticon(obj) {
    classname = jQuery(obj).attr("class");
    i = parseInt(classname.replace('emoticon', '')) - 1;
    chatboxtextarea = jQuery('#chatbox #chatCustomer .chatboxtextarea');
    if (jQuery.browser.msie) {
        ie_sel.text = "";
    }
    chatboxtextarea.insertAtCaret(emoticon[i]);
    jQuery('#emoticon_list').toggle();
    chatboxtextarea.focus();
}

function enable_auto_translation(Obj) {
    if (isAutoTranslationEnabled) {
        isAutoTranslationEnabled = false
        Obj.style.border = '0px none white';
    } else {
        isAutoTranslationEnabled = true;
        Obj.style.border = '1px solid white';
    }
}

function chat_translate_zh_to_en(messageId) {
    if (isAutoTranslationEnabled) {
        var message = messageId + ":" + jQuery("#transchat" + messageId).text();
        google.language.translate(message, "zh-CN", "en", function (result) {
            if (result.translation) {
                message = result.translation;
            }
            var retVal = message;
            var seperatorIndex = retVal.indexOf(":");
            var _messageId = retVal.substr(0, seperatorIndex);
            if (seperatorIndex > 0) {
                var message = jQuery.trim(retVal.substr(seperatorIndex + 1, retVal.length));
                if (message.replace(/ /g, "") != jQuery("#transchat" + _messageId).text().replace(/ /g, "")) var messageSpan = jQuery("#transchat" + _messageId).append(" (" + message + ")");
            }
        });
    }
}

function chat_show_file_list()
{
	if(jQuery("#emoticon_list").is(':visible'))
    	jQuery("#emoticon_list").hide();

    if(jQuery("#chat_tags_list").is(':visible'))
    	jQuery("#chat_tags_list").hide();

    if(jQuery("#cds_content_list").is(':visible'))
    	jQuery("#cds_content_list").hide();

	if(jQuery.browser.msie && !jQuery("#file_transfer_link").is(':visible'))
	{
        jQuery('#chatbox .chatboxtextarea').focus();
        ie_sel = document.selection.createRange();
    }

    jQuery("#file_transfer_list").toggle();
    if(jQuery("#file_transfer_list").is(':visible'))
        jQuery("#file_transfer_list").focus();
}

function chat_add_show_file_tag(value) {
    if (jQuery.browser.msie) {
        ie_sel.text = "";
    }
    jQuery('#chatbox #chatCustomer .chatboxtextarea').insertAtCaret(value);
    jQuery('#file_transfer_list').toggle();
    chatboxtextarea.focus();
}

function chat_send_file_mail(file) {
    if (file == null) return;
    jQuery.getJSON(chat_site_url + "index.html", {
        "action": "im_chat_sendfilemail",
        "agentid": chat_agent_id,
        "uid": chat_user_id,
        "file": file,
        "return": "json",
        "noCache": Math.floor(Math.random() * 100001)
    }, function (response) {
        if (response.success) chat_display_msg("File successfully sent via email", null, "Customer");
        else
        chat_display_msg("Failure: " + response.error, null, "Customer");
    });
    jQuery('#file_transfer_list').toggle();
    jQuery('#chatbox #chatCustomer .chatboxtextarea').focus();
}

function chat_show_tags()
{
    if(jQuery("#emoticon_list").is(':visible'))
    	jQuery("#emoticon_list").hide();

	if(jQuery("#file_transfer_list").is(':visible'))
    	jQuery("#file_transfer_list").hide();

    if(jQuery("#cds_content_list").is(':visible'))
    	jQuery("#cds_content_list").hide();

	if(jQuery.browser.msie && !jQuery("#chat_tags_list").is(':visible'))
    {
        jQuery('#chatbox .chatboxtextarea').focus();
        ie_sel = document.selection.createRange();
    }

    jQuery("#chat_tags_list").toggle();

    if(jQuery("#chat_tags_list").is(':visible'))
        jQuery("#chat_tags_list").focus();
}


function cds_content_urls()
{
    if(jQuery("#emoticon_list").is(':visible'))
    	jQuery("#emoticon_list").hide();

	if(jQuery("#file_transfer_list").is(':visible'))
    	jQuery("#file_transfer_list").hide();

    if(jQuery("#chat_tags_list").is(':visible'))
    	jQuery("#chat_tags_list").hide();
    
	if(jQuery.browser.msie && !jQuery("#cds_content_list").is(':visible'))
    {
        jQuery('#chatbox .chatboxtextarea').focus();
    	ie_sel = document.selection.createRange();
    }
    
    jQuery('#cds_content_list').toggle();

    if(jQuery("#cds_content_list").is(':visible'))
        jQuery("#cds_content_list").focus();
}


function chat_add_content(value, key)
{
    if (key == chat_content.SHORTCUT)
    {
        if(jQuery.browser.msie)
            ie_sel.text = "";

        jQuery('#chatbox #chatCustomer .chatboxtextarea').insertAtCaret(value);
        jQuery('#chat_tags_list').toggle();

        chatboxtextarea.focus();
    }
    else if (key == chat_content.CDS_CONTENT_LIST)
    {
        if(jQuery.browser.msie)
            ie_sel.text = "";

        jQuery('#chatbox #chatCustomer .chatboxtextarea').insertAtCaret(value);
        jQuery('#cds_content_list').toggle();

        chatboxtextarea.focus();
    }
}



function chat_add_tag(value)
{

    if(jQuery.browser.msie)
    {
        ie_sel.text = "";
    }
    jQuery('#chatbox #chatCustomer .chatboxtextarea').insertAtCaret(value);
    jQuery('#chat_tags_list').toggle();
    chatboxtextarea.focus();
}

function chat_blink_title(message) {
    if (!chat_windowHasFocus) {
        if (jQuery.trim(document.title) != jQuery.trim(jQuery("#chatbox .chatboxhead").text())) document.title = jQuery("#chatbox .chatboxhead").text();
        else {
            if (message == "") document.title = "NEW MESSAGE";
            else
            document.title = urldecode(message);
        }
        setTimeout("chat_blink_title('" + message + "')", 1000);
    } else
    document.title = jQuery("#chatbox .chatboxhead").text();
}

function toggle_memberinfo() {
    jQuery("#chatmemberinfo").toggle();
    resize_window();
}

function toggle_agentarea() {
    jQuery('#chatAgent').toggle();
    if (jQuery("#chatAgent").css('width') == "10px") {
        jQuery('#chatAgent *').show();
        jQuery('#chatAgent').animate({
            width: "300px"
        }, 500);
        jQuery('#chatCustomer').animate({
            marginRight: "300px"
        }, 500);
        jQuery("#agent_separator").css('opacity', "0.1");
        jQuery("#agent_separator").css('background-position', '0px center');
		resize_window();		
    } else {
        jQuery('#chatAgent *').hide();
        jQuery('#chatAgent').animate({
            width: "10px"
        }, 500);
        jQuery('#chatCustomer').animate({
            marginRight: "10px"
        }, 500);
        if (separator_timer != null) clearTimeout(separator_timer);
        jQuery("#agent_separator").show();
        jQuery("#agent_separator").css('background-position', '-10px center');
        jQuery("#agent_separator").css('opacity', "1");
    }
}

function display_history(duration) {
    if (duration == null) {
        jQuery("#chathistory").html("");
        return;
    }
    jQuery.getJSON(chat_site_url + "index.html", {
        "action": "im_chat_getchathistory",
        "agentid": chat_agent_id,
        "uid": chat_user_id,
        "starttime": chat_start_time,
        "now": new Date(),
        "duration": duration,
        "return": "json",
        "noCache": Math.floor(Math.random() * 100001)
    }, function (data) {
        if (data.messages != null) jQuery("#chathistory").html(chat_replace_emoticon(data.messages));
        else
        jQuery("#chathistory").html("");
    });
}
var last_chat_logid;

function display_chatlog(uid, chat_obj) {
    if (jQuery('#chat_log_div').is(':visible') && last_chat_logid == uid) {
        jQuery('#chat_log_div').hide();
        return;
    }
    last_chat_logid = uid;
    jQuery.ajax({
        url: chat_site_url + "index.html",
        data: {
            "action": "im_chat_getchatlog",
            "uid": uid,
            "noCache": Math.floor(Math.random() * 100001)
        },
        success: function (data) {
            if (document.getElementById('chat_log') == null) {
                jQuery('body').append("<div id='chat_log_div' style='position:fixed;top:30%;width:100%;display:none;'></div>");
                if (jQuery.browser.msie) {
                    jQuery('#chat_log_div').css({
                        position: "absolute"
                    });
                    jQuery('#chat_log_div').css({
                        top: document.body.scrollTop + document.body.clientHeight / 3
                    });
                    jQuery(window).scroll(function () {
                        if (jQuery('#chat_log_div').is(':visible')) jQuery('#chat_log_div').css({
                            top: document.body.scrollTop + document.body.clientHeight / 3
                        });
                    })
                }
            }
            jQuery('#chat_log_div').html(data);
            jQuery('#chat_log_div').show();
        }
    });
}

function chat_get_agent_inchat() {
    var userid_busy = new Array();
    var place_holder = "CHAT_STATUS_BUSY_";
    var body_ele = jQuery("body").find("*");
    for (var i = 0; i < body_ele.length; i++) {
        if (body_ele[i].className.match(place_holder)) userid_busy[userid_busy.length] = body_ele[i].className.replace(place_holder, "");
    }
    userid_busy = array_unique(userid_busy);
    if (userid_busy.length > 0) {
        jQuery.getJSON(chat_site_url + "index.html?callback=?", {
            "action": "im_chat_getagentinchat",
            "uid": userid_busy.toString(),
            "return": "json-x",
            "noCache": Math.floor(Math.random() * 100001)
        }, function (response) {
            if (response.Agents != null) {
                for (var i = 0; i < response.Agents.length; i++) {
                    obj = jQuery('.' + place_holder + response.Agents[i].UserID);
                    obj.attr("title", "Busy with agent: " + response.Agents[i].Name + " [" + response.Agents[i].Username + "]");
                }
            }
        });
    }
}


function chat_show_forwardChat(chat_user_id, chat_im_id, nickname, server)
{
    close_all_menus();

    jQuery("#tranfer_user_id").val(chat_user_id);
    jQuery("#tranfer_im_id").val(chat_im_id);
    jQuery("#tranfer_server").val(server);
    jQuery("#transfer_nickname").val(nickname);
    jQuery("#customerid_span").text(" [" + nickname + "]");
    jQuery("#tranfer_agent_id").val("");
    jQuery.getJSON(chat_im_sendmessage_url + "/?callback=?", {
        "action": "agentStatus",
        "key": "online",
        "rtype": "JSON",
        "noCache": Math.floor(Math.random() * 100001)
    }, function (data) {
        if (data.response.success) {
            if (data.response.result != null) {
                var agent_online = data.response.result.toString().split(",");
                if (typeof all_agents_options == "undefined") all_agents_options = jQuery("#tranfer_agent_id").html();
                jQuery("#tranfer_agent_id").html(all_agents_options);
                agent_options = jQuery("#tranfer_agent_id option");
                for (var i = 1; i < agent_options.length; i++) {
                    if (jQuery(agent_options[i]).val() == chat_agent_id) {
                        jQuery(agent_options[i]).remove();
                        continue;
                    }
                    var j;
                    for (j = 0; j < agent_online.length; j++) {
                        if (jQuery(agent_options[i]).val() == agent_online[j]) break;
                    }
                    if (j == agent_online.length) jQuery(agent_options[i]).remove();
                }
                jQuery("#chat_transfer_div").show();
            } else
            alert("All agents are offline.");
        } else
        alert("Fail to get online agents.");
    });
}

function chat_forwardChat() {
    var agent_id = jQuery.trim(jQuery("#tranfer_agent_id").val());
    var chat_im_id = jQuery("#tranfer_im_id").val();
    var chat_user_id = jQuery("#tranfer_user_id").val();
    var nickname = jQuery("#transfer_nickname").val();
    var server = jQuery("#tranfer_server").val();
    if (agent_id == "") {
        chat_show_error("Invalid online agent");
        return false;
    }
    jQuery.getJSON(chat_im_presence_url[server - 1] + "/?callback=?", {
        "action": "forwardChat",
        "agentId": agent_id,
        "roomId": chat_room_id,
        "customerIMId": jQuery.rc4DecryptStr(chat_im_id, chat_user_id),
        "userId": chat_user_id,
        "nickname": nickname,
        "IMInstance": server,
        "type": "forward",
        "rtype": "JSON",
        "noCache": Math.floor(Math.random() * 100001)
    }, function (data) {
        if (data.response.success) jQuery("#chat_transfer_div").hide();
        else
        chat_show_error(data.response.error);
    });
}

function chat_show_error(message) {
    jQuery("#transfer_error_div div").text(message);
    jQuery("#transfer_error_div").show();
}

function array_unique(input_arr) {
    var tmp_arr = new Array();
    var input_len = input_arr.length;
    for (input_count = 0; input_count < input_len; input_count++) {
        var tmp_len = tmp_arr.length;
        for (tmp_count = 0; tmp_count < tmp_len; tmp_count++) {
            if (input_arr[input_count].toString() == tmp_arr[tmp_count].toString()) break;
        }
        if (tmp_count == tmp_len) tmp_arr[tmp_len] = input_arr[input_count];
    }
    return tmp_arr;
}

function urldecode(str) {
    return decodeURIComponent(str.replace(/\+/g, '%20'));
}

function urlencode(str) {
    return encodeURIComponent(str);
}

