/**
 *  Copyright 2018 Avaya Inc. All Rights Reserved.
 *
 * Usage of this source is bound to the terms described in
 * licences/License.txt
 *
 * Avaya - Confidential & Proprietary. Use pursuant to your signed agreement or
 * Avaya Policy
 *
 * Handles the UI side of the web chat library, which is based around jQuery UI. Replace the following with your own UI code, if you prefer.
 */

var chatUI = {

    /**
     * Hide the chat panel.
     */
    hideChatPanel : function() {
        'use strict';
        $('#liveChatLink').hide();
    },

    /**
     * Show the chat panel.
     */
    showChatPanel : function() {
        'use strict';
        $('#liveChatLink').show();
    },

    /**
     * Change the textContent of the specified element.
     * @param el
     * @param newText
     */
    changeElementText : function(el, newText) {
        'use strict';
        $(el).text(newText);
    },

    /**
     * Add the EWT to the chat tab. Included as an alternative to using an alert window.
     */
    addEwtToChatTab : function(waitTime) {
        'use strict';
        $('#liveChatLink').attr('title',
                'Click to chat with an agent! Wait time is approximately ' + waitTime + ' minutes');
    },

    /**
     * Changes the chat panel to chat mode.
     */
    changeToChatMode : function() {
        'use strict';
        $('#chatForm').hide();
        $('#chatInterface').show();
        $('#chatPanel').dialog({
            width : 400,
            'resize' : 'auto',
            dialogClass : 'fixedPosition'
        });
        
        $('#chatPanel').dialog('widget').attr('id', 'chatPanelHidden');
    },

    /**
     * Changes the chat panel to login mode.
     */
    changeToLoginMode : function() {
        'use strict';
        $('#chatInterface').hide();
        $('#chatForm').show();
        $('#chatPanel').dialog({
            width : 400,
            'resize' : 'auto',
            dialogClass : 'fixedPosition'
        });
    },

    resetChatUI : function() {
        'use strict';
        chatUI.changeToLoginMode();
        $('#chatPanel').dialog('close');
        $('#liveChatLink').show();
        $("#outmessage").val("");
        $("#messages").empty();
    },

    resizeConfigPanel : function() {
        'use strict';
        $('#configPanel').dialog({
            width : 400,
            height : 350
        });
    },

    /**
     * Create and show an alert
     * @param {string} msg
     */
    showAlert : function(msg) {
        'use strict';
        $('#alertDialog').dialog({
            draggable : false,
            resizeable : false,
            buttons : {
                OK : function() {
                    $(this).dialog('close');
                }
            }
        }).text(msg);
    },
    
    showLoginErrors: function(msg) {
        "use strict";
        $('#loginErrorsDiv').show("fold");
        $('#loginErrorsDiv').text(msg);
        setTimeout(function(){
            $('#loginErrorsDiv').hide("fold");
        }, 2000);
    },
    
    markElAsRequired: function(id, isRequired){
        "use strict";
        
        var text = $(id).text();
        var newText;
        console.log(text);
        
        if (isRequired) {
            newText = text + " (required)";
        } else {
            newText = text.replace(" (required)", "");
        }
        
        $(id).text(newText);
    },

    /**
     * Shake the chat tab slightly to draw attention to it.
     */
    shakeChatTab : function() {
        'use strict';
        var shakes = 0, maxShakes = 6;
        var dir = 1;
        window.tabShakeInterval = setInterval(function() {
            shakes++;
            $('#liveChatLink').css('right', dir * 4);
            dir *= -1;

            if (shakes >= maxShakes) {
                clearTimeout(window.tabShakeInterval);
            }
        }, 1000);
    },
    
    closePanel : function(event) {
        'use strict';
        event.preventDefault();
        console.debug("WebChat: closing chat panel");

        // when the chat dialog is closed, reset things
        $('#liveChatLink').show();
        chatSocket.clearRefresh();
        chatSocket.manualClose = true;
        clearTimeout(chatSocket.closeTimer);
        if (webSocket.readyState !== WebSocket.CLOSING) {
            chatConfig.dontRetryConnection = true;
            webChat.quitChat();
        }
    },

    /**
     * Sets up the UI code.
     */
    setup : function() {
        'use strict';

        // set up the link for liveChat - this is what the user clicks to open the chat
        // The jQuery .one() method means that the chat will only close once when the panel is closed,
        // rather than repeatedly trying to close it due to the event firing multiple times
        $('#liveChatLink').click(function(event) {
            event.preventDefault();
            $('#liveChatLink').hide();
            $('#chatPanel').dialog({
                width : 400,
                height : 'auto',
                dialogClass : 'fixedPosition',
            }).one('dialogclose', function(event) {
                if (webSocket !== undefined ) {
                    chatUI.closePanel(event);
                } else {
                    chatUI.showChatPanel();
                }
            });
        });

        // gives the liveChatLink a fancier tooltip
        $('#liveChatLink').tooltip();

        $('#configLink').click(function(event) {
            $('#configPanel').dialog({
                width : 400,
                height : 350,
                'resize' : 'auto',
                dialogClass : 'fixedPosition'
            });
            event.preventDefault();
        });

        $('#showCoBrowseLink').click(function(event) {
            if (!coBrowseUI.checkDialogOpen(coBrowseUI.proactiveJoinDialogId)) {
                coBrowseUI.createProactiveJoinDialog(true);
            }
            event.preventDefault();
        });

        // Set jQuery UI button
        $('.button').button();

        // hide the alert header and shake the chat tab
        $('#chatJavaScriptAlertHeader').hide();
        chatUI.shakeChatTab();
        
        chatUI.markElAsRequired("#nameLabel", chatConfig.requireFirstName || chatConfig.requireLastName);
        chatUI.markElAsRequired("#emailLabel", chatConfig.requireEmail);
        chatUI.markElAsRequired("#phoneLabel", chatConfig.requirePhone);
        
        $("#outmessage").on("keydown", webChat.onType);
    },
    
    /**
     * Reload the chat panel after a refresh
     */
    reloadChatPanel: function() {
        'use strict';
        console.log("Reloading chat panel");
        chatUI.changeToChatMode();
        
        // I honestly don't know WHY this line is required, but it's the only thing that works.
        $("#liveChatLink").click();
    },
    
    /**
     * Returns the values of the phone inputs, and patterns defined on them for validation.
     * @returns {chatUI.getPhoneDetails.webChatUIAnonym$6}
     */
    getPhoneDetails: function() {
        "use strict";
        return {
            "country" : { 
                "value" : $("#phone-country").val(),
                "pattern" : $("#phone-country").prop("pattern") 
            },
            "area" : { 
                "value" : $("#phone-area").val(),
                "pattern" : $("#phone-area").prop("pattern") 
            },
            "phone" : { 
                "value" : $("#phone-chat").val(),
                "pattern" : $("#phone-chat").prop("pattern") 
            }
        };
    },
    
    /**
     * Gather customer details from the page. Phone details are added separately so they can be validated.
     * @returns {Object} a JSON object containing entries from the page
     */
    getCustomerDetails: function() {
        "use strict";
        return {
            "firstName" : $("#user-chat").val(),
            "lastName" : $("#user-chat-last").val(),
            "email" : $("#email-chat").val()
        };
    },
    
    getChatMessage: function(){
        "use strict";
        return $("#outmessage").val();
    },
    
    /**
     * Disable the chatbox and sendbutton.
     * @param {Boolean} isDisabled - if true, disable the controls.
     */
    disableControls: function(isDisabled) {
        "use strict";
        $("#outmessage").attr("disabled", isDisabled);
        $("#sendbutton-chat").attr("disabled", isDisabled);
    },
    
    /**
     * Append a paragraph or other element to the chat transcript.
     * Includes an autoscroll mechanism
     * @param {HTMLElement} para
     */
    appendParagraph: function(para) {
        "use strict";
        $("#messages").append(para);
        $("#messages").scrollTop($("#messages").prop("scrollHeight"));
    },
    
    /**
     * Clears the chatbox.
     */
    clearMessageInput: function() {
        "use strict";
        $("#outmessage").val("");
    },
    
    getCustomFields: function() {
        "use strict";
        return {
            "title" : $("#customFieldTitle").val(),
            "value" : $("#customFieldValue").val()
        };
    },
    
    /**
     * Get the value of the topic field.
     * @return {String}
     */
    getTopic: function() {
        "use strict";
        return $("#topic").val().replace(/[ #?@$\s]/g, "");
    },
    
    /**
     * Check if the value of the topic input is valid.
     * @return {Boolean}
     */
    isTopicValid: function() {
        "use strict";
        return $("#topic").prop("validity").valid;
    },
    
    getRequestTranscript: function() {
        "use strict";
        return $("#transcript-chat").prop("checked");
    },
    
    /**
     * Toggles whether or not the email is considered valid by the browser.
     * If not, disable and uncheck the "request transcript" checkbox.
     * @param {Boolean} isValid
     */
    setEmailInputValid: function(isValid) {
        "use strict";
        if (!isValid) {
            $("#transcript-chat").prop("disabled", true);
            $("#transcript-chat").prop("checked", false);
        } else {
            $("#transcript-chat").prop("disabled", false);
        }
    },
    
    clearUsers: function() {
        "use strict";
        $("#participants > div").children("img").attr("src", "");
        $("#participants > div").children("img").attr("class", "hidden");
        var images = $("#participants > .hidden").children("img").toArray();
        for (var i = 0; i < images.length; i++) {
            images[i].nextSibling.textContent = "";
        }
    },
    
    updateUserImage: function(index, imageSrc, className, displayName) {
        "use strict";
        var image = $("#participants > div > img")[index];
        image.src = imageSrc;
        image.className = className;
        image.nextSibling.textContent = displayName;
    },
    
    /**
     * Flip the page direction to support RTL languages.
     */
    flipPageDirection: function() {
        "use strict";
        var dir = document.dir;
        if (dir.toUpperCase() === 'RTL') {
            document.dir = "ltr";
        } else {
            document.dir = "rtl";
        }
        chatUI.updatePageDirection();
    },
    
    /**
     * Update certain text alignments to match the page direction.
     */
    updatePageDirection: function() {
        "use strict";
        var dir = document.dir;
        if (dir.toUpperCase() === 'LTR') {
            console.log("Left-to-right. So, agent messages should be on the right-hand-side and customer on the left");
            // set the text-align fields accordingly (agent on right, customer on left)
            // you may also wish to set the chatbot as well, if you use a different style for that
            $(".agentDate").css({"text-align": "left"});
            $(".response").css({"text-align": "left"});
            $(".sent").css({"text-align": "right"});
            $(".date").css({"text-align": "right"});
        } else {
            console.log("right-to-left. So, agent messages should be on the right-hand-side and customer on the left");
            // flip the relevant fields from right to left, otherwise the agentDate will be off the screen.
            $(".agentDate").css({"text-align": "right"});
            $(".response").css({"text-align": "right"});
            $(".sent").css({"text-align": "left"});
            $(".date").css({"text-align": "left"});
        }
    }
  
};
