let authenticationCheckRunning = false;
window.addEventListener('DOMContentLoaded', init, false);
let customerNumberCheck;

function init() {
    if (!readSiteData() && window.localStorage.getItem('userAuthenticated')) {
       // console.log('setting userAuthenticated to false');
        window.localStorage.setItem('userAuthenticated', false);
    }
    window.addEventListener('beginCheckAuthentication', checkAuthentication);
}
function initDomNode(){
	//console.log
}


function readSiteData(){
	return window["clientSideData"].CustomerNumber;
}

function getSnapIn(origin){

	let chatServices = [{
		//ShopHQ
		"brand" : "ShopHQ",
		"esAPIName" : "ShopHQ_Chat_Service",
        //"eswLiveAgentDevName": "EmbeddedServiceLiveAgent_Parent04I7h000000GmdmEAC_17aa2033be1", //QA
        "eswLiveAgentDevName": "EmbeddedServiceLiveAgent_Parent04I3r000000CaS2EAK_17b7b502ccf",  //Prod
		"origins": ["https://web-t.vips.vvtv.com", "https://web-q.vips.vvtv.com", "https://web-s.vips.vvtv.com" ,"https://www.shophq.com","https://shophq.com", "https://slalom-de-poc.s3.us-west-2.amazonaws.com"]
		// "qaOrigin": "https://web-q.vips.vvtv.com",
		// "prodOrigin": "https://www.shophq.com"
	},{
		//ShopHQ Health
		"brand" : "ShopHQ Health",
		"esAPIName" : "ShopHQ_Health_Chat_Service",
		//"eswLiveAgentDevName": "EmbeddedServiceLiveAgent_Parent04I110000008OzFEAU_17acea8bc12",  //QA
        "eswLiveAgentDevName": "EmbeddedServiceLiveAgent_Parent04I3r000000CaS3EAK_17b7b5e4a6a",  //Prod
		"origins": ["https://shophqhealthweb-s.vips.vvtv.com", "https://www.shophqhealth.com", "https://shophqhealth.com"]
		// "qaOrigin": "https://shophqhealthweb-s.vips.vvtv.com",
		// "prodOrigin": "https://www.shophqhealth.com"
	},{
		//Bulldog
		"brand" : "Bulldog Shopping Network",
		"esAPIName" : "Bulldog_Chat_Service",
		//"eswLiveAgentDevName": "EmbeddedServiceLiveAgent_Parent04I110000008OzKEAU_17acefc8c6d",  //QA
        "eswLiveAgentDevName": "EmbeddedServiceLiveAgent_Parent04I3r000000CaS0EAK_17b7b5d0890", //Prod
		"origins": ["https://bulldogweb-s.vips.vvtv.com", "https://www.bulldogshoppingnetwork.com", "https://bulldogshoppingnetwork.com"],
		// "stagingOrigin": "https://bulldogweb-s.vips.vvtv.com",
		// "prodOrigin": "https://www.bulldogshoppingnetwork.com"
	},{
		//C&B
		"brand" : "Christopher and Banks",
		"esAPIName" : "Christopher_and_Banks_Chat_Service",
		//"eswLiveAgentDevName": "EmbeddedServiceLiveAgent_Parent04I110000008OzPEAU_17acefdc80c", //QA
        "eswLiveAgentDevName": "EmbeddedServiceLiveAgent_Parent04I3r000000CaS1EAK_17b7b5f7940", //Prod
		"origins": ["", "", ""],
		// "qaOrigin": "",
		// "prodOrigin": ""
	}];

	// let chatService = chatServices.filter(service => {
	// 	if(service.origins.includes(origin)){
	// 		return service
	// 	}
	// })
	let chatServiceMapped = [];
	for(var i = 0, n = chatServices.length; i < n; i ++) {
		if(chatServices[i].origins.includes(origin)){
			//console.log('Use this service: ' + JSON.stringify(chatServices[i]));
			chatServiceMapped.push(chatServices[i]);
			return chatServiceMapped;
		}
	}

	return chatService;
}

function setButtonStyles(){
	
	//Set button init display styles
	let chatService = this.getSnapIn(window.location.origin);
    let chatButton = document.getElementsByClassName('uiButton')[0];
	//console.log('Chat Button: ' + chatButton);
    if (chatService[0].brand === "ShopHQ") {
        chatButton.style.backgroundColor = "#6c6256";
	} 
    else if (chatService[0].brand === "Bulldog Shopping Network"){
        chatButton.style.backgroundColor = "#00647D";
    }
    else if (chatService[0].brand === "ShopHQ Health"){
        chatButton.style.backgroundColor = "#6a8987";
	}
    else if (chatService[0].brand === "Christopher and Banks"){
        chatButton.style.backgroundColor = "#E7C4B9";
    }
}

document.addEventListener("DOMNodeInserted", function (event) {
    if (event.target && event.target.className) {
        if(event.target.className === 'embeddedServiceHelpButton'){
            //console.log('Chat button created');
            setButtonStyles();
        }
    }
}, false);

/*
function setAvatars(){
	//Set avatars init display styles
	let chatService = this.getSnapIn(window.location.origin)
    let avatar = document.createElement('img');
    if (chatService[0].brand === "ShopHQ") {
        avatar.src = "https://www.shophq.com/images/store1/logos/Avatars/Chatbot_Eve_40x40.jpg";
    } 
    else if (chatService[0].brand === "Bulldog Shopping Network"){
        avatar.src = "https://www.shophq.com/images/store1/logos/Avatars/Chatbot_Beau_40x40.jpg";
    }
    else if (chatService[0].brand === "ShopHQ Health"){
        avatar.src = "https://www.shophq.com/images/store1/logos/Avatars/Chatbot_Val_40x40.jpg";
    }
    else if (chatService[0].brand === "Christopher and Banks"){
        avatar.src = "https://www.shophq.com/images/store1/logos/Avatars/Chatbot_Chrissy_40x40.jpg";
    }

	return avatar;
}
*/

function setAvatars(){
    //Set avatars init display styles
    let chatService = this.getSnapIn(window.location.origin)
    let avatar = document.createElement('img');
    let agentAvatar = document.createElement('img');
    let avatarArray = [];
    if (chatService[0].brand === "ShopHQ") {
        avatar.src = "https://www.shophq.com/images/store1/logos/Avatars/Chatbot_Eve_40x40.jpg";
        avatarArray.push(avatar);
        agentAvatar.src = "https://www.shophq.com/images/global/brand-default.png";
        avatarArray.push(agentAvatar);
    } 
    else if (chatService[0].brand === "Bulldog Shopping Network"){
        avatar.src = "https://www.shophq.com/images/store1/logos/Avatars/Chatbot_Beau_40x40.jpg";
        avatarArray.push(avatar);
        agentAvatar.src = "https://www.shophq.com/images/store1/logos/HP1Badges/HP1_topdog.png";
        avatarArray.push(agentAvatar);
    }
    else if (chatService[0].brand === "ShopHQ Health"){
        avatar.src = "https://www.shophq.com/images/store1/logos/Avatars/Chatbot_Val_40x40.jpg";
        avatarArray.push(avatar);
        agentAvatar.src = "https://www.shophqhealth.com/images/store1/logos/health-logo-default.png";
        avatarArray.push(agentAvatar);
    }
    else if (chatService[0].brand === "Christopher and Banks"){
        avatar.src = "https://www.shophq.com/images/store1/logos/Avatars/Chatbot_Chrissy_40x40.jpg";
        avatarArray.push(avatar);
        agentAvatar.src = "https://www.shophq.com/images/store1/logos/Avatars/Chatbot_Chrissy_40x40.jpg";
        avatarArray.push(agentAvatar);
    }
    return avatarArray;
}


function checkAuthentication() {
    if (!authenticationCheckRunning) {
        //console.log('checking authentication');
        customerNumberCheck = setInterval(checkCustomerNumberExists, 1000);
        authenticationCheckRunning = true;
    }
}

function checkCustomerNumberExists() {
    let chatKey = window.sessionStorage.getItem('chatKey');
    let customerNumber = readSiteData();
    //console.log('customerNumber: ' + customerNumber);
    userAuthenticated = window.localStorage.getItem('userAuthenticated');
    if (customerNumber && (userAuthenticated === 'false' || !userAuthenticated) && chatKey) {
        //console.log('sending auth message');
        sendAuthMessage(customerNumber, 'authenticated', 'login', chatKey);
    } else if (!customerNumber && userAuthenticated === 'false') {
        //console.log('logging out');
        sendAuthMessage(null, 'unauthenticated', 'logout', chatKey);
    }
}

function setOnclickEvents() {
    //console.log('setting events');
    // setTimeout(() => {
    //     let endChatButton = document.querySelector('div.endChatContainer button.endChatButton');
    //     let closeButton = document.querySelector('embeddedservice-chat-header') ? 
    //         document.querySelector('embeddedservice-chat-header').shadowRoot.querySelector('button.closeButton') : null;
    //     let leaveButton = document.querySelector('button.embeddedServiceSidebarButton');
    //     if (endChatButton) {
    //         endChatButton.onclick = function() { endChat() };
    //     }
    //     if (closeButton) {
    //         closeButton.onclick = function() { endChat() };
    //     }
    //     if (leaveButton) {
    //         leaveButton.onclick = function() { endChat() };
    //     }
    // }, 500);
	setTimeout(function() {
        let endChatButton = document.querySelector('div.endChatContainer button.endChatButton');
        let closeButton = document.querySelector('embeddedservice-chat-header') ? 
            document.querySelector('embeddedservice-chat-header').shadowRoot.querySelector('button.closeButton') : null;
        let leaveButton = document.querySelector('button.embeddedServiceSidebarButton');
        if (endChatButton) {
            endChatButton.onclick = function() { endChat() };
        }
        if (closeButton) {
            closeButton.onclick = function() { endChat() };
        }
        if (leaveButton) {
            leaveButton.onclick = function() { endChat() };
        }
	}, 500);
}

function endChat() {
    //console.log('ending chat');
    sessionStorage.clear();
    clearInterval(customerNumberCheck);
    authenticationCheckRunning = false;
    window.localStorage.removeItem('userAuthenticated');
    //console.log('finished ending chat');
}

function sendAuthMessage(altCustId, authStatus, action, chatKey) {
    let message = {
        '[SIGNIN-STATUS]': {
            'AltCustId': altCustId,
            'ActionType': action,
            'AuthStatus': authStatus,
            'ActionId': Date.now()
        },
        'ChatKey': chatKey
    }
    window.localStorage.setItem('userAuthenticated', authStatus === 'authenticated' ? true : false);
    if (authStatus === 'unauthenticated') window.localStorage.removeItem('userAuthenticated');
    //embedded_svc.postMessage('chasitor.sendMessage', JSON.stringify(message));
}

var initESW = function(gslbBaseURL) {
	let org = '';
	let chatService = this.getSnapIn(window.location.origin);
	// let chatButton = this.setButtonStyles();
	// console.log('Chat Button Color: '+ chatButton.style.color);
	// console.log('ChatService: ' + JSON.stringify(chatService));
	let customerNumber = this.readSiteData();
	let avatar = this.setAvatars();
	//console.log('Avatar: ' + avatar.src)
	embedded_svc.settings.chatbotAvatarImgURL = avatar[0].src;
    embedded_svc.settings.avatarImgURL = avatar[1].src;

	//console.log(avatar[0]);
	embedded_svc.settings.displayHelpButton = true; //Or false
	embedded_svc.settings.language = ''; //For example, enter 'en' or 'en-US'
    embedded_svc.settings.defaultMinimizedText = (window["clientSideData"].PageType == "CHECKOUT" || window["clientSideData"].PageType == "SHOPPING CART VIEW") ? 'Need Help?' : 'Chat with us'; //(Defaults to Chat with an Expert)

	//embedded_svc.settings.defaultMinimizedText = 'Chat with us'; //(Defaults to Chat with an Expert)
	//embedded_svc.settings.disabledMinimizedText = '...'; //(Defaults to Agent Offline)

	//embedded_svc.settings.loadingText = ''; //(Defaults to Loading)
	//embedded_svc.settings.storageDomain = 'yourdomain.com'; //(Sets the domain for your deployment so that visitors can navigate subdomains during a chat session)

	// Settings for Chat
	//embedded_svc.settings.directToButtonRouting = function(prechatFormData) {
		// Dynamically changes the button ID based on what the visitor enters in the pre-chat form.
		// Returns a valid button ID.
	//};
	//embedded_svc.settings.prepopulatedPrechatFields = {}; //Sets the auto-population of pre-chat form fields
	//embedded_svc.settings.fallbackRouting = []; //An array of button IDs, user IDs, or userId_buttonId
	//embedded_svc.settings.offlineSupportMinimizedText = '...'; //(Defaults to Contact Us)
    let userId = (window["clientSideData"] != null && window["clientSideData"].hasOwnProperty('UserId')) ? window["clientSideData"].UserId : "Guest";
    var cartAbandoned =  (window["clientSideData"].PageType == "CHECKOUT" || window["clientSideData"].PageType == "SHOPPING CART VIEW") ? true : false;
    const offerCodes = [];
    if (window["clientSideData"].PageType == "SHOPPING CART VIEW" || window["clientSideData"].PageType == "CHECKOUT"){
        let cartProducts = window["clientSideData"].Products;  
        cartProducts.forEach(grabProductValues);
        function grabProductValues(item){
            var offerCode = String(item.OfferCode + ' - ' + item.ProductName);
            console.log('offerCode = ' + offerCode);
            offerCodes.push(offerCode);
        }
        var offerCodesString = offerCodes.toString();
         }
         var cartTotal;
    
         if(window["clientSideData"].PageType == "CHECKOUT" || window["clientSideData"].PageType == "SHOPPING CART VIEW"){
             if(chatService[0].brand == "ShopHQ"){
                 console.log('brand = shopHQ');
                 if(window["clientSideData"].CartCount > 0){
                 cartTotal = document.querySelector(".price-text").innerHTML;
                 console.log('cart total = ' + cartTotal);
                 }
             }
             else if(chatService[0].brand == "Bulldog Shopping Network"){
                 console.log('brand = bulldog');
                 if(window["clientSideData"].CartCount > 0){
                 cartTotal = document.getElementById('cart-summary-total').innerHTML;
                 console.log('cart total = ' + cartTotal);
                 }
             }
             else if(chatService[0].brand == "ShopHQ Health"){
                 console.log('brand = health');
                 if(window["clientSideData"].CartCount > 0){
                 cartTotal = document.getElementById('cart-summary-total').innerHTML;
                 console.log('cart total = ' + cartTotal);
                 }
             }
         }
     
    window.onload = function() {
        console.log('onloadFunction initiated');
        if (window["clientSideData"].PageType == "CHECKOUT" || window["clientSideData"].PageType == "SHOPPING CART VIEW"){
            cartAbandoned = true;
         console.log('CHECKOUT pagetype boolean has evaluated to true');
            startCartAbandonmentTimer();
            }
    };
    function startCartAbandonmentTimer() {
        setTimeout(function(){ 
            /*chain together getElementsByClassName methods from outside div elements to narrow scope */
             button = document.getElementsByClassName("uiButton"); 
            console.log('button = ' + button[0]);
            button[0].classList.add('blinking');
            message = document.getElementsByClassName("message");
            message[0].innerHTML = 'Need Help?';
            cartAbandoned = true;
            embedded_svc.settings.extraPrechatFormDetails = [{  
                "value": cartAbandoned,
                "transcriptFields":[ "Cart_Abandoned__c" ]
            },{  
                "value": cartTotal,
                "transcriptFields":[ "Cart_Total__c" ]
            },{  
                "value": window.location.origin,
                "transcriptFields":[ "Origination__c" ]
            },{  
                "value": chatService[0].brand,
                "transcriptFields":[ "Brand__c" ]
            },{  
                "value": offerCodesString,
                "transcriptFields":[ "Cart_Offer_Codes__c" ]
            },{
                "label":"First Name",
                 "name":"FirstName",
                "value": userId !==null ? userId : "Guest" ,
                "displayToAgent":true
              }];
            setTimeout(function(){button[0].classList.remove('blinking');  }, 30 * 1000);
        }, 180 * 1000);
      }

      embedded_svc.settings.extraPrechatFormDetails = [{  
        "value": cartAbandoned,
        "transcriptFields":[ "Cart_Abandoned__c" ]
    },{  
        "value": cartTotal,
        "transcriptFields":[ "Cart_Total__c" ]
    },{  
		"value": customerNumber,
		"transcriptFields":[ "Customer_Number__c" ]
	},{  
		"value": window.location.origin,
		"transcriptFields":[ "Origination__c" ]
	},{  
		"value": chatService[0].brand,
		"transcriptFields":[ "Brand__c" ]
	},{  
		"value": offerCodesString,
		"transcriptFields":[ "Cart_Offer_Codes__c" ]
	},{
        "label":"First Name",
         "name":"FirstName",
        "value": userId !==null ? userId : "Guest" ,
        "displayToAgent":true
      }];

    embedded_svc.addEventHandler('afterMaximize', function(e) {
        let closeButton = document.querySelector('embeddedservice-chat-header').shadowRoot.querySelector('button.closeButton');
        closeButton.onclick = function() { setOnclickEvents() };
    });
    embedded_svc.addEventHandler('afterDestroy', stopBlinking)
    function stopBlinking(){
        document.querySelector("button.uiButton").classList.remove('blinking');
        console.log('blinking class gone');
    }

    embedded_svc.addEventHandler('onChatEndedByChasitor', setOnclickEvents);
    embedded_svc.addEventHandler('onChatEndedByAgent', setOnclickEvents);
    embedded_svc.addEventHandler('onIdleTimeoutOccurred', setOnclickEvents);
	embedded_svc.settings.enabledFeatures = ['LiveAgent'];
	embedded_svc.settings.entryFeature = 'LiveAgent';
    embedded_svc.addEventHandler('onChatRequestSuccess', function(e) {
        //console.log('chatKey: ' + e.liveAgentSessionKey);
        if (readSiteData()) window.localStorage.setItem('userAuthenticated', true);
        window.sessionStorage.setItem('chatKey', e.liveAgentSessionKey);
        let closeButton = document.querySelector('embeddedservice-chat-header').shadowRoot.querySelector('button.closeButton');
        closeButton.onclick = function() { setOnclickEvents() };
    });
    embedded_svc.addEventHandler('onAgentMessage', function(e) {
        //console.log('chatKey: ' + e.liveAgentSessionKey);
        window.sessionStorage.setItem('chatKey', e.liveAgentSessionKey);
    });
    embedded_svc.addEventHandler('onChasitorMessage', function(e) {
        //console.log('chatKey: ' + e.liveAgentSessionKey);
        window.sessionStorage.setItem('chatKey', e.liveAgentSessionKey);
    });
    window.addEventListener('menu1' , function(event){
        console.log('event listener has received menu1 event');
        embedded_svc.postMessage('chasitor.sendMessage', event.detail.chasitorMessage);
        });
	//console.log(chatService[0].esAPIName);
	
	embedded_svc.init(
        //'https://evine--qa.my.salesforce.com',  //QA 
		//'https://qa-shophq.cs201.force.com',    //QA 
        //Prod
        'https://evine.my.salesforce.com',   //Prod
		'https://shophq.secure.force.com',   //Prod
		gslbBaseURL,
        //'00D7h0000004fUe',  //QA Org
        '00D40000000N1PC',   //Prod Org
		//'ShopHQ_Chat_Service', //ES Dev Name
		chatService[0].esAPIName, //ES Dev Name
		{
			baseLiveAgentContentURL: 'https://c.la3-c1cs-ia5.salesforceliveagent.com/content',
			deploymentId: '5723r000000blNW',
            //buttonId: '5737h000000GmeB', //QA
            buttonId: '5733r000000RsDV', //Prod
			baseLiveAgentURL: 'https://d.la3-c1cs-ia5.salesforceliveagent.com/chat',
			eswLiveAgentDevName: chatService[0].eswLiveAgentDevName, //ES Live Agent Dev Name
			isOfflineSupportEnabled: false
		}
	);
};

if (!window.embedded_svc) {
	var s = document.createElement('script');
	//QA 
    //s.setAttribute('src', 'https://evine--qa.my.salesforce.com/embeddedservice/5.0/esw.min.js');
    //Prod
    s.setAttribute('src', 'https://evine.my.salesforce.com/embeddedservice/5.0/esw.min.js');
	s.onload = function() {
		initESW(null);
	};
	document.body.appendChild(s);
} else {
	initESW('https://service.force.com');
}