
window.print = function() {
    try {
        window.webkit.messageHandlers.iCab.postMessage('print');
    } catch (err) {
    }
}

/*
Object.defineProperty(window, 'status', {
    get: function () {
        return "";
    },
    set: function (value) {
        window.webkit.messageHandlers.iCab.postMessage( {'status': value });
    }
});
*/

function iCab_LinkForElement(element) {
    try {
        while (element) {
            if (element.href) {
                return element
            }
            element = element.parentNode;
        }
    } catch (err) {
    }
    return null;
}

function iCab_StatusMessage(element, show) {
    try {
        element = iCab_LinkForElement(element);
        if (element && element.href) {
            window.webkit.messageHandlers.iCab.postMessage( {'status': (show ? element.href : '') });
        }
    } catch (err) {
    }
}

function iCab_InputMessage(element, inputType) {
    try {
        var data = {
            'input': element.value,
            'type': element.type,
            'name': element.name,
            'id': element.id,
            'inputType': inputType,
            'selectionStart': element.selectionStart,
            'selectionEnd': element.selectionEnd
        }
        document.iCab_CurrentInputElement = element
        window.top.webkit.messageHandlers.iCab.postMessage(data);
    } catch (err) {
    }
}

function iCab_AutoCompleteWith(text,start,end) {
    try {
        if (document.iCab_CurrentInputElement) {
            document.iCab_CurrentInputElement.value = text
            document.iCab_CurrentInputElement.setSelectionRange(start,end)
            document.iCab_CurrentInputElement = null
        } else {
            var frames = document.getElementsByTagName("IFRAME")
            if (frames && frames.length) {
                for (var i=0; i<frames.length; i++) {
                    try {
                        frames[i].contentWindow.iCab_AutoCompleteWith(text,start,end)
                    } catch (err) {
                    }
                }
            }
        }
    } catch (err) {
    }
}

function iCab_AutoCompleteReset() {
    try {
        if (document.iCab_CurrentInputElement) {
            document.iCab_CurrentInputElement = null
        } else {
            var frames = document.getElementsByTagName("IFRAME")
            if (frames && frames.length) {
                for (var i=0; i<frames.length; i++) {
                    try {
                        frames[i].contentWindow.iCab_AutoCompleteReset()
                    } catch (err) {
                    }
                }
            }
        }
    } catch (err) {
    }
}


function iCab_FocusEvent(element) {
    try {
        if (hasFillButton()) return
            
        var form = element.form
        var action = ""
        var elements
        var hasNameField = false
        var hasPasswordField = false
        if (form) {
            action = form.action
            elements = form.elements
        } else {
            elements = document.getElementsByTagName("INPUT")
        }
        if (elements) {
            for (var i=0; i<elements.length; i++) {
                var inputElement = elements[i]
                if (inputElement.tagName.toLowerCase() == "input") {
                    if (inputElement.disabled == false && (inputElement.type.toLowerCase() == "text" || inputElement.type.toLowerCase() == "email")) {
                        hasNameField = true
                    } else if (inputElement.type.toLowerCase() == "password") {
                        hasPasswordField = true
                    }
                }
            }
        }
        if (hasPasswordField) {
            document.iCab_FocussedInputElement = element
            document.iCab_FocussedFormAction = action
            window.top.webkit.messageHandlers.iCab.postMessage({ "form": (action ? action : "") });
        }
    } catch (err) {
    }
}

function iCab_DispatchKeyEvent(element,event) {
    try {
        var evt = element.ownerDocument.createEvent("KeyboardEvent");
        evt.initKeyboardEvent(event, true, false)
        element.dispatchEvent(evt)
    } catch (err) {
    }
}

function iCab_DispatchEvent(element,event,type) {
    try {
        var evt = element.ownerDocument.createEvent("HTMLEvents");
        evt.initEvent(event,true, false);
        element.dispatchEvent(evt)
    } catch (err) {
    }
}

function iCab_SimulateKeyPress(element) {
    try {
        iCab_DispatchKeyEvent(element,'keydown');
        iCab_DispatchKeyEvent(element,'keyup');
        iCab_DispatchKeyEvent(element,'keypress');
        iCab_DispatchEvent(element,'input');
        iCab_DispatchEvent(element,'change');
    } catch (err) {
    }
}

function iCab_fillElement(element, value) {
    try {
        element.focus()
        element.value = value
        iCab_SimulateKeyPress(element)
        element.blur()
    } catch (err) {
    }
}

function iCab_ElementBox(element) {
    try {
        let box = element.getBoundingClientRect();
        return { y: box.top + pageYOffset, x: box.left + pageXOffset, width:box.right - box.left, height: box.bottom - box.top };
    } catch (err) {
        return { x:0, y:0, width:0, height:0 }
    }
}


function hasFillButton() {
    return document.getElementById("iCab_FillFormButton") != null
}

function iCab_RequestFillForm(event) {
    try {
        var id = event.target.innerText
        var action = document.iCab_FocussedFormAction
        window.top.webkit.messageHandlers.iCab.postMessage({ "fillform": (action ? action : ""), "id":id });
        iCab_CloseFillForm()
    } catch (err) {
    }
}

function iCab_CloseFillForm() {
    try {
        var element = document.getElementById("iCab_FillFormButton")
        if (element) {
            element.parentNode.removeChild(element)
        }
        //document.iCab_FocussedInputElement = null
        //document.iCab_FocussedFormAction = null
    } catch (err) {
    }
}

function iCab_SaveForm() {
    try {
        if (document.iCab_FocussedInputElement) {
            var element = document.iCab_FocussedInputElement
            var action = document.iCab_FocussedFormAction
            var form = element.form
            var elements
            var name = ""
            var password = ""
            if (form) {
                elements = form.elements
            } else {
                elements = document.getElementsByTagName("INPUT")
            }
            if (elements) {
                for (var i=0; i<elements.length; i++) {
                    var inputElement = elements[i]
                    if (inputElement.tagName.toLowerCase() == "input") {
                        if (inputElement.disabled == false && (inputElement.type.toLowerCase() == "text" || inputElement.type.toLowerCase() == "email")) {
                            name = inputElement.value
                        } else if (inputElement.type.toLowerCase() == "password") {
                            password = inputElement.value
                        }
                    }
                }
            }
            window.top.webkit.messageHandlers.iCab.postMessage({ "saveform": (action ? action : ""), "name": (name ? name : ""), "password": (password ? password : "") });
            iCab_CloseFillForm()
        }
    } catch (err) {
    }
}


function iCab_MenuItem(clickHandler, title, normalcolor, highlightcolor) {
    var item = document.createElement("DIV");
    item.style = "font-size: 1em; text-align:center!important; border: 1px solid #aaa; margin: 0 -1px -1px -1px; padding: 5px 6px; background: "+normalcolor+";"
    item.onclick = clickHandler
    item.onmouseover = function() { this.style.backgroundColor = highlightcolor; this.style.cursor = "pointer" }
    item.onmouseout = function() { this.style.backgroundColor = normalcolor; this.style.cursor = "auto" }
    var text = document.createTextNode(title);
    item.appendChild(text)
    return  item;
}

function iCab_MarkFillForm(keys, saveTitle, accountsTitle) {
    try {
        if (document.iCab_FocussedInputElement) {
            if (hasFillButton() == false) {
                var element = document.iCab_FocussedInputElement
                var coord = iCab_ElementBox(document.iCab_FocussedInputElement)
                var titles = keys.split("|")
            
                var container = document.createElement("DIV");
                container.id = "iCab_FillFormButton"
                container.style = "border: 1px solid #aaa; position:absolute; display:block; top:" + (coord.y + coord.height + 4) + "px; left:" + coord.x + "px; font-size: small; text-align:center!important; z-index:999999; box-shadow:0 4px 10px 0 rgba(0,0,0,0.2), 0 4px 10px 0 rgba(0,0,0,0.2); background-color:#ffffff; min-width:" + coord.width + "px;";
                
                var item = document.createElement("DIV");
                item.style = "display:block;";
                var item2 = document.createElement("SPAN");
                item2.style = "display:inline-block; border: 1px solid #aaa; margin: -1px; padding: 0; background: #ffffff; width:2em; text-align:center!important; position:absolute; left:0;"
                item2.onclick = iCab_CloseFillForm
                item2.onmouseover = function() { this.style.backgroundColor = "#dddddd"; this.style.cursor = "pointer" }
                item2.onmouseout = function() { this.style.backgroundColor = "#ffffff"; this.style.cursor = "auto" }
                var text = document.createTextNode("⨉");
                item2.appendChild(text)
                item.appendChild(item2)
                var item2 = document.createElement("SPAN");
                item2.style = "display:inline-block; text-align:center!important; margin: -1px; padding: 0 36px;"
                var text = document.createTextNode(accountsTitle);
                item2.appendChild(text)
                item.appendChild(item2)
                container.appendChild(item)
                
                if (keys.length > 0) {
                    for (var i=0; i<titles.length; i++) {
                        var item = iCab_MenuItem(iCab_RequestFillForm, titles[i], "#eeeeee", "#bbbbbb")
                        container.appendChild(item)
                    }
                }
                var item = iCab_MenuItem(iCab_SaveForm, saveTitle, "#ffcccc", "#ddaaaa")
                container.appendChild(item)
            
                document.body.appendChild(container)
            }
        } else {
            var frames = document.getElementsByTagName("IFRAME")
            if (frames && frames.length) {
                for (var i=0; i<frames.length; i++) {
                    try {
                        frames[i].contentWindow.iCab_MarkFillForm(keys, saveTitle, accountsTitle)
                    } catch (err) {
                    }
                }
            }
        }
    } catch (err) {
    }
}


function iCab_KeyedFillFormValue(keys, key1, key2, key3) {
    try {
        for (var i=0; i<keys.length; i++) {
            var item = keys[i]
            if (key1 && item["key"] == key1 || key2 && item["key"] == key2 || key3 && item["key"] == key3) {
                return item["value"];
            }
        }
    } catch (err) {
    }
    return null
}

function iCab_KeyedFillForm(keys) {
    try {
        var elements = document.getElementsByTagName("INPUT")
        if (elements) {
            for (var i=0; i<elements.length; i++) {
                var inputElement = elements[i]
                if (inputElement.disabled == false && (inputElement.type.toLowerCase() == "text" || inputElement.type.toLowerCase() == "email" || inputElement.type.toLowerCase() == "number" || inputElement.type.toLowerCase() == "tel" || inputElement.type.toLowerCase() == "date" || inputElement.type.toLowerCase() == "time" || inputElement.type.toLowerCase() == "url" || inputElement.type.toLowerCase() == "week")) {
                    var value = null
                    if (inputElement.name || inputElement.id) {
                        value = iCab_KeyedFillFormValue(keys, inputElement.name, inputElement.id, inputElement.type)
                    }
                    if (value) {
                        iCab_fillElement(inputElement, value)
                    }
                }
            }
        }
        var frames = document.getElementsByTagName("IFRAME")
        if (frames && frames.length) {
            for (var i=0; i<frames.length; i++) {
                try {
                    frames[i].contentWindow.iCab_KeyedFillForm(keys)
                } catch (err) {
                }
            }
        }
    } catch (err) {
    }
}

function iCab_AutoFillForm(action, name, password) {
    try {
        var elements = null;
        if (action != "") {
            var forms = document.getElementsByTagName("FORM")
            for (var i=0; i<forms.length; i++) {
                var form = forms[i];
                var a = "" + form.action
                if (a.startsWith(action)) {
                    elements = form.elements
                    break
                }
            }
        } else {
            elements = document.getElementsByTagName("INPUT")
        }
        var finished = false;
        if (elements) {
            var nameField = null;
            var passwordField = null;
            for (var i=0; i<elements.length; i++) {
                var inputElement = elements[i]
                if (inputElement.tagName.toLowerCase() == "input") {
                    if (inputElement.disabled == false && (inputElement.type.toLowerCase() == "text" || inputElement.type.toLowerCase() == "email")) {
                        nameField = inputElement
                    } else if (inputElement.type.toLowerCase() == "password") {
                        passwordField = inputElement
                    }
                }
            }
            if (passwordField) {
                if (nameField) {
                    iCab_fillElement(nameField, name)
                }
                iCab_fillElement(passwordField, password)
                finished = true
            }
        }
        if (finished == false) {
            var frames = document.getElementsByTagName("IFRAME")
            if (frames && frames.length) {
                for (var i=0; i<frames.length; i++) {
                    try {
                        var result = frames[i].contentWindow.iCab_AutoFillForm(action, name, password)
                        if (result) {
                            return true;
                        }
                    } catch (err) {
                    }
                }
            }
            return false;
        } else {
            return true;
        }
    } catch (err) {
        return false;
    }
}


function iCab_GetAutoFillFormDataFrom(action, elements) {
    try {
        var nameField = null;
        var passwordField = null;
        for (var i=0; i<elements.length; i++) {
            var inputElement = elements[i]
            if (inputElement.tagName.toLowerCase() == "input") {
                if (inputElement.disabled == false && (inputElement.type.toLowerCase() == "text" || inputElement.type.toLowerCase() == "email")) {
                    nameField = inputElement
                } else if (inputElement.type.toLowerCase() == "password") {
                    passwordField = inputElement
                }
            }
        }
        if (passwordField) {
            var name = nameField ? nameField.value : ""
            var password = passwordField.value
            window.top.webkit.messageHandlers.iCab.postMessage({ "saveform": (action ? action : ""), "name": (name ? name : ""), "password": (password ? password : "") });
            return true
        }
    } catch (err) {
        return false;
    }
}

function iCab_GetAutoFillFormData() {
    try {
        var elements = null;
        var action = null;
        var finished = false;
        var forms = document.getElementsByTagName("FORM")
        for (var i=0; i<forms.length; i++) {
            var form = forms[i];
            action = form.action
            elements = form.elements
        }
        if (elements == null) {
            elements = document.getElementsByTagName("INPUT")
        }
        if (elements) {
            finished = iCab_GetAutoFillFormDataFrom(action ? action : "", elements)
        }
        if (finished == false) {
            var frames = document.getElementsByTagName("IFRAME")
            if (frames && frames.length) {
                for (var i=0; i<frames.length; i++) {
                    try {
                        var result = frames[i].contentWindow.iCab_GetAutoFillFormData()
                        if (result) {
                            return true;
                        }
                    } catch (err) {
                    }
                }
            }
            return false;
        } else {
            return true;
        }
    } catch (err) {
        return false;
    }
}


function iCab_FillForm(name, password) {
    try {
        if (document.iCab_FocussedInputElement) {
            var form = document.iCab_FocussedInputElement.form
            var elements
            if (form) {
                elements = form.elements
            } else {
                elements = document.getElementsByTagName("INPUT")
            }
            if (elements) {
                for (var i=0; i<elements.length; i++) {
                    var inputElement = elements[i]
                    if (inputElement.tagName.toLowerCase() == "input") {
                        if (inputElement.disabled == false && (inputElement.type.toLowerCase() == "text" || inputElement.type.toLowerCase() == "email")) {
                            iCab_fillElement(inputElement, name)
                        } else if (inputElement.type.toLowerCase() == "password") {
                            iCab_fillElement(inputElement, password)
                        }
                    }
                }
            }
        } else {
            var frames = document.getElementsByTagName("IFRAME")
            if (frames && frames.length) {
                for (var i=0; i<frames.length; i++) {
                    try {
                        frames[i].contentWindow.iCab_FillForm(name, password)
                    } catch (err) {
                    }
                }
            }
        }
    } catch (err) {
    }
}


function iCab_ClickHandler(element) {
    try {
        if (element.tagName.toLowerCase() == "input" && (element.type == "text" || element.type == "email" || element.type == "password")) {
            iCab_FocusEvent(element);
        }
        if (!(element.iCabHasInputHandler) && (element.type == "text" || element.type == "search" || element.type == "email" || element.type == "url")) {
            element.iCabHasInputHandler = true
            element.addEventListener('input',function(event) { iCab_InputMessage(event.target, event.inputType); });
        }
    } catch (err) {
    }
}

function iCab_SetupAtPageLoad(event) {
    try {
        var elements = document.getElementsByTagName("INPUT");
        for (var i=0; i<elements.length; i++) {
            var element = elements[i];
            if (!(element.iCabHasInputHandler) && (element.type == "text" || element.type == "search" || element.type == "email" || element.type == "url")) {
                element.iCabHasInputHandler = true
                element.addEventListener('input',function(event) { iCab_InputMessage(event.target, event.inputType); });
            }
        }
    } catch (err) {
    }
}


try {
    document.addEventListener('mouseover',function(event) { iCab_StatusMessage(event.target, true); });
    document.addEventListener('mouseout',function(event) { iCab_StatusMessage(event.target, false); });
    document.addEventListener('click',function(event) { iCab_ClickHandler(event.target); });

    window.addEventListener('load', function (event) { iCab_SetupAtPageLoad(event); });
} catch (err) {
}
