$(function() {

    //DISABLED
    return false;

    livechat.renderWin();
    livechat.addMsg(livechat.sysUser, "Welcome to Live Chat. You are now chatting live with a member of staff. " +
                                    "If you do not wish to talk, hit \"Leave me alone!\" and we will leave you to it.", "sys");
    livechat.poll();

    setTimeout( function() {
        $('#lcToolTip').fadeOut(2000);
    }, 10000);

    $(window).resize(function() { livechat.centerWin(); });
    $(window).scroll(function() { livechat.centerWin(); });

    $('#lcClose').click(function() {
        livechat.hideWin();
    }).hover( function() {
        $('#lcToolTip').fadeIn(500);
    }, function() {
        $('#lcToolTip').fadeOut(500);
    }); 

    $('#lcLeaveMeAlone').click(function() {
        livechat.leaveMeAlone();
    });

    $('#lcSendBtn').click(function() {
        livechat.sendMsg();
    });

    $('#lcOut').focus().keyup(function(e) {
        var key = e.keyCode; 
        if ( key == 13 )
            livechat.sendMsg();
    });

});

var livechat = {
    sysUser: 'abtoyota.net',
    visitorId: null,
    agentId: null,

    poll: function() {
        var url = encodeURIComponent(document.location.href);

        $.ajax({
            timeout: 3000,
            type: "POST",
            url: "/ajax_serv/livechat_poll.php",
            data: "request_url="+url,

            success: function(json_data) {
                var jsd = eval('('+json_data+')');
                var now = new Date;

                $('div.lcTile').each(function() {
                    var categoryId =  parseInt( $(this).attr('id').replace(/lcTile_/, '') );
                    var catOnline = false;
                    var catBg = false;

                    $('#lcTile_'+categoryId).unbind("click");

                    for ( agent in jsd.agents ) {
                        if ( jsd.agents[agent].category_id == categoryId ) {
                            catOnline = true;
                            if ( catBg == false )
                                catBg = jsd.agents[agent].glamshot_url;
                        }
                    }
    
                    if ( catOnline == true ) {
                        $('#lcTileStatus_'+ categoryId).css({ backgroundPosition: '0px 0px' });
                        $('#lcTileThumb_'+ categoryId).css({ backgroundImage: "url('" + catBg + "')" });

                        $('#lcTile_'+categoryId).click(function() {
                            if ( $('#lcConnecting').length > 0 )
                                return;


                            $('body').append("<div id=\"lcConnecting\">" +
                                    "<div id=\"lcCText\">We are connecting you to a <strong>live chat agent</strong>, please wait..</div>" +
                                    "<div id=\"lcCImg\"><img src=\"/layout/images/livechat/lcConnect.gif\" width=\"200\" height=\"9\" alt=\"Connecting...\" /></div>" +
                                    "<div id=\"lcCCancel\"><A href=\"#\"><img src=\"/layout/images/livechat/lcCancel.png\" width=\"66\" height=\"26\" alt=\"Cancel\" /></a></div>" +
                                "</div>");

                            setTimeout( function() {
                                $('#lcCText').text("All of our agents are currently busy, please hold..");
                                setTimeout ( function() {
                                    $('#lcCText').text("Thank you for your continued patience!");
                                    setTimeout ( function() {
                                        $('#lcCText').html("Still trying.. <a href=\"/dealership/contact\"><Strong>Leave a message instead</strong></a>");
                                    }, 20000);
                                }, 25000);
                            }, 15000);

                            $.ajax({
                                timeout: 3000,
                                type: "POST",
                                url: "/ajax_serv/livechat_helpme.php",
                                data: "category=" + categoryId
                            });


                            $('#lcConnecting').css({
                                top: ( Math.floor( ( $(window).height() / 2 ) - ( $('#lcConnecting').height() / 2 ) ) + $(window).scrollTop() ) + 'px',
                                left: Math.floor( ( $(window).width() / 2 ) - ( $('#lcConnecting').width() / 2 ) ) + 'px'
                            });

                            $('#lcConnecting a').click(function() {

                                $.ajax({
                                    timeout: 3000,
                                    type: "POST",
                                    url: "/ajax_serv/livechat_helpme.php",
                                    data: "unhelpme=1"
                                });

                                $('#lcConnecting').remove();
                            });
                            

                        });
                    }
                    else {
                        $('#lcTileStatus_'+ categoryId).css({ backgroundPosition: '0px -19px' });
                        $('#lcTileThumb_'+ categoryId).css({ backgroundImage: "url('/layout/images/livechat/lcLater.png')" });

                        $('#lcTile_'+categoryId).click(function() {
                            if ( confirm('This department is offline - would you like to leave a message?') ) {
                                self.location.href="/dealership/contact";
                            };
                        });
                    }
        
                });

                livechat.visitorId = jsd.visitor.visitor_id;

                if ( livechat.visitorId == null )
                    return false;

                if ( jsd.messages.length > 0 )  {
                    for ( msg in jsd.messages ) {
                        livechat.agentId = jsd.messages[msg].agent_id;
    
                        $('#lcAgentName').text( jsd.messages[msg].agent_name );
                        $('#lcAgentJobTitle').text( jsd.messages[msg].agent_job_title );
                        $('#lcAgentEmail').text( jsd.messages[msg].agent_email );
                        $('#lcAgentPhone').text( jsd.messages[msg].agent_telephone );

                        if ( jsd.messages[msg].glamshot_url != '' ) {
                            $('#lcThumb').css({
                                backgroundImage: "url('" + jsd.messages[msg].glamshot_url + "')"
                            });
                        }
                    


                        livechat.addMsg( jsd.messages[msg].agent_name, jsd.messages[msg].msg );
                    }                    

                    livechat.showWin();
                }

            }
        });

        setTimeout( function() {
            livechat.poll();
        }, 4000);
    },

    renderWin: function() {
        var winBuff = '';

        winBuff += "<div id=\"lcTitleBar\"><div id=\"lcClose\"><!-- --></div></div>" +
                   "<div id=\"lcAgentInfo\">" +
                        "<div id=\"lcThumbShadow\"><div id=\"lcThumb\"></div></div>" +
                        "<div id=\"lcAgentMetaData\">" +
                            "<div id=\"lcAgentName\">--</div>" +
                            "<div id=\"lcAgentJobTitle\">--</div>" +
                            "<div id=\"lcAgentEmail\">--</div>" +
                            "<div id=\"lcAgentPhone\">--</div>" +
                        "</div>" +

                        "<div id=\"lcToolTip\">End chat session</div>" +
                        "<div id=\"lcLeaveMeAlone\"><!-- --></div>" +
                   "</div>" +
                   "<div id=\"lcChat\"><div id=\"lcOutput\"><!-- --></div></div>" +
                   "<div id=\"lcFooter\">" +
                        "<div id=\"lcSendBox\"><input type=\"text\" id=\"lcOut\" maxlength=\"4096\" /></div>" +
                        "<div id=\"lcSendBtn\"><!-- --></div>" +
                   "</div>";


        $('body').append("<div id=\"livechatShadow\"><!-- --></div>");
        $('body').append("<div id=\"livechatWin\">" + winBuff + "</div>");
        this.centerWin();
    },

    centerWin: function() {
        /* Center both divs */
        $('#livechatShadow').css({
            top: ( Math.floor( ( $(window).height() / 2 ) - ( $('#livechatShadow').height() / 2 ) ) + $(window).scrollTop() ) + 'px',
            left: Math.floor( ( $(window).width() / 2 ) - ( $('#livechatShadow').width() / 2 ) ) + 'px'
        });
        $('#livechatWin').css({
            top: ( Math.floor( ( $(window).height() / 2 ) - ( $('#livechatWin').height() / 2 ) ) + $(window).scrollTop() ) + 'px',
            left: Math.floor( ( $(window).width() / 2 ) - ( $('#livechatWin').width() / 2 ) ) + 'px'
        });
    },

    showWin: function() {
        if ( $('#livechatWin').is(':visible') )
            return false;

        $('#lcConnecting').remove();

        $('#livechatShadow').show();
        $('#livechatWin').show();
    },

    hideWin: function() {
        $('#livechatShadow').hide();
        $('#livechatWin').hide();
    },

    leaveMeAlone: function() {
        $.ajax({
            timeout: 3000,
            type: "POST",
            url: "/ajax_serv/livechat_leavemealone.php"
        });

        this.hideWin();
    },

    addMsg: function(from_addr, msg, msgClass) {
        $('#lcOutput').append("<div class=\"lcMsg lcMsg" + msgClass + "\"><strong>" + from_addr + " said: </strong>" + this.clean(msg) + "</div>");

        var lco = $('#lcOutput').get(0);
        lco.scrollTop = lco.scrollHeight;
    },

    sendMsg: function() {
        var msg = $('#lcOut').val();
        $('#lcOut').focus();

        if ( livechat.visitorId == null || livechat.agentId == null ) {
            this.addMsg(livechat.sysUser, 'Connection not available, please try again in a moment', 'error');
            return false;
        }

        $('#lcOut').val('');

        if ( msg == '' )
            return false;

        $.ajax({
            timeout: 3000,
            type: "POST",
            url: "/ajax_serv/livechat_send.php",
            data: "agent_id="+ livechat.agentId + "&msg=" + encodeURIComponent(msg)
        });

        this.addMsg('I', msg, 'out');
    },

    clean: function (str) {
        str = str.replace(/\&/g, '&amp;');
        str = str.replace(/"/g, '&quot;');
        str = str.replace(/'/g, '&#039;');
        str = str.replace(/</g, '&lt;');
        str = str.replace(/>/g, '&gt;');
        return str;
    }


};
