safari.self.addEventListener("message", extensionMessageHandler, false);
window.addEventListener('ac-message',webPageMessageHandler);
document.addEventListener("DOMContentLoaded", function(event) {
                          if(document.contentType == "text/html") {
                          domLoaded = true;
                          if(!pageModified && version != null) {
                            modifyPage();
                          }
                          }
                          });

var domLoaded = false;
var authenticationInProgress = false;
var version = {major:2,minor:9,fix:"9.7"};
var pageModified = false;
let pageURL = window.location.href;

function modifyPage() {
    var script = document.createElement('script');
    script.textContent = 'var acExtension = {version:{minor:'+version.minor+',major:'+version.major+',fix:'+version.fix+'}}';
    document.documentElement.appendChild(script);
    pageModified = true;
}

function webPageMessageHandler(event) {
    
    if(event.detail.method  == "authenticate") {
        if(event.detail.method == "authenticate") {
            extensionKeepAlive();
        }
        safari.extension.dispatchMessage(event.detail.method,event.detail.parameters);
    }
}

function extensionMessageHandler(event) {
    if(document.contentType == "text/html") {
        if(event.name == "init-response") {
            version = event.message.version;
            if(!pageModified && domLoaded) {
                modifyPage();
            }
        } else if (event.name == "authenticate-response") {
            stopKeepAlive();
            if (event.message.url == pageURL) {
                var responseEvent = new CustomEvent("ac-message-authenticate-response",{detail:event.message});
                window.dispatchEvent(responseEvent);
            }
        } else if(event.name == "heartbit-response") {
            var responseEvent = new CustomEvent("ac-message-keep-alive-response",{detail:event.message});
            window.dispatchEvent(responseEvent);
        } else if(event.name == "invalid-response"){
            var responseEvent = new CustomEvent("ac-message-invalid-response",{detail:event.message});
            window.dispatchEvent(responseEvent);
        }
    }
}


function extensionKeepAlive() {
    authenticationInProgress = true;
    keepSendingKeepAliveMessage(10000);
}

function keepSendingKeepAliveMessage (time) {
    
    if(authenticationInProgress) {
        
        safari.extension.dispatchMessage("keep-alive",{});
        
        setTimeout(function(){
                   keepSendingKeepAliveMessage(time);
                   },time);
    }
    
}


function stopKeepAlive() {
    authenticationInProgress = false;
}

function onDOMLoaded() {
    
}


