﻿function FireUpChat() {
    $('#chat-close').click(function () {
        LClick('chat:close');
        clearInterval(chatTimer);
        if ($('#chat-panel').is(':visible')) {
            $('#chat-panel').hide(function () {
                $('#chat-transcript').show();
            });
        }
        else {
            CloseChatPanel();
        }
    });
    $('#chat-message').click(function () {
        if ($('#chat-message').val() == 'enter your message here') {
            $('#chat-message').val('');
        }
    });
    $('#chat-transcript-no').click(function () {
        CloseChatPanel();
    });
    $('#chat-transcript-yes').click(function () {
        EmailChat();
    });
}

var lastMsgId = 0;
var gettingMessages = false;
var chatTimer = null;
var k = '';
var sales = '';
var me = '';
var chatAttempts = 0;
var chatResponse = false;

function ChatMessage(msg) {
    this.MsgId = 0;
    this.MyId = me;
    this.Msg = msg;
    this.Key = k;
    return this;
}



function CloseChatPanel() {
    var url = 'handleChatSession.ashx?r=end';
    if (thisPage === 'news') { url = '../handleChatSession.ashx?r=end' };
    $('#chat-form').hide(function () {
        $('#chat-panel').hide();
        $('#chat-messages').html('');
        $('#chat-transcript').hide();
        $('#chat-keys').hide();
    });
    $.ajax({
        type: 'get',
        async: false,
        url: url,
        data: '{}',
        contentType: 'text/plain; charset=utf-8',
        dataType: 'text',
        error: function (e) {
        },
        success: function (data) {
        }
    });
    clearTimeout(chatTimer);
}

function GetKey() {
    var url = 'handleChatSession.ashx?r=k';
    if (thisPage === 'news') { url = '../handleChatSession.ashx?r=k' };
    $.ajax({
        type: 'get',
        async: false,
        url: url,
        data: '{}',
        contentType: 'text/plain; charset=utf-8',
        dataType: 'text',
        error: function (e) {
            k = 0;
        },
        success: function (data) {
            if (data) {
                k = data;
            }
        }
    });
}

function StartChatSession() {
    var cPos = $('#chat-link').offset();
    $('#chat-form').css({ top: cPos.top - 175, left: cPos.left - 350 });
    $('#chat-form').show();
    var url = 'handleChatSession.ashx?r=s&k=';
    if (thisPage === 'news') { url = '../handleChatSession.ashx?r=s&k=' };
    var chatRetry = setTimeout(function () {
        if (chatResponse == false && chatAttempts < 3) { StartChatSession(); } else { if (chatAttempts === 3) { $('#sales-online').html('Sorry there is no body around at the moment to handle your request.'); } else { chatAttempts++; clearTimeout(chatRetry); } };
    }, 2000);
    $.ajax({
        type: 'GET',
        async: true,
        url: url + k,
        data: '{}',
        contentType: 'text/plain; charset=utf-8',
        dataType: 'text',
        error: function (e) {
            $('#chat-keys').show();
            alert("Sorry - we're unable to start a chat session at this time.");
            LClick('chat:start-error');
            chatResponse = true;
        },
        success: function (data) {
            chatResponse = true;
            chatAttempts = 0;
            $('#chat-keys').show();
            if (data.length > 2) {
                sales = data;
                $('#sales-online').html('<div class="title"><h4><span  class="blue">' + sales + '</span> is online</h4></div><br/><p>If you would like to chat, please enter your name in the box below.</p><br/>')
                $('#sales-online').append('<input type="text" class="edit-input" onkeyup="return CheckMyName(event);" id="my-name" value=""><br/><br/><input disabled="disabled" class="edit-button" id="my-name-submit" type="button" onclick="SubmitMyName();" value="Lets Talk">');
                LClick('chat:start-success');
            }
            else {
                $('#sales-online').html('<h4>Sorry we are not online at the moment</h4><br/><p>Sorry we missed you. <br/><br/><a href="mailto:contact-us@practice-it.co.uk">Click here if you would like to drop us an email instead</a>.</p>')
                LClick('chat:start-no-one-home');
            }
        }
    });
}
function CheckMyName(e) {
    var characterCode = e.keyCode;
    var myName = $('#my-name').val();
    if (myName.length > 1) {
        if (characterCode == 13) {
            SubmitMyName();
        } else {
            $('#my-name-submit').attr('disabled', false);
        }
    }
    else {
        $('#my-name-submit').attr('disabled', true);
    }
}

function SubmitMyName() {
    var url = 'handleChatSession.ashx?r=n&n=';
    if (thisPage === 'news') { url = '../handleChatSession.ashx?r=n&n=' };
    $.ajax({
        type: 'get',
        async: true,
        url: url + $('#my-name').val() + '&k=' + k,
        data: '{}',
        contentType: 'text/plain; charset=utf-8',
        dataType: 'text',
        error: function (e) {
            alert("Please enter your name in the box shown.");
        },
        success: function (data) {
            if (data) {
                if (data.split('~')[0] == 'OK') {
                    $('#chat-keys').hide();
                    $('#chat-panel').show();
                    $('#chat-my-session').html('<span class="blue">' + data.split('~')[1] + ' </span> you are talking to <span class="blue">' + sales + '</span>');
                    me = data.split('~')[1];
                    GetMessages();
                }
            }
        }
    });
}

function SendMessage(e) {
    var characterCode = null;
    if (e != null) {
        characterCode = e.keyCode;
    }
    else {
        characterCode = 13;
    }
    if (characterCode == 13) {
        var thisMsg = $('#chat-message').val();
        if (thisMsg.length == 0) {
            alert('Please enter a message');
        } else {
            $('#chat-message').val('');
            var msg = new ChatMessage(thisMsg);
            var str = JSON.stringify(msg);
            var url = 'handleChatMessage.ashx?r=s&m=';
            if (thisPage === 'news') { url = '../handleChatMessage.ashx?r=s&m=' };
            $.ajax({
                type: 'POST',
                async: true,
                url: url + str,
                data: '{}',
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                error: function (e) {
                },
                success: function () {
                    GetMessages();
                }
            });
            return false;
        }
    } else {
        return true;
    }
}

function GetMessages() {
    var chatWindow = document.getElementById('chat-messages');
    var url = 'handleChatMessage.ashx?r=g&k=';
    if (thisPage === 'news') { url = '../handleChatMessage.ashx?r=g&k=' };
    $.ajax({
        type: 'get',
        async: true,
        url: url + k + '&mId=' + lastMsgId,
        data: '{}',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        error: function (e) {
        },
        success: function (data) {
            if (data) {
                gettingMessages = false;
                $.each(data, function (i, result) {
                    var msg = '';
                    if (data[i].MyId == me) {
                        msg = '<p class="msg"><span class="chat-from-me">[' + data[i].MyId + ']</span><br/>' + data[i].Msg + '</p>';
                    }
                    else {
                        msg = '<p class="msg"><span class="chat-from">[' + data[i].MyId + ']</span><br/>' + data[i].Msg + '</p>';
                    }
                    lastMsgId = data[i].MsgId;
                    $('#chat-messages').append(msg);
                    chatWindow.scrollTop = chatWindow.scrollHeight;
                });
            }
            chatTimer = setTimeout(function () { GetMessages(); }, 3000);
        }
    });
}

function SendEmailTranscript() {
    var emailAddress = $('#chat-my-email-address').val();
    var pattern = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
    if (pattern.test(emailAddress)) {
        $('#button-send-transcript').attr('disabled', true);
        var url = 'handleChatSession.ashx?r=email&address=';
        if (thisPage === 'news') { url = '../handleChatSession.ashx?r=email&address=' };
        $.ajax({
            type: 'post',
            async: false,
            url: url + emailAddress + '&k=' + k,
            data: '{}',
            contentType: 'text/plain; charset=utf-8',
            dataType: 'text',
            error: function (e) {
                alert("Sorry something went wrong when we tried to email your transcript, please check your email address.");
                $('#button-send-transcript').attr('disabled', false);
            },
            success: function (data) {
                if (data == "OK") {
                    if (confirm('Your transcript has been emailed')) {
                        CloseChatPanel();
                        $('#button-send-transcript').attr('disabled', true);
                    } else {

                    }
                } else {
                    alert("Sorry something went wrong when we tried to email your transcript, please check your email address.");
                    $('#button-send-transcript').attr('disabled', false);
                }
            }
        });
    } else {
        alert("Sorry your email address doesn't seem to be formatted correctly, please check");
    }
}

function EmailChat(obj) {
    $('#chat-my-email-address').click(function () {
        if ($(this).val() == 'please enter your email address') {
            $(this).val('');
        }
    });
    $(obj).next('div').slideDown();
    $('#button-send-transcript').attr('disabled', false);
    $('#chat-transcript-no').hide();
}
