﻿/// <reference path="jquery-1.5.1.min.js" />
/// <reference path="jconnect.js" />
/// <reference path="jquery-ui.js" />
/// <reference path="jquery.cookie.js" />
/// <reference path="jquery.json-2.2.min.js" />
/// <reference path="jquery.scrollTo-1.4.2-min.js" />
/// <reference path="jquery.window.js" />
/// <reference path="jquery.flXHRproxy.js" />
/// <reference path="flXHR.js" />
/// <reference path="strophe.flxhr.min.js" />

var BOSH_SERVICE = 'http://public.im.myetrack.com/http-bind/';
var stylepath = 'http://api.myetrack.com/css/';
var scriptpath = 'http://api.myetrack.com/scripts/';
var connected = null;
var connection = null;
var connectedTo = null;
var chatwin = null;
var cb = null;
var isAuthorized = false;
var chatstate = null;
var chatapi = null;
var pint = null;
var userid = null;

(function ($) {
    $.fn.ESTChatSend = function (message) {
        chatapi.Methods.DoSendChatMessage(message);
    };

    $.fn.ESTJSAPI = function (options) {
        var settings = {
            ConnectToken: '',
            OnMessageReceived: function (message, from) {
                // This is the default action when a chat message has been received.
                // It can be overridden by the client by supplying a method to handle the event.
                methods.DoAddChatMessage(from, message);
            },
            OnMessageHistoryReceived: function (chattingwith, messagehistory) {
                var obj = jQuery.parseJSON(messagehistory);
                var cbt = '';
                var cbo = $(cb);
                for (var i = 0; i < obj.length; i++) {
                    var objt = jQuery.parseJSON(obj[i]);
                    $(cbo).find('.chatconvo').append('<div><b>' + (connection.jid.split('@')[0] == objt.From.split('@')[0] ? 'Me' : objt.From.split('@')[0]) + '</b>: ' + objt.Message + '</div>');
                }
                cbt = $('<div />').append($(cbo).clone()).html();
                if (obj.length > 0) {
                    var t = '';
                    if (chattingwith != '')
                        t = 'Chat with ' + chattingwith;
                    else
                        t = 'Chat with a representative';
                    chatwin = methods.DoLoadChatWindow(cbt, t);
                    $(chatwin).dialog('open');
                }
            },
            ChatContainer: '',
            ChatTextBox: '',
            ChatSendButton: '',
            Theme: 'light',
            AccountId: 0,
            AuthToken: ''
        };

        if (options) {
            $.extend(settings, options);
        }

        var methods = {
            InitChat: function () {
                // First we would authenticate the user here...
                if (typeof jQuery == 'undefined' ||
                //                    typeof jQuery().window == 'undefined' ||
                    typeof jQuery().ui == 'undefined') {
                    if (typeof jQuery == 'undefined') {
                        methods.DoLoadExternalFile(scriptpath + 'jquery-1.5.1.min.js', 'js');
                    }
                    methods.DoLoadExternalFile(stylepath + 'estchat.css', 'css');
                    //                    methods.DoLoadExternalFile(stylepath + 'jquery.window.css', 'css');
                    if (settings.Theme) {
                        if (settings.Theme == 'light' ||
                            settings.Theme == 'dark') {
                            methods.DoLoadTheme(settings.Theme)
                        }
                        else {
                            methods.DoLoadTheme('default');
                        }
                    } else {
                        methods.DoLoadTheme('default');
                    }
                    var int = setInterval(function () {
                        if (typeof jQuery != 'undefined') {
                            window.clearInterval(int);
                            if (typeof jQuery.ui == 'undefined')
                                methods.DoLoadExternalFile(scriptpath + 'jquery-ui.js', 'js');
                            if (typeof jQuery.scrollTo == 'undefined')
                                methods.DoLoadExternalFile(scriptpath + 'jquery.scrollTo-1.4.2-min.js', 'js');
                            //                            if (typeof jQuery.window == 'undefined')
                            //                                methods.DoLoadExternalFile(scriptpath + 'jquery.window.js', 'js');
                            if (typeof jQuery.cookie == 'undefined')
                                methods.DoLoadExternalFile(scriptpath + 'jquery.cookie.js', 'js');
                            if (typeof jQuery.toJSON == 'undefined')
                                methods.DoLoadExternalFile(scriptpath + 'jquery.json-2.2.min.js', 'js');
                            int = setInterval(function () {
                                if (
                                //                                jQuery.window &&
                                jQuery.ui && jQuery.cookie && jQuery.toJSON && jQuery.scrollTo) {
                                    window.clearInterval(int);
                                    methods.DoInit();
                                }
                            }, 500);
                        }
                    }, 100);
                } else {
                    var int = setInterval(function () {
                        if (typeof jQuery != 'undefined') {
                            window.clearInterval(int);
                            methods.DoLoadExternalFile(scriptpath + 'jquery-ui.js', 'js');
                            //                            methods.DoLoadExternalFile(scriptpath + 'jquery.window.js', 'js');
                            methods.DoLoadExternalFile(scriptpath + 'jquery.cookie.js', 'js');
                            methods.DoLoadExternalFile(scriptpath + 'jquery.json-2.2.min.js', 'js');
                            int = setInterval(function () {
                                if (
                                //                                jQuery().window && 
                                jQuery.ui && jQuery.cookie && jQuery.toJSON) {
                                    window.clearInterval(int);
                                    methods.DoInit();
                                }
                            }, 100);
                        }
                    }, 100);
                }
            },
            InitTracker: function () {
                if (typeof jQuery == 'undefined' ||
                //                    typeof jQuery().window == 'undefined' ||
                    typeof jQuery().ui == 'undefined') {
                    if (typeof jQuery == 'undefined') {
                        methods.DoLoadExternalFile(scriptpath + 'jquery-1.5.1.min.js', 'js');
                    }
                    var int = setInterval(function () {
                        if (typeof jQuery != 'undefined') {
                            clearInterval(int);
                            if (typeof jQuery.cookie == 'undefined') {
                                methods.DoLoadExternalFile(methods.DoLoadExternalFile(scriptpath + 'jquery.cookie.js', 'js'));
                                int = setInterval(function () {
                                    if (typeof jQuery.cookie != 'undefined') {
                                        clearInterval(int);
                                        methods.DoLoadExternalFile(scriptpath + 'ePageTracker.js', 'js');
                                        int = setInterval(function () {
                                            if (typeof ePageTracker != 'undefined') {
                                                clearInterval(int);
                                                var sid = methods.DoGetSessionID();
                                                var tid = methods.DoReadQueryString('ctl');
                                                var ttype = methods.DoReadQueryString('ctlt');
                                                var lid = methods.DoReadQueryString('lid');
                                                if (tid == '') {
                                                    tid = methods.DoGetCookie('entrymed');
                                                    if (tid == null)
                                                        tid = '';
                                                } else {
                                                    methods.DoSetCookie('entrymed', tid);
                                                }
                                                if (ttype == '') {
                                                    ttype = methods.DoGetCookie('entrymedt');
                                                    if (ttype == null)
                                                        ttype = '';
                                                } else {
                                                    methods.DoSetCookie('entrymedt', ttype);
                                                }
                                                if (lid == '') {
                                                    lid = methods.DoGetCookie('lid');
                                                    if (lid == null)
                                                        lid = '';
                                                } else {
                                                    methods.DoSetCookie('lid', lid);
                                                }
                                                var sessionId = methods.DoGetSessionID();
                                                ePageTracker(settings.AccountId, sessionId, tid, ttype, lid);
                                                $('form[action*="esalestrack/data/portal"]').prepend('<input type="hidden" id="hidTrackId" name="hidTrackId" value="' + sessionId + '" />');
                                            }
                                        }, 100);
                                    }
                                }, 100);
                            }
                        }
                    }, 100);
                } else {
                    var int = setInterval(function () {
                        if (typeof jQuery != 'undefined') {
                            clearInterval(int);
                            methods.DoLoadExternalFile(scriptpath + 'jquery.cookie.js', 'js');
                            methods.DoLoadExternalFile(scriptpath + 'ePageTracker.js', 'js');
                            int = setInterval(function () {
                                if (typeof ePageTracker != 'undefined' && typeof jQuery.cookie != 'undefined') {
                                    ePageTracker(settings.AccountId);
                                }
                            });
                        }
                    }, 100);
                }
            },
            OnMessage: function (msg) {
                try {
                    var to = msg.getAttribute('to');
                    var from = msg.getAttribute('from');
                    var type = msg.getAttribute('type');
                    var elems = msg.getElementsByTagName('body');

                    if (type == "chat" && elems.length > 0) {
                        var body = elems[0];
                        var message = Strophe.getText(body);
                        from = $.trim(from);
                        from = from.split('@')[0];
                        if (message.indexOf('Control|') == 0) {
                            methods.DoProcessControl(message, from);
                        } else {
                            methods.DoShowMessage(message, from);
                        }
                    } else {
                        //                        console.log('not chat');
                        //                        console.log(msg);
                    }
                }
                catch (e) {

                }


                // we must return true to keep the handler alive.  
                // returning false would remove it after it finishes.
                return true;
            },
            OnConnect: function (status) {
                if (status == Strophe.Status.CONNECTING) {
                    connected = false;
                } else if (status == Strophe.Status.CONNFAIL) {
                    connected = false;
                } else if (status == Strophe.Status.DISCONNECTING) {
                } else if (status == Strophe.Status.DISCONNECTED) {
                    connected = false;
                    methods.DoSetCookie('jid', null);
                    methods.DoSetCookie('sid', null);
                    methods.DoSetCookie('rid', null);
                    methods.InitChat();
                } else if (status == Strophe.Status.CONNECTED) {
                    connected = true;
                    methods.DoSaveConn();
                    methods.DoSendInitMsg();
                    methods.DoGetMessageHistory();
                    connection.flush();
                } else if (status == Strophe.Status.ATTACHED) {
                    connected = true;
                    methods.DoSendInitMsg();
                    methods.DoGetMessageHistory();
                    connection.flush();
                } else if (status == Strophe.Status.ERROR) {
                    connected = false;
                }
            },
            DoInit: function () {
                var sendaction = "$.fn.ESTChatSend($('.estchatbox').find('#chatmessage').val()); $('.estchatbox').find('#chatmessage').val(''); $('.estchatbox').find('#chatmessage').focus(); return false;";
                cb = '<div class="estchatbox">';
                cb += '<table class="chatarea" cellpadding="0" cellspacing="0">';
                cb += '<tr><td class="chatconvoholder">';
                cb += '<div class="chatconvo"></div>';
                cb += '</td></tr>';
                cb += '<tr><td>';
                cb += '<textarea id="chatmessage"></textarea>';
                cb += '<input type="button" id="buttonsend" class="ui-button ui-widget ui-state-default ui-button-text-only" role="button" value="Send" onclick="' + sendaction + '"></input>';
                cb += '</td></tr>';
                cb += '</table>';
                cb += '</div>';

                if (navigator.appName != 'Microsoft Internet Explorer') {
                    methods.DoLoadExternalFile(scriptpath + 'jconnect.js', 'js');
                    methods.DoLoadExternalFile(scriptpath + 'b64.js', 'js');
                    var int = setInterval(function () {
                        if (typeof Strophe != 'undefined' && typeof Base64 != 'undefined') {
                            window.clearInterval(int);
                            methods.DoStartChat();
                        }
                    }, 100);
                } else {
                    methods.DoLoadExternalFile('http://flxhr.flensed.com/code/build/flXHR.js', 'js');
                    var int = setInterval(function () {
                        if (typeof flensed != 'undefined') {
                            window.clearInterval(int);
                            methods.DoLoadExternalFile(scriptpath + 'jconnect.js', 'js');
                            methods.DoLoadExternalFile(scriptpath + 'b64.js', 'js');
                            int = setInterval(function () {
                                if (typeof Strophe != 'undefined' && typeof Base64 != 'undefined' && typeof flensed.flXHR != 'undefined') {
                                    window.clearInterval(int);
                                    methods.DoLoadExternalFile(scriptpath + 'strophe.flxhr.min.js', 'js');
                                    if (navigator.appName == 'Microsoft Internet Explorer') {
                                        int = window.setInterval(function () {
                                            if (typeof Strophe._connectionPlugins.flxhr != 'undefined') {
                                                window.clearInterval(int);
                                                methods.DoStartChat();
                                            }
                                        }, 100);
                                    } else {
                                        methods.DoStartChat();
                                    }
                                }
                            }, 100);
                        }
                    }, 100);
                }
            },
            DoStartChat: function () {
                // Setup the unload to save our RID
                $(window).unload(function () {
                    if (connected) {
                        methods.DoSaveConn();
                    }
                });

                connection = new Strophe.Connection(BOSH_SERVICE);
                connection.addHandler(methods.OnMessage, null, 'message', null, null, null);
                var data = methods.DoGetConn();
                if (data == null) {
                    connection.connect('public.im.myetrack.com', 'test', methods.OnConnect);
                } else {
                    connection.attach(data.jid, data.sid, data.rid, methods.OnConnect);
                    methods.DoSaveConn();
                }
            },
            DoSendInitMsg: function () {
                methods.DoGetUserId();
                methods.DoSendMessage(settings.AccountId.toString(), 'Control|StartSession|' + userid + '|' + window.location.href);
            },
            DoSendChatMessage: function (msg) {
                if (msg == '')
                    return;
                methods.DoSendMessage(settings.AccountId.toString(), 'Control|RFUSER|' + msg);
                methods.DoShowMessage(msg, 'Me');
            },
            DoSendMessage: function (mto, msg) {
                if (connected) {
                    var mfrom = connection.jid.split('@')[0];
                    var message = $msg({ to: mto + '@im.myetrack.com', from: mfrom + '@public.im.myetrack.com', type: 'chat' }).c('body').t(msg);
                    connection.send(message.tree());
                    connection.flush();
                }
            },
            DoGetMessageHistory: function () {
                var mfrom = connection.jid.split('@')[0];
                var message = $msg({ to: settings.AccountId.toString() + '@im.myetrack.com', from: mfrom + '@public.im.myetrack.com', type: 'chat' }).c('body').t('Control|GetMessageHistory|' + userid);
                connection.send(message.tree());
            },
            DoShowMessage: function (msg, name) {
                settings.OnMessageReceived(msg, name);
                return true;
            },
            DoSendMetrics: function () {
                methods.DoSendMessage(settings.AccountId.toString(), 'Control|Location|' + window.location.href);
            },
            DoProcessControl: function (msg, from) {
                var split = msg.split('|');
                var action = split[1];
                switch (action) {
                    case "Redirect":
                        if (window.location.href.toLowerCase() != split[2].toLowerCase()) {
                            window.location = split[2];
                        }
                        break;
                    case "RelayedMessage":
                        //                        console.log(split[2] + ': ' + split[3]);
                        methods.DoShowMessage(split[3], split[2]);
                        break;
                    case "MessageHistory":
                        chatstate = methods.DoGetChatState();
                        if (chatstate.Initiated && !chatstate.UserClosed)
                            settings.OnMessageHistoryReceived(split[2], split[3]);
                        break;
                    case "PollRequest":
                        methods.DoSendPollResponse();
                        break;
                }
            },
            DoSendPollResponse: function () {
                methods.DoSendMessage(settings.AccountId.toString(), 'Control|PollResponse|Anon');
            },
            DoLoadTheme: function (theme) {
                methods.DoLoadExternalFile(stylepath + 'Themes/' + theme + '/theme.css', 'css');
            },
            //            DoLoadChat: function (content, data) {
            //                if (data != null && data != undefined) {
            //                    var win = $.window({
            //                        showModal: false,
            //                        title: "Chat with ???",
            //                        content: content,
            //                        closable: true,
            //                        minimizable: true,
            //                        maximizable: false,
            //                        resizable: false,
            //                        showFooter: false,
            //                        showRoundCorner: true,
            //                        x: data.x,
            //                        y: data.y
            //                    });
            //                }
            //                if (data != null && data != undefined) {
            //                    $('.chatconvo').html(Base64.decode(data.convo));
            //                }
            //                return win;
            //            },
            DoSaveConn: function () {
                if (connection != null) {
                    methods.DoSetCookie('jid', connection.jid);
                    methods.DoSetCookie('sid', connection.sid);
                    methods.DoSetCookie('rid', connection.rid);
                }
            },
            DoGetConn: function () {
                var c = methods.DoGetCookie('jid');
                if (c != null && c != undefined) {
                    var obj = new Object();
                    obj.jid = c;
                    obj.sid = methods.DoGetCookie('sid');
                    obj.rid = parseInt(methods.DoGetCookie('rid'));
                    return obj;
                }
                else {
                    return null;
                }
            },
            DoSaveConv: function () {
                if (chatwin != null) {
                    var encoded = Base64.encode($('.chatconvo').html());
                    methods.DoSetCookie('savedconvo', encoded);
                }
            },
            DoGetConvo: function () {
                if (chatwin != null) {
                    var encoded = methods.DoGetCookie('savedconvo');
                    return Base64.decode(encoded);
                }
            },
            DoSaveChat: function () {
                if (!connected)
                    return;
                var obj = new Object();
                obj.jid = connection.jid;
                obj.sid = connection.sid;
                obj.rid = connection.rid;
                obj.userid = userid;

                if (chatwin == null) {
                    obj.convo = Base64.encode('');
                    obj.minimized = false;
                    obj.chatloaded = false;
                }

                var savedata = jQuery.toJSON(obj);
                methods.DoSetCookie('savedchat', savedata);
                obj = null;
            },
            DoGetChat: function () {
                var obj = null;
                var saveddata = methods.DoGetCookie('savedchat');
                if (saveddata != null) {
                    obj = jQuery.evalJSON(saveddata);
                }
                return obj;
            },
            DoLoadExternalFile: function (ref, type, callback) {
                if (type == 'js') {
                    var fr = document.createElement('script');
                    fr.setAttribute('type', 'text/javascript');
                    fr.setAttribute('src', ref);
                } else if (type == 'css') {
                    var fr = document.createElement('link');
                    fr.setAttribute('rel', 'stylesheet');
                    fr.setAttribute('type', 'text/css');
                    fr.setAttribute('href', ref);
                }
                if (typeof fr != 'undefined') {
                    document.getElementsByTagName('head')[0].appendChild(fr)
                    if (callback) {
                        callback();
                    }
                }
            },
            DoSetCookie: function (name, value) {
                var expdate = new Date();
                expdate.setFullYear(expdate.getFullYear() + 1);
                jQuery.cookie('estchat_' + settings.AccountId.toString() + '_' + name, value, { expires: expdate });
            },
            DoGetCookie: function (name) {
                return jQuery.cookie('estchat_' + settings.AccountId.toString() + '_' + name);
            },
            DoAuthorizeUser: function (accountId, authToken) {
                $.getJSON('http://devportal.myetrack.com/eCustomerPortal/eAPIAuth.ashx?callback=?', { accountId: accountId, authToken: authToken },
                    function (data) {
                        if (data.Authenticated) {
                            if ($('est\\:chat').size() > 0) {
                                //                                console.log('init chat');
                                methods.InitChat();
                            }
                            if ($('est\\:tracker').size() > 0) {
                                var eAuthority = '<input type="hidden" value="http://devportal.myetrack.com/ecustomerportal" class="eAuthority" />';
                                $(eAuthority).insertAfter($('est\\:tracker'));
                                methods.InitTracker();
                            }
                        }
                    });
            },
            DoGetSessionID: function () {
                if (typeof jQuery.cookie == 'undefined') {
                    methods.DoLoadExternalFile(scriptpath + 'jquery.cookie.js', 'js');
                    var intc = window.setInterval(function () {
                        if (typeof jQuery.cookie != 'undefined') {
                            var c = methods.DoGetCookie('TrackingSessionID');
                            if (c == null) {
                                var ts = methods.DoCreateSessionID(4);
                                methods.DoSetCookie('TrackingSessionID', ts);
                                return ts;
                            }
                            return c;
                        }
                    }, 100);
                } else {
                    var c = methods.DoGetCookie('TrackingSessionID');
                    if (c == null) {
                        var ts = methods.DoCreateSessionID(4);
                        methods.DoSetCookie('TrackingSessionID', ts);
                        return ts;
                    }
                    return c;
                }
            },
            DoCreateSessionID: function (sectioncount) {
                var chars = "0123456789ABCDEFGHJKLMNPQRTUVWXYZ";
                var randomstring = '';
                for (var i = 0; i < (sectioncount * 5); i++) {
                    if (i != 0 && i % 5 == 0)
                        randomstring += "-";
                    var rnum = Math.floor(Math.random() * chars.length);
                    randomstring += chars.substring(rnum, rnum + 1);
                }
                return randomstring;
            },
            DoGetUserId: function () {
                userid = methods.DoGetCookie('userid');
                if (userid == null) {
                    var chars = "0123456789ABCDEFGHJKLMNPQRTUVWXYZ";
                    var length = 10;
                    userid = '';
                    for (var i = 0; i < length; i++) {
                        var rnum = Math.floor(Math.random() * chars.length);
                        userid += chars.substring(rnum, rnum + 1);
                    }
                    methods.DoSetCookie('userid', userid);
                }
                return userid;
            },
            DoAddChatMessage: function (from, message) {
                LogToConsole('Add Chat Message');
                var chatstate = methods.DoGetChatState();
                LogToConsole(chatstate);
                LogToConsole(chatwin);
                if (chatwin == null) {
                    methods.DoLoadChatWindow(cb, 'Chat with ' + from);
                }
                LogToConsole(chatwin);

                if (chatstate != null && !chatstate.UserClosed) {
                    $(chatwin).dialog('open');
                } else {
                    if (chatstate == null) {
                        methods.DoSetChatState(true, false);
                        $(chatwin).dialog('open');
                    }
                }

                $('.estchatbox').find('.chatconvo').append('<div><b>' + from + '</b>: ' + message + '</div>');
            },
            DoLoadChatWindow: function (windowhtml, wtitle) {
                try {
                    $('body').append('<div id="estchatwindow" style="display: none;">' + windowhtml + '</div>');
                    chatwin = $('.estchatbox').dialog({
                        autoOpen: false,
                        closeOnEscape: false,
                        closeText: 'X',
                        height: 400,
                        width: 450,
                        resizable: false,
                        title: wtitle,
                        close: function () { methods.DoSetChatState(true, true); }
                    });
                }
                catch (e) {
                    LogToConsole('Error: ');
                    LogToConsole(e);
                }
                return chatwin;
            },
            DoSetUserClosed: function (userclosed) {
                var obj = methods.DoGetChatState();
                methods.DoSetChatState(obj.Initiated, userclosed);
                delete obj;
            },
            DoSetChatState: function (initiated, userclosed) {
                var obj = new Object();
                obj.Initiated = initiated;
                obj.UserClosed = userclosed;

                var savestate = jQuery.toJSON(obj);
                methods.DoSetCookie('chatstate', savestate);
                delete obj;
                delete savestate;
            },
            DoGetChatState: function () {
                var savestate = methods.DoGetCookie('chatstate');
                var obj = jQuery.evalJSON(savestate);
                delete savestate;
                return obj;
            },
            DoAlertMe: function (msg) {
                alert(msg);
            },
            DoReadQueryString: function (key, default_) {
                if (default_ == null) default_ = "";
                key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
                var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
                var qs = regex.exec(window.location.href);
                if (qs == null)
                    return default_;
                else
                    return qs[1];
            }
        };

        //        console.log('Got here');
        methods.DoAuthorizeUser(settings.AccountId, settings.AuthToken);
        chatapi = new Object();
        chatapi.Methods = methods;
        chatapi.Settings = settings;
    };
})(jQuery);


function log(msg) {
    $('#log').append('<div></div>').append(document.createTextNode(msg));
}

function rawInput(data) {
    log('RECV: ' + data);
}

function rawOutput(data) {
    log('SENT: ' + data);
}

function LogToConsole(obj) {
    if (console)
        console.log(obj);
}
