cycleThroughFrames();

function replaceTheNode(frameID, nodeID, newHtm){
	if (frameID == 'M'){
		var anode = document.getElementById(nodeID);
	}
	else
	{
		var anode = top.frames[frameID].document.getElementById(nodeID);
	}
	if (anode){
		anode.innerHTML = newHtm;
	}
}

function cycleThroughFrames(){
    if (window.top === window.self) {
		sendToAccord('M');
    } else if (window.frameElement){
    	sendToAccord(window.frameElement.id);
    }
}

function sendToAccord(frameID) {
	if (frameID == 'M'){
		var theNodes = document.body.querySelectorAll('p,h1,h2,h3,h4,h5,h6,li,span,div,tr');
	}
	else
	{
		var theNodes = document.body.querySelectorAll('p,h1,h2,h3,h4,h5,h6,li,span,tr');
	}
	var counter = 100;
    for (var i = theNodes.length-1; i >= 0; i--) {
        if (sendNodeToAccord(theNodes[i])){
        	if (theNodes[i].id == ''){
        		theNodes[i].id = 'OT.' + frameID + '.' + counter++;
        	}
        	window.webkit.messageHandlers.%@.postMessage({theFrame: frameID, theIndex: theNodes[i].id, theText: theNodes[i].innerHTML});
        }
    }
}

function hovRef(vNum,fstVs,lstVs) {
	window.webkit.messageHandlers.%@.postMessage({'webview.hyper.versionNum LONGINT': vNum, 'webview.hyper.firstVerse LONGINT': fstVs, 'webview.hyper.lastVerse LONGINT': lstVs});
}

function clkRef() {
	window.webkit.messageHandlers.%@.postMessage('');
}

function clearRef() {
	window.webkit.messageHandlers.%@.postMessage('');
}

function sendNodeToAccord(aNode){
    var doSend = (('innerText' in aNode) && (aNode.innerText.length > 2));
    if (doSend)
        doSend = nodeHasOwnText(aNode);
    return doSend;
}

function nodeHasOwnText(aNode) {
    var childTextLength = 0;
    for (var i = 0; i < aNode.children.length; i++) {
        childTextLength += aNode.children[i].textContent.length;
    }
    var hasText = (aNode.textContent.length > childTextLength)
    return hasText;
}

function getSelectionAndSendMessage() {
	var top = 0;
	var bot = 0;
	var lef = 0;
	var rit = 0;
    var txt = "";
    if (document.getSelection()){
   		txt = document.getSelection().toString();
   	 	var ran = window.getSelection().getRangeAt(0);
    	if (ran){
    		var rect = ran.getBoundingClientRect();
    		top = rect.top;
			bot = rect.bottom;
			lef = rect.left;
			rit = rect.right;
    	}
    }
    window.webkit.messageHandlers.%@.postMessage({theText: txt, t: top, b: bot, l: lef, r: rit});
}

document.onmouseup = getSelectionAndSendMessage;
document.onkeyup = getSelectionAndSendMessage;
document.oncontextmenu = getSelectionAndSendMessage;
document.onscroll = getSelectionAndSendMessage;