// This is to be used by the WKWebView in PersistencePrototype only.
// It assumes that this is loaded once the DOM itself is ready.

/**
 
 *extraStyles* placeholder is reserved by WebViewLoader for injecting any custom styles

 */

var resizeTimer = null;

window.onload = function () {

    //-- CSS Styles
    
    var styles = document.createElement("style");
    styles.textContent = ".dl-mail-quote {display: none;}\
    .dl-mail-quote .dl-mail-quote {display: block;}\
    body {margin: 0; padding: 0; -webkit-text-size-adjust: 100%; overflow-y: hidden}\
	::-webkit-scrollbar {display:none}\
    /*extraStyles*/";
    
    // we assume that head is available here (which will definitely be the case if content is passed through HTMLKit).
    var head = document.querySelector("head");
    head.appendChild(styles);

    
    //-- The real Javascript code

    // this check is not working as intended. So we do that weird trick of .insertBefore
     if (document.querySelector(".dl-mail-quote")) {
         hasHiddenQuotedText(true)
     }

	window.webkit.messageHandlers.loader.postMessage({content: document.body.outerHTML, width: document.body.scrollWidth, height: document.body.scrollHeight});

	var allSources = new Array();
	var images = document.getElementsByTagName('img');
	for(i=0; i<images.length; i++) {
        var sourceURL = images[i].src
        var mimepartnumber = images[i].getAttribute('data-dayliteoriginmimepartnumber');
        if(sourceURL.startsWith("cid:")) {

            if(mimepartnumber)
                sourceURL = sourceURL + "|" + mimepartnumber;

            allSources.push(sourceURL);
        }
        else {

            if(mimepartnumber)
                allSources.push(mimepartnumber);
        }
	}

	var objects = document.getElementsByTagName('object');
	for(i=0; i<objects.length; i++) {
        var sourceURL = objects[i].data
        var mimepartnumber = objects[i].getAttribute('data-dayliteoriginmimepartnumber');

        if(sourceURL.startsWith("cid:")) {

            if(mimepartnumber)
                sourceURL = sourceURL + "|" + mimepartnumber;

            allSources.push(sourceURL);
        }
        else {

            if(mimepartnumber)
                allSources.push(mimepartnumber);
        }
	}

	window.webkit.messageHandlers.loadImages.postMessage(allSources);

	document.addEventListener("click",clickedObject, false);

}

document.addEventListener('contextmenu', contextMenu, false);

function contextMenu(e) {
    e = e || window.event;
    var target = e.target;
    if(target.getAttribute('data-dayliteattachment') == 'yes') {
        var attribute = target.getAttribute("src");
        if(!attribute) {
            attribute = target.getAttribute("data");
        }

        var mimepartnumber = target.getAttribute('data-dayliteoriginmimepartnumber');
        if(mimepartnumber)
            attribute = attribute + "|" + mimepartnumber;

        window.webkit.messageHandlers.attachmentContextMenu.postMessage(attribute);
        e.preventDefault();
    }
}

function clickedObject(e) {
	e = e || window.event;
	var target = e.target;
	if(target.getAttribute('data-dayliteattachment') == 'yes') {
		var attribute = target.getAttribute("src");
		if(!attribute) {
			attribute = target.getAttribute("data");
		}

        var mimepartnumber = target.getAttribute('data-dayliteoriginmimepartnumber');
        if(mimepartnumber)
            attribute = attribute + "|" + mimepartnumber;

		window.webkit.messageHandlers.clickedObject.postMessage(attribute);
	}
}

function retryContent() {
	window.webkit.messageHandlers.reloadEmail.postMessage(null);
	return NO;
}

function showQuotes() {
    document.querySelector(".dl-mail-quote").style.display = "block";
    
    hasHiddenQuotedText(false)
    resizeWindow();
}


function resizeWindow() {
    var wrapperDiv = document.querySelector(".dl-mail-body-wrapper")

    if (wrapperDiv) {
        window.webkit.messageHandlers.sizeNotification.postMessage({width: wrapperDiv.scrollWidth, height: wrapperDiv.scrollHeight});
    }
    else {
        // fallback
        window.webkit.messageHandlers.sizeNotification.postMessage({width: document.body.scrollWidth, height: document.body.scrollHeight});
    }
}

function hasHiddenQuotedText(hidden) {
    window.webkit.messageHandlers.quotedText.postMessage({hiddenQuotedText: hidden});
}

function loadExtraIPadStyles(styles) {
    var styleTag = document.createElement("style");
    styleTag.textContent = styles;

    document.head.appendChild(styleTag);
}

function generateContentForIDs(IDsDictionaryData)
{
	var sDecodedParam = window.atob(IDsDictionaryData);
	var IDsDictionary = JSON.parse(sDecodedParam);

	var keys = Object.keys(IDsDictionary);
	for(var key of keys) {

		var keyDictionary = IDsDictionary[key];

		var newStyle = document.getElementById(key);
		if(!newStyle){
			newStyle = document.createElement('style');
			newStyle.setAttribute('class','dlImageStyling');
			newStyle.id = key;
			document.getElementsByTagName('head')[0].appendChild(newStyle);
		}

        var attributeKey = "src";
        var object = document.querySelector("["+attributeKey + "='"+key+"']");

		if(!object) {
            attributeKey = "data";
            object = document.querySelector("["+attributeKey + "='"+key+"']");
		}

        if(!object) {
            attributeKey = "data-dayliteoriginmimepartnumber";
            object = document.querySelector("["+attributeKey + "='"+key+"']");

            // if a style exists for the real contentID (so same object), skip this definition
            if(object) {
                var realContentID = object.getAttribute("data");
                if(!realContentID) {
                    realContentID = object.getAttribute("src");
                }

                if(realContentID) {
                    var existingStyle = document.querySelector("style[id='"+realContentID+"']");
                    if(existingStyle) {
                        object = NULL;
                    }
                }
            }
        }

        if(!object)
            return;

		var mimeType = "";
		if(keyDictionary["mimeType"])
			mimeType = keyDictionary['mimeType'];

		var dimensions = "";
		if(keyDictionary['isPlaceholder'])
			dimensions = "width:250px;height:56px;";

		var hoverData = null;
		if(keyDictionary['dataHover'])
			hoverData = keyDictionary['dataHover'];

        var innerHTMLString = object.tagName.toLowerCase()+"["+attributeKey+"='"+key+"']{"+dimensions+"content:url('data:"+mimeType+";base64,"+keyDictionary['data']+"')}";
        if(hoverData)
            innerHTMLString = innerHTMLString + object.tagName.toLowerCase() + "["+attributeKey+"='"+key+"']:hover {"+dimensions+"content:url('data:"+mimeType+";base64,"+hoverData+"')}";

        if(mimeType.length)
            object.type = mimeType;

		newStyle.innerHTML = innerHTMLString;
	}
}
